UNPKG

908 kBJavaScriptView Raw
1/** @license React v16.9.0-alpha.0
2 * react-dom-unstable-fire.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactFire = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18// 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// This is just to get the setup running.
9973// TODO: real implementation.
9974// console.log('Hello from Fire host config.');
9975
9976// Prefix measurements so that it's possible to filter them.
9977// Longer prefixes are hard to read in DevTools.
9978var reactEmoji = '\u269B';
9979var warningEmoji = '\u26D4';
9980var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
9981
9982// Keep track of current fiber so that we know the path to unwind on pause.
9983// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
9984var currentFiber = null;
9985// If we're in the middle of user code, which fiber and method is it?
9986// Reusing `currentFiber` would be confusing for this because user code fiber
9987// can change during commit phase too, but we don't need to unwind it (since
9988// lifecycles in the commit phase don't resemble a tree).
9989var currentPhase = null;
9990var currentPhaseFiber = null;
9991// Did lifecycle hook schedule an update? This is often a performance problem,
9992// so we will keep track of it, and include it in the report.
9993// Track commits caused by cascading updates.
9994var isCommitting = false;
9995var hasScheduledUpdateInCurrentCommit = false;
9996var hasScheduledUpdateInCurrentPhase = false;
9997var commitCountInCurrentWorkLoop = 0;
9998var effectCountInCurrentCommit = 0;
9999var isWaitingForCallback = false;
10000// During commits, we only show a measurement once per method name
10001// to avoid stretch the commit phase with measurement overhead.
10002var labelsInCurrentCommit = new Set();
10003
10004var formatMarkName = function (markName) {
10005 return reactEmoji + ' ' + markName;
10006};
10007
10008var formatLabel = function (label, warning) {
10009 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
10010 var suffix = warning ? ' Warning: ' + warning : '';
10011 return '' + prefix + label + suffix;
10012};
10013
10014var beginMark = function (markName) {
10015 performance.mark(formatMarkName(markName));
10016};
10017
10018var clearMark = function (markName) {
10019 performance.clearMarks(formatMarkName(markName));
10020};
10021
10022var endMark = function (label, markName, warning) {
10023 var formattedMarkName = formatMarkName(markName);
10024 var formattedLabel = formatLabel(label, warning);
10025 try {
10026 performance.measure(formattedLabel, formattedMarkName);
10027 } catch (err) {}
10028 // If previous mark was missing for some reason, this will throw.
10029 // This could only happen if React crashed in an unexpected place earlier.
10030 // Don't pile on with more errors.
10031
10032 // Clear marks immediately to avoid growing buffer.
10033 performance.clearMarks(formattedMarkName);
10034 performance.clearMeasures(formattedLabel);
10035};
10036
10037var getFiberMarkName = function (label, debugID) {
10038 return label + ' (#' + debugID + ')';
10039};
10040
10041var getFiberLabel = function (componentName, isMounted, phase) {
10042 if (phase === null) {
10043 // These are composite component total time measurements.
10044 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
10045 } else {
10046 // Composite component methods.
10047 return componentName + '.' + phase;
10048 }
10049};
10050
10051var beginFiberMark = function (fiber, phase) {
10052 var componentName = getComponentName(fiber.type) || 'Unknown';
10053 var debugID = fiber._debugID;
10054 var isMounted = fiber.alternate !== null;
10055 var label = getFiberLabel(componentName, isMounted, phase);
10056
10057 if (isCommitting && labelsInCurrentCommit.has(label)) {
10058 // During the commit phase, we don't show duplicate labels because
10059 // there is a fixed overhead for every measurement, and we don't
10060 // want to stretch the commit phase beyond necessary.
10061 return false;
10062 }
10063 labelsInCurrentCommit.add(label);
10064
10065 var markName = getFiberMarkName(label, debugID);
10066 beginMark(markName);
10067 return true;
10068};
10069
10070var clearFiberMark = function (fiber, phase) {
10071 var componentName = getComponentName(fiber.type) || 'Unknown';
10072 var debugID = fiber._debugID;
10073 var isMounted = fiber.alternate !== null;
10074 var label = getFiberLabel(componentName, isMounted, phase);
10075 var markName = getFiberMarkName(label, debugID);
10076 clearMark(markName);
10077};
10078
10079var endFiberMark = function (fiber, phase, warning) {
10080 var componentName = getComponentName(fiber.type) || 'Unknown';
10081 var debugID = fiber._debugID;
10082 var isMounted = fiber.alternate !== null;
10083 var label = getFiberLabel(componentName, isMounted, phase);
10084 var markName = getFiberMarkName(label, debugID);
10085 endMark(label, markName, warning);
10086};
10087
10088var shouldIgnoreFiber = function (fiber) {
10089 // Host components should be skipped in the timeline.
10090 // We could check typeof fiber.type, but does this work with RN?
10091 switch (fiber.tag) {
10092 case HostRoot:
10093 case HostComponent:
10094 case HostText:
10095 case HostPortal:
10096 case Fragment:
10097 case ContextProvider:
10098 case ContextConsumer:
10099 case Mode:
10100 return true;
10101 default:
10102 return false;
10103 }
10104};
10105
10106var clearPendingPhaseMeasurement = function () {
10107 if (currentPhase !== null && currentPhaseFiber !== null) {
10108 clearFiberMark(currentPhaseFiber, currentPhase);
10109 }
10110 currentPhaseFiber = null;
10111 currentPhase = null;
10112 hasScheduledUpdateInCurrentPhase = false;
10113};
10114
10115var pauseTimers = function () {
10116 // Stops all currently active measurements so that they can be resumed
10117 // if we continue in a later deferred loop from the same unit of work.
10118 var fiber = currentFiber;
10119 while (fiber) {
10120 if (fiber._debugIsCurrentlyTiming) {
10121 endFiberMark(fiber, null, null);
10122 }
10123 fiber = fiber.return;
10124 }
10125};
10126
10127var resumeTimersRecursively = function (fiber) {
10128 if (fiber.return !== null) {
10129 resumeTimersRecursively(fiber.return);
10130 }
10131 if (fiber._debugIsCurrentlyTiming) {
10132 beginFiberMark(fiber, null);
10133 }
10134};
10135
10136var resumeTimers = function () {
10137 // Resumes all measurements that were active during the last deferred loop.
10138 if (currentFiber !== null) {
10139 resumeTimersRecursively(currentFiber);
10140 }
10141};
10142
10143function recordEffect() {
10144 if (enableUserTimingAPI) {
10145 effectCountInCurrentCommit++;
10146 }
10147}
10148
10149function recordScheduleUpdate() {
10150 if (enableUserTimingAPI) {
10151 if (isCommitting) {
10152 hasScheduledUpdateInCurrentCommit = true;
10153 }
10154 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
10155 hasScheduledUpdateInCurrentPhase = true;
10156 }
10157 }
10158}
10159
10160function startRequestCallbackTimer() {
10161 if (enableUserTimingAPI) {
10162 if (supportsUserTiming && !isWaitingForCallback) {
10163 isWaitingForCallback = true;
10164 beginMark('(Waiting for async callback...)');
10165 }
10166 }
10167}
10168
10169function stopRequestCallbackTimer(didExpire, expirationTime) {
10170 if (enableUserTimingAPI) {
10171 if (supportsUserTiming) {
10172 isWaitingForCallback = false;
10173 var warning = didExpire ? 'React was blocked by main thread' : null;
10174 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
10175 }
10176 }
10177}
10178
10179function startWorkTimer(fiber) {
10180 if (enableUserTimingAPI) {
10181 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10182 return;
10183 }
10184 // If we pause, this is the fiber to unwind from.
10185 currentFiber = fiber;
10186 if (!beginFiberMark(fiber, null)) {
10187 return;
10188 }
10189 fiber._debugIsCurrentlyTiming = true;
10190 }
10191}
10192
10193function cancelWorkTimer(fiber) {
10194 if (enableUserTimingAPI) {
10195 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10196 return;
10197 }
10198 // Remember we shouldn't complete measurement for this fiber.
10199 // Otherwise flamechart will be deep even for small updates.
10200 fiber._debugIsCurrentlyTiming = false;
10201 clearFiberMark(fiber, null);
10202 }
10203}
10204
10205function stopWorkTimer(fiber) {
10206 if (enableUserTimingAPI) {
10207 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10208 return;
10209 }
10210 // If we pause, its parent is the fiber to unwind from.
10211 currentFiber = fiber.return;
10212 if (!fiber._debugIsCurrentlyTiming) {
10213 return;
10214 }
10215 fiber._debugIsCurrentlyTiming = false;
10216 endFiberMark(fiber, null, null);
10217 }
10218}
10219
10220function stopFailedWorkTimer(fiber) {
10221 if (enableUserTimingAPI) {
10222 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
10223 return;
10224 }
10225 // If we pause, its parent is the fiber to unwind from.
10226 currentFiber = fiber.return;
10227 if (!fiber._debugIsCurrentlyTiming) {
10228 return;
10229 }
10230 fiber._debugIsCurrentlyTiming = false;
10231 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
10232 endFiberMark(fiber, null, warning);
10233 }
10234}
10235
10236function startPhaseTimer(fiber, phase) {
10237 if (enableUserTimingAPI) {
10238 if (!supportsUserTiming) {
10239 return;
10240 }
10241 clearPendingPhaseMeasurement();
10242 if (!beginFiberMark(fiber, phase)) {
10243 return;
10244 }
10245 currentPhaseFiber = fiber;
10246 currentPhase = phase;
10247 }
10248}
10249
10250function stopPhaseTimer() {
10251 if (enableUserTimingAPI) {
10252 if (!supportsUserTiming) {
10253 return;
10254 }
10255 if (currentPhase !== null && currentPhaseFiber !== null) {
10256 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
10257 endFiberMark(currentPhaseFiber, currentPhase, warning);
10258 }
10259 currentPhase = null;
10260 currentPhaseFiber = null;
10261 }
10262}
10263
10264function startWorkLoopTimer(nextUnitOfWork) {
10265 if (enableUserTimingAPI) {
10266 currentFiber = nextUnitOfWork;
10267 if (!supportsUserTiming) {
10268 return;
10269 }
10270 commitCountInCurrentWorkLoop = 0;
10271 // This is top level call.
10272 // Any other measurements are performed within.
10273 beginMark('(React Tree Reconciliation)');
10274 // Resume any measurements that were in progress during the last loop.
10275 resumeTimers();
10276 }
10277}
10278
10279function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
10280 if (enableUserTimingAPI) {
10281 if (!supportsUserTiming) {
10282 return;
10283 }
10284 var warning = null;
10285 if (interruptedBy !== null) {
10286 if (interruptedBy.tag === HostRoot) {
10287 warning = 'A top-level update interrupted the previous render';
10288 } else {
10289 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
10290 warning = 'An update to ' + componentName + ' interrupted the previous render';
10291 }
10292 } else if (commitCountInCurrentWorkLoop > 1) {
10293 warning = 'There were cascading updates';
10294 }
10295 commitCountInCurrentWorkLoop = 0;
10296 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
10297 // Pause any measurements until the next loop.
10298 pauseTimers();
10299 endMark(label, '(React Tree Reconciliation)', warning);
10300 }
10301}
10302
10303function startCommitTimer() {
10304 if (enableUserTimingAPI) {
10305 if (!supportsUserTiming) {
10306 return;
10307 }
10308 isCommitting = true;
10309 hasScheduledUpdateInCurrentCommit = false;
10310 labelsInCurrentCommit.clear();
10311 beginMark('(Committing Changes)');
10312 }
10313}
10314
10315function stopCommitTimer() {
10316 if (enableUserTimingAPI) {
10317 if (!supportsUserTiming) {
10318 return;
10319 }
10320
10321 var warning = null;
10322 if (hasScheduledUpdateInCurrentCommit) {
10323 warning = 'Lifecycle hook scheduled a cascading update';
10324 } else if (commitCountInCurrentWorkLoop > 0) {
10325 warning = 'Caused by a cascading update in earlier commit';
10326 }
10327 hasScheduledUpdateInCurrentCommit = false;
10328 commitCountInCurrentWorkLoop++;
10329 isCommitting = false;
10330 labelsInCurrentCommit.clear();
10331
10332 endMark('(Committing Changes)', '(Committing Changes)', warning);
10333 }
10334}
10335
10336function startCommitSnapshotEffectsTimer() {
10337 if (enableUserTimingAPI) {
10338 if (!supportsUserTiming) {
10339 return;
10340 }
10341 effectCountInCurrentCommit = 0;
10342 beginMark('(Committing Snapshot Effects)');
10343 }
10344}
10345
10346function stopCommitSnapshotEffectsTimer() {
10347 if (enableUserTimingAPI) {
10348 if (!supportsUserTiming) {
10349 return;
10350 }
10351 var count = effectCountInCurrentCommit;
10352 effectCountInCurrentCommit = 0;
10353 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
10354 }
10355}
10356
10357function startCommitHostEffectsTimer() {
10358 if (enableUserTimingAPI) {
10359 if (!supportsUserTiming) {
10360 return;
10361 }
10362 effectCountInCurrentCommit = 0;
10363 beginMark('(Committing Host Effects)');
10364 }
10365}
10366
10367function stopCommitHostEffectsTimer() {
10368 if (enableUserTimingAPI) {
10369 if (!supportsUserTiming) {
10370 return;
10371 }
10372 var count = effectCountInCurrentCommit;
10373 effectCountInCurrentCommit = 0;
10374 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
10375 }
10376}
10377
10378function startCommitLifeCyclesTimer() {
10379 if (enableUserTimingAPI) {
10380 if (!supportsUserTiming) {
10381 return;
10382 }
10383 effectCountInCurrentCommit = 0;
10384 beginMark('(Calling Lifecycle Methods)');
10385 }
10386}
10387
10388function stopCommitLifeCyclesTimer() {
10389 if (enableUserTimingAPI) {
10390 if (!supportsUserTiming) {
10391 return;
10392 }
10393 var count = effectCountInCurrentCommit;
10394 effectCountInCurrentCommit = 0;
10395 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
10396 }
10397}
10398
10399var valueStack = [];
10400
10401var fiberStack = void 0;
10402
10403{
10404 fiberStack = [];
10405}
10406
10407var index = -1;
10408
10409function createCursor(defaultValue) {
10410 return {
10411 current: defaultValue
10412 };
10413}
10414
10415function pop(cursor, fiber) {
10416 if (index < 0) {
10417 {
10418 warningWithoutStack$1(false, 'Unexpected pop.');
10419 }
10420 return;
10421 }
10422
10423 {
10424 if (fiber !== fiberStack[index]) {
10425 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
10426 }
10427 }
10428
10429 cursor.current = valueStack[index];
10430
10431 valueStack[index] = null;
10432
10433 {
10434 fiberStack[index] = null;
10435 }
10436
10437 index--;
10438}
10439
10440function push(cursor, value, fiber) {
10441 index++;
10442
10443 valueStack[index] = cursor.current;
10444
10445 {
10446 fiberStack[index] = fiber;
10447 }
10448
10449 cursor.current = value;
10450}
10451
10452function checkThatStackIsEmpty() {
10453 {
10454 if (index !== -1) {
10455 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
10456 }
10457 }
10458}
10459
10460function resetStackAfterFatalErrorInDev() {
10461 {
10462 index = -1;
10463 valueStack.length = 0;
10464 fiberStack.length = 0;
10465 }
10466}
10467
10468var warnedAboutMissingGetChildContext = void 0;
10469
10470{
10471 warnedAboutMissingGetChildContext = {};
10472}
10473
10474var emptyContextObject = {};
10475{
10476 Object.freeze(emptyContextObject);
10477}
10478
10479// A cursor to the current merged context object on the stack.
10480var contextStackCursor = createCursor(emptyContextObject);
10481// A cursor to a boolean indicating whether the context has changed.
10482var didPerformWorkStackCursor = createCursor(false);
10483// Keep track of the previous context object that was on the stack.
10484// We use this to get access to the parent context after we have already
10485// pushed the next context provider, and now need to merge their contexts.
10486var previousContext = emptyContextObject;
10487
10488function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
10489 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
10490 // If the fiber is a context provider itself, when we read its context
10491 // we may have already pushed its own child context on the stack. A context
10492 // provider should not "see" its own child context. Therefore we read the
10493 // previous (parent) context instead for a context provider.
10494 return previousContext;
10495 }
10496 return contextStackCursor.current;
10497}
10498
10499function cacheContext(workInProgress, unmaskedContext, maskedContext) {
10500 var instance = workInProgress.stateNode;
10501 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
10502 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
10503}
10504
10505function getMaskedContext(workInProgress, unmaskedContext) {
10506 var type = workInProgress.type;
10507 var contextTypes = type.contextTypes;
10508 if (!contextTypes) {
10509 return emptyContextObject;
10510 }
10511
10512 // Avoid recreating masked context unless unmasked context has changed.
10513 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
10514 // This may trigger infinite loops if componentWillReceiveProps calls setState.
10515 var instance = workInProgress.stateNode;
10516 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
10517 return instance.__reactInternalMemoizedMaskedChildContext;
10518 }
10519
10520 var context = {};
10521 for (var key in contextTypes) {
10522 context[key] = unmaskedContext[key];
10523 }
10524
10525 {
10526 var name = getComponentName(type) || 'Unknown';
10527 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
10528 }
10529
10530 // Cache unmasked context so we can avoid recreating masked context unless necessary.
10531 // Context is created before the class component is instantiated so check for instance.
10532 if (instance) {
10533 cacheContext(workInProgress, unmaskedContext, context);
10534 }
10535
10536 return context;
10537}
10538
10539function hasContextChanged() {
10540 return didPerformWorkStackCursor.current;
10541}
10542
10543function isContextProvider(type) {
10544 var childContextTypes = type.childContextTypes;
10545 return childContextTypes !== null && childContextTypes !== undefined;
10546}
10547
10548function popContext(fiber) {
10549 pop(didPerformWorkStackCursor, fiber);
10550 pop(contextStackCursor, fiber);
10551}
10552
10553function popTopLevelContextObject(fiber) {
10554 pop(didPerformWorkStackCursor, fiber);
10555 pop(contextStackCursor, fiber);
10556}
10557
10558function pushTopLevelContextObject(fiber, context, didChange) {
10559 (function () {
10560 if (!(contextStackCursor.current === emptyContextObject)) {
10561 {
10562 throw ReactError('Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.');
10563 }
10564 }
10565 })();
10566
10567 push(contextStackCursor, context, fiber);
10568 push(didPerformWorkStackCursor, didChange, fiber);
10569}
10570
10571function processChildContext(fiber, type, parentContext) {
10572 var instance = fiber.stateNode;
10573 var childContextTypes = type.childContextTypes;
10574
10575 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
10576 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
10577 if (typeof instance.getChildContext !== 'function') {
10578 {
10579 var componentName = getComponentName(type) || 'Unknown';
10580
10581 if (!warnedAboutMissingGetChildContext[componentName]) {
10582 warnedAboutMissingGetChildContext[componentName] = true;
10583 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);
10584 }
10585 }
10586 return parentContext;
10587 }
10588
10589 var childContext = void 0;
10590 {
10591 setCurrentPhase('getChildContext');
10592 }
10593 startPhaseTimer(fiber, 'getChildContext');
10594 childContext = instance.getChildContext();
10595 stopPhaseTimer();
10596 {
10597 setCurrentPhase(null);
10598 }
10599 for (var contextKey in childContext) {
10600 (function () {
10601 if (!(contextKey in childContextTypes)) {
10602 {
10603 throw ReactError((getComponentName(type) || 'Unknown') + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
10604 }
10605 }
10606 })();
10607 }
10608 {
10609 var name = getComponentName(type) || 'Unknown';
10610 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
10611 // In practice, there is one case in which we won't get a stack. It's when
10612 // somebody calls unstable_renderSubtreeIntoContainer() and we process
10613 // context from the parent component instance. The stack will be missing
10614 // because it's outside of the reconciliation, and so the pointer has not
10615 // been set. This is rare and doesn't matter. We'll also remove that API.
10616 getCurrentFiberStackInDev);
10617 }
10618
10619 return _assign({}, parentContext, childContext);
10620}
10621
10622function pushContextProvider(workInProgress) {
10623 var instance = workInProgress.stateNode;
10624 // We push the context as early as possible to ensure stack integrity.
10625 // If the instance does not exist yet, we will push null at first,
10626 // and replace it on the stack later when invalidating the context.
10627 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
10628
10629 // Remember the parent context so we can merge with it later.
10630 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
10631 previousContext = contextStackCursor.current;
10632 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
10633 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
10634
10635 return true;
10636}
10637
10638function invalidateContextProvider(workInProgress, type, didChange) {
10639 var instance = workInProgress.stateNode;
10640 (function () {
10641 if (!instance) {
10642 {
10643 throw ReactError('Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.');
10644 }
10645 }
10646 })();
10647
10648 if (didChange) {
10649 // Merge parent and own context.
10650 // Skip this if we're not updating due to sCU.
10651 // This avoids unnecessarily recomputing memoized values.
10652 var mergedContext = processChildContext(workInProgress, type, previousContext);
10653 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
10654
10655 // Replace the old (or empty) context with the new one.
10656 // It is important to unwind the context in the reverse order.
10657 pop(didPerformWorkStackCursor, workInProgress);
10658 pop(contextStackCursor, workInProgress);
10659 // Now push the new context and mark that it has changed.
10660 push(contextStackCursor, mergedContext, workInProgress);
10661 push(didPerformWorkStackCursor, didChange, workInProgress);
10662 } else {
10663 pop(didPerformWorkStackCursor, workInProgress);
10664 push(didPerformWorkStackCursor, didChange, workInProgress);
10665 }
10666}
10667
10668function findCurrentUnmaskedContext(fiber) {
10669 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
10670 // makes sense elsewhere
10671 (function () {
10672 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
10673 {
10674 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.');
10675 }
10676 }
10677 })();
10678
10679 var node = fiber;
10680 do {
10681 switch (node.tag) {
10682 case HostRoot:
10683 return node.stateNode.context;
10684 case ClassComponent:
10685 {
10686 var Component = node.type;
10687 if (isContextProvider(Component)) {
10688 return node.stateNode.__reactInternalMemoizedMergedChildContext;
10689 }
10690 break;
10691 }
10692 }
10693 node = node.return;
10694 } while (node !== null);
10695 (function () {
10696 {
10697 {
10698 throw ReactError('Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
10699 }
10700 }
10701 })();
10702}
10703
10704var onCommitFiberRoot = null;
10705var onCommitFiberUnmount = null;
10706var hasLoggedError = false;
10707
10708function catchErrors(fn) {
10709 return function (arg) {
10710 try {
10711 return fn(arg);
10712 } catch (err) {
10713 if (true && !hasLoggedError) {
10714 hasLoggedError = true;
10715 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
10716 }
10717 }
10718 };
10719}
10720
10721var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
10722
10723function injectInternals(internals) {
10724 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
10725 // No DevTools
10726 return false;
10727 }
10728 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
10729 if (hook.isDisabled) {
10730 // This isn't a real property on the hook, but it can be set to opt out
10731 // of DevTools integration and associated warnings and logs.
10732 // https://github.com/facebook/react/issues/3877
10733 return true;
10734 }
10735 if (!hook.supportsFiber) {
10736 {
10737 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');
10738 }
10739 // DevTools exists, even though it doesn't support Fiber.
10740 return true;
10741 }
10742 try {
10743 var rendererID = hook.inject(internals);
10744 // We have successfully injected, so now it is safe to set up hooks.
10745 onCommitFiberRoot = catchErrors(function (root) {
10746 return hook.onCommitFiberRoot(rendererID, root);
10747 });
10748 onCommitFiberUnmount = catchErrors(function (fiber) {
10749 return hook.onCommitFiberUnmount(rendererID, fiber);
10750 });
10751 } catch (err) {
10752 // Catch all errors because it is unsafe to throw during initialization.
10753 {
10754 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
10755 }
10756 }
10757 // DevTools exists
10758 return true;
10759}
10760
10761function onCommitRoot(root) {
10762 if (typeof onCommitFiberRoot === 'function') {
10763 onCommitFiberRoot(root);
10764 }
10765}
10766
10767function onCommitUnmount(fiber) {
10768 if (typeof onCommitFiberUnmount === 'function') {
10769 onCommitFiberUnmount(fiber);
10770 }
10771}
10772
10773// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
10774// Math.pow(2, 30) - 1
10775// 0b111111111111111111111111111111
10776var maxSigned31BitInt = 1073741823;
10777
10778// Intentionally not named imports because Rollup would use dynamic dispatch for
10779// CommonJS interop named imports.
10780var Scheduler_runWithPriority = unstable_runWithPriority;
10781var Scheduler_scheduleCallback = unstable_scheduleCallback;
10782var Scheduler_cancelCallback = unstable_cancelCallback;
10783var Scheduler_shouldYield = unstable_shouldYield;
10784var Scheduler_now = unstable_now;
10785var Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
10786var Scheduler_ImmediatePriority = unstable_ImmediatePriority;
10787var Scheduler_UserBlockingPriority = unstable_UserBlockingPriority;
10788var Scheduler_NormalPriority = unstable_NormalPriority;
10789var Scheduler_LowPriority = unstable_LowPriority;
10790var Scheduler_IdlePriority = unstable_IdlePriority;
10791
10792
10793var fakeCallbackNode = {};
10794
10795// Except for NoPriority, these correspond to Scheduler priorities. We use
10796// ascending numbers so we can compare them like numbers. They start at 90 to
10797// avoid clashing with Scheduler's priorities.
10798var ImmediatePriority = 99;
10799var UserBlockingPriority = 98;
10800var NormalPriority = 97;
10801var LowPriority = 96;
10802var IdlePriority = 95;
10803// NoPriority is the absence of priority. Also React-only.
10804
10805
10806var now$1 = Scheduler_now;
10807var shouldYield$1 = disableYielding ? function () {
10808 return false;
10809} // Never yield when `disableYielding` is on
10810: Scheduler_shouldYield;
10811
10812var immediateQueue = null;
10813var immediateQueueCallbackNode = null;
10814var isFlushingImmediate = false;
10815
10816function getCurrentPriorityLevel() {
10817 switch (Scheduler_getCurrentPriorityLevel()) {
10818 case Scheduler_ImmediatePriority:
10819 return ImmediatePriority;
10820 case Scheduler_UserBlockingPriority:
10821 return UserBlockingPriority;
10822 case Scheduler_NormalPriority:
10823 return NormalPriority;
10824 case Scheduler_LowPriority:
10825 return LowPriority;
10826 case Scheduler_IdlePriority:
10827 return IdlePriority;
10828 default:
10829 (function () {
10830 {
10831 {
10832 throw ReactError('Unknown priority level.');
10833 }
10834 }
10835 })();
10836 }
10837}
10838
10839function reactPriorityToSchedulerPriority(reactPriorityLevel) {
10840 switch (reactPriorityLevel) {
10841 case ImmediatePriority:
10842 return Scheduler_ImmediatePriority;
10843 case UserBlockingPriority:
10844 return Scheduler_UserBlockingPriority;
10845 case NormalPriority:
10846 return Scheduler_NormalPriority;
10847 case LowPriority:
10848 return Scheduler_LowPriority;
10849 case IdlePriority:
10850 return Scheduler_IdlePriority;
10851 default:
10852 (function () {
10853 {
10854 {
10855 throw ReactError('Unknown priority level.');
10856 }
10857 }
10858 })();
10859 }
10860}
10861
10862function runWithPriority(reactPriorityLevel, fn) {
10863 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
10864 return Scheduler_runWithPriority(priorityLevel, fn);
10865}
10866
10867function scheduleCallback(reactPriorityLevel, callback, options) {
10868 if (reactPriorityLevel === ImmediatePriority) {
10869 // Push this callback into an internal queue. We'll flush these either in
10870 // the next tick, or earlier if something calls `flushImmediateQueue`.
10871 if (immediateQueue === null) {
10872 immediateQueue = [callback];
10873 // Flush the queue in the next tick, at the earliest.
10874 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueueImpl);
10875 } else {
10876 // Push onto existing queue. Don't need to schedule a callback because
10877 // we already scheduled one when we created the queue.
10878 immediateQueue.push(callback);
10879 }
10880 return fakeCallbackNode;
10881 }
10882 // Otherwise pass through to Scheduler.
10883 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
10884 return Scheduler_scheduleCallback(priorityLevel, callback, options);
10885}
10886
10887function cancelCallback(callbackNode) {
10888 if (callbackNode !== fakeCallbackNode) {
10889 Scheduler_cancelCallback(callbackNode);
10890 }
10891}
10892
10893function flushImmediateQueue() {
10894 if (immediateQueueCallbackNode !== null) {
10895 Scheduler_cancelCallback(immediateQueueCallbackNode);
10896 }
10897 flushImmediateQueueImpl();
10898}
10899
10900function flushImmediateQueueImpl() {
10901 if (!isFlushingImmediate && immediateQueue !== null) {
10902 // Prevent re-entrancy.
10903 isFlushingImmediate = true;
10904 var i = 0;
10905 try {
10906 var _isSync = true;
10907 for (; i < immediateQueue.length; i++) {
10908 var callback = immediateQueue[i];
10909 do {
10910 callback = callback(_isSync);
10911 } while (callback !== null);
10912 }
10913 immediateQueue = null;
10914 } catch (error) {
10915 // If something throws, leave the remaining callbacks on the queue.
10916 if (immediateQueue !== null) {
10917 immediateQueue = immediateQueue.slice(i + 1);
10918 }
10919 // Resume flushing in the next tick
10920 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueue);
10921 throw error;
10922 } finally {
10923 isFlushingImmediate = false;
10924 }
10925 }
10926}
10927
10928var NoWork = 0;
10929var Never = 1;
10930var Sync = maxSigned31BitInt;
10931
10932var UNIT_SIZE = 10;
10933var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
10934
10935// 1 unit of expiration time represents 10ms.
10936function msToExpirationTime(ms) {
10937 // Always add an offset so that we don't clash with the magic number for NoWork.
10938 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
10939}
10940
10941function expirationTimeToMs(expirationTime) {
10942 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
10943}
10944
10945function ceiling(num, precision) {
10946 return ((num / precision | 0) + 1) * precision;
10947}
10948
10949function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
10950 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
10951}
10952
10953// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
10954// the names to reflect.
10955var LOW_PRIORITY_EXPIRATION = 5000;
10956var LOW_PRIORITY_BATCH_SIZE = 250;
10957
10958function computeAsyncExpiration(currentTime) {
10959 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
10960}
10961
10962// We intentionally set a higher expiration time for interactive updates in
10963// dev than in production.
10964//
10965// If the main thread is being blocked so long that you hit the expiration,
10966// it's a problem that could be solved with better scheduling.
10967//
10968// People will be more likely to notice this and fix it with the long
10969// expiration time in development.
10970//
10971// In production we opt for better UX at the risk of masking scheduling
10972// problems, by expiring fast.
10973var HIGH_PRIORITY_EXPIRATION = 500;
10974var HIGH_PRIORITY_BATCH_SIZE = 100;
10975
10976function computeInteractiveExpiration(currentTime) {
10977 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
10978}
10979
10980function inferPriorityFromExpirationTime(currentTime, expirationTime) {
10981 if (expirationTime === Sync) {
10982 return ImmediatePriority;
10983 }
10984 if (expirationTime === Never) {
10985 return IdlePriority;
10986 }
10987 var msUntil = msToExpirationTime(expirationTime) - msToExpirationTime(currentTime);
10988 if (msUntil <= 0) {
10989 return ImmediatePriority;
10990 }
10991 if (msUntil <= HIGH_PRIORITY_EXPIRATION) {
10992 return UserBlockingPriority;
10993 }
10994 if (msUntil <= LOW_PRIORITY_EXPIRATION) {
10995 return NormalPriority;
10996 }
10997
10998 // TODO: Handle LowPriority
10999
11000 // Assume anything lower has idle priority
11001 return IdlePriority;
11002}
11003
11004var NoContext = 0;
11005var ConcurrentMode = 1;
11006var StrictMode = 2;
11007var ProfileMode = 4;
11008
11009var hasBadMapPolyfill = void 0;
11010
11011{
11012 hasBadMapPolyfill = false;
11013 try {
11014 var nonExtensibleObject = Object.preventExtensions({});
11015 var testMap = new Map([[nonExtensibleObject, null]]);
11016 var testSet = new Set([nonExtensibleObject]);
11017 // This is necessary for Rollup to not consider these unused.
11018 // https://github.com/rollup/rollup/issues/1771
11019 // TODO: we can remove these if Rollup fixes the bug.
11020 testMap.set(0, 0);
11021 testSet.add(0);
11022 } catch (e) {
11023 // TODO: Consider warning about bad polyfills
11024 hasBadMapPolyfill = true;
11025 }
11026}
11027
11028// A Fiber is work on a Component that needs to be done or was done. There can
11029// be more than one per component.
11030
11031
11032var debugCounter = void 0;
11033
11034{
11035 debugCounter = 1;
11036}
11037
11038function FiberNode(tag, pendingProps, key, mode) {
11039 // Instance
11040 this.tag = tag;
11041 this.key = key;
11042 this.elementType = null;
11043 this.type = null;
11044 this.stateNode = null;
11045
11046 // Fiber
11047 this.return = null;
11048 this.child = null;
11049 this.sibling = null;
11050 this.index = 0;
11051
11052 this.ref = null;
11053
11054 this.pendingProps = pendingProps;
11055 this.memoizedProps = null;
11056 this.updateQueue = null;
11057 this.memoizedState = null;
11058 this.contextDependencies = null;
11059
11060 this.mode = mode;
11061
11062 // Effects
11063 this.effectTag = NoEffect;
11064 this.nextEffect = null;
11065
11066 this.firstEffect = null;
11067 this.lastEffect = null;
11068
11069 this.expirationTime = NoWork;
11070 this.childExpirationTime = NoWork;
11071
11072 this.alternate = null;
11073
11074 if (enableProfilerTimer) {
11075 // Note: The following is done to avoid a v8 performance cliff.
11076 //
11077 // Initializing the fields below to smis and later updating them with
11078 // double values will cause Fibers to end up having separate shapes.
11079 // This behavior/bug has something to do with Object.preventExtension().
11080 // Fortunately this only impacts DEV builds.
11081 // Unfortunately it makes React unusably slow for some applications.
11082 // To work around this, initialize the fields below with doubles.
11083 //
11084 // Learn more about this here:
11085 // https://github.com/facebook/react/issues/14365
11086 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
11087 this.actualDuration = Number.NaN;
11088 this.actualStartTime = Number.NaN;
11089 this.selfBaseDuration = Number.NaN;
11090 this.treeBaseDuration = Number.NaN;
11091
11092 // It's okay to replace the initial doubles with smis after initialization.
11093 // This won't trigger the performance cliff mentioned above,
11094 // and it simplifies other profiler code (including DevTools).
11095 this.actualDuration = 0;
11096 this.actualStartTime = -1;
11097 this.selfBaseDuration = 0;
11098 this.treeBaseDuration = 0;
11099 }
11100
11101 {
11102 this._debugID = debugCounter++;
11103 this._debugSource = null;
11104 this._debugOwner = null;
11105 this._debugIsCurrentlyTiming = false;
11106 this._debugHookTypes = null;
11107 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
11108 Object.preventExtensions(this);
11109 }
11110 }
11111}
11112
11113// This is a constructor function, rather than a POJO constructor, still
11114// please ensure we do the following:
11115// 1) Nobody should add any instance methods on this. Instance methods can be
11116// more difficult to predict when they get optimized and they are almost
11117// never inlined properly in static compilers.
11118// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
11119// always know when it is a fiber.
11120// 3) We might want to experiment with using numeric keys since they are easier
11121// to optimize in a non-JIT environment.
11122// 4) We can easily go from a constructor to a createFiber object literal if that
11123// is faster.
11124// 5) It should be easy to port this to a C struct and keep a C implementation
11125// compatible.
11126var createFiber = function (tag, pendingProps, key, mode) {
11127 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
11128 return new FiberNode(tag, pendingProps, key, mode);
11129};
11130
11131function shouldConstruct(Component) {
11132 var prototype = Component.prototype;
11133 return !!(prototype && prototype.isReactComponent);
11134}
11135
11136function isSimpleFunctionComponent(type) {
11137 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
11138}
11139
11140function resolveLazyComponentTag(Component) {
11141 if (typeof Component === 'function') {
11142 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
11143 } else if (Component !== undefined && Component !== null) {
11144 var $$typeof = Component.$$typeof;
11145 if ($$typeof === REACT_FORWARD_REF_TYPE) {
11146 return ForwardRef;
11147 }
11148 if ($$typeof === REACT_MEMO_TYPE) {
11149 return MemoComponent;
11150 }
11151 }
11152 return IndeterminateComponent;
11153}
11154
11155// This is used to create an alternate fiber to do work on.
11156function createWorkInProgress(current, pendingProps, expirationTime) {
11157 var workInProgress = current.alternate;
11158 if (workInProgress === null) {
11159 // We use a double buffering pooling technique because we know that we'll
11160 // only ever need at most two versions of a tree. We pool the "other" unused
11161 // node that we're free to reuse. This is lazily created to avoid allocating
11162 // extra objects for things that are never updated. It also allow us to
11163 // reclaim the extra memory if needed.
11164 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
11165 workInProgress.elementType = current.elementType;
11166 workInProgress.type = current.type;
11167 workInProgress.stateNode = current.stateNode;
11168
11169 {
11170 // DEV-only fields
11171 workInProgress._debugID = current._debugID;
11172 workInProgress._debugSource = current._debugSource;
11173 workInProgress._debugOwner = current._debugOwner;
11174 workInProgress._debugHookTypes = current._debugHookTypes;
11175 }
11176
11177 workInProgress.alternate = current;
11178 current.alternate = workInProgress;
11179 } else {
11180 workInProgress.pendingProps = pendingProps;
11181
11182 // We already have an alternate.
11183 // Reset the effect tag.
11184 workInProgress.effectTag = NoEffect;
11185
11186 // The effect list is no longer valid.
11187 workInProgress.nextEffect = null;
11188 workInProgress.firstEffect = null;
11189 workInProgress.lastEffect = null;
11190
11191 if (enableProfilerTimer) {
11192 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
11193 // This prevents time from endlessly accumulating in new commits.
11194 // This has the downside of resetting values for different priority renders,
11195 // But works for yielding (the common case) and should support resuming.
11196 workInProgress.actualDuration = 0;
11197 workInProgress.actualStartTime = -1;
11198 }
11199 }
11200
11201 workInProgress.childExpirationTime = current.childExpirationTime;
11202 workInProgress.expirationTime = current.expirationTime;
11203
11204 workInProgress.child = current.child;
11205 workInProgress.memoizedProps = current.memoizedProps;
11206 workInProgress.memoizedState = current.memoizedState;
11207 workInProgress.updateQueue = current.updateQueue;
11208 workInProgress.contextDependencies = current.contextDependencies;
11209
11210 // These will be overridden during the parent's reconciliation
11211 workInProgress.sibling = current.sibling;
11212 workInProgress.index = current.index;
11213 workInProgress.ref = current.ref;
11214
11215 if (enableProfilerTimer) {
11216 workInProgress.selfBaseDuration = current.selfBaseDuration;
11217 workInProgress.treeBaseDuration = current.treeBaseDuration;
11218 }
11219
11220 return workInProgress;
11221}
11222
11223function createHostRootFiber(isConcurrent) {
11224 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
11225
11226 if (enableProfilerTimer && isDevToolsPresent) {
11227 // Always collect profile timings when DevTools are present.
11228 // This enables DevTools to start capturing timing at any point–
11229 // Without some nodes in the tree having empty base times.
11230 mode |= ProfileMode;
11231 }
11232
11233 return createFiber(HostRoot, null, null, mode);
11234}
11235
11236function createFiberFromTypeAndProps(type, // React$ElementType
11237key, pendingProps, owner, mode, expirationTime) {
11238 var fiber = void 0;
11239
11240 var fiberTag = IndeterminateComponent;
11241 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
11242 var resolvedType = type;
11243 if (typeof type === 'function') {
11244 if (shouldConstruct(type)) {
11245 fiberTag = ClassComponent;
11246 }
11247 } else if (typeof type === 'string') {
11248 fiberTag = HostComponent;
11249 } else {
11250 getTag: switch (type) {
11251 case REACT_FRAGMENT_TYPE:
11252 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
11253 case REACT_CONCURRENT_MODE_TYPE:
11254 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
11255 case REACT_STRICT_MODE_TYPE:
11256 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
11257 case REACT_PROFILER_TYPE:
11258 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
11259 case REACT_SUSPENSE_TYPE:
11260 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
11261 default:
11262 {
11263 if (typeof type === 'object' && type !== null) {
11264 switch (type.$$typeof) {
11265 case REACT_PROVIDER_TYPE:
11266 fiberTag = ContextProvider;
11267 break getTag;
11268 case REACT_CONTEXT_TYPE:
11269 // This is a consumer
11270 fiberTag = ContextConsumer;
11271 break getTag;
11272 case REACT_FORWARD_REF_TYPE:
11273 fiberTag = ForwardRef;
11274 break getTag;
11275 case REACT_MEMO_TYPE:
11276 fiberTag = MemoComponent;
11277 break getTag;
11278 case REACT_LAZY_TYPE:
11279 fiberTag = LazyComponent;
11280 resolvedType = null;
11281 break getTag;
11282 case REACT_EVENT_COMPONENT_TYPE:
11283 if (enableEventAPI) {
11284 return createFiberFromEventComponent(type, pendingProps, mode, expirationTime, key);
11285 }
11286 break;
11287 case REACT_EVENT_TARGET_TYPE:
11288 if (enableEventAPI) {
11289 return createFiberFromEventTarget(type, pendingProps, mode, expirationTime, key);
11290 }
11291 break;
11292 }
11293 }
11294 var info = '';
11295 {
11296 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
11297 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.';
11298 }
11299 var ownerName = owner ? getComponentName(owner.type) : null;
11300 if (ownerName) {
11301 info += '\n\nCheck the render method of `' + ownerName + '`.';
11302 }
11303 }
11304 (function () {
11305 {
11306 {
11307 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);
11308 }
11309 }
11310 })();
11311 }
11312 }
11313 }
11314
11315 fiber = createFiber(fiberTag, pendingProps, key, mode);
11316 fiber.elementType = type;
11317 fiber.type = resolvedType;
11318 fiber.expirationTime = expirationTime;
11319
11320 return fiber;
11321}
11322
11323function createFiberFromElement(element, mode, expirationTime) {
11324 var owner = null;
11325 {
11326 owner = element._owner;
11327 }
11328 var type = element.type;
11329 var key = element.key;
11330 var pendingProps = element.props;
11331 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
11332 {
11333 fiber._debugSource = element._source;
11334 fiber._debugOwner = element._owner;
11335 }
11336 return fiber;
11337}
11338
11339function createFiberFromFragment(elements, mode, expirationTime, key) {
11340 var fiber = createFiber(Fragment, elements, key, mode);
11341 fiber.expirationTime = expirationTime;
11342 return fiber;
11343}
11344
11345function createFiberFromEventComponent(eventComponent, pendingProps, mode, expirationTime, key) {
11346 var fiber = createFiber(EventComponent, pendingProps, key, mode);
11347 fiber.elementType = eventComponent;
11348 fiber.type = eventComponent;
11349 fiber.stateNode = {
11350 props: pendingProps,
11351 state: null
11352 };
11353 fiber.expirationTime = expirationTime;
11354 return fiber;
11355}
11356
11357function createFiberFromEventTarget(eventTarget, pendingProps, mode, expirationTime, key) {
11358 var fiber = createFiber(EventTarget, pendingProps, key, mode);
11359 fiber.elementType = eventTarget;
11360 fiber.type = eventTarget;
11361 fiber.expirationTime = expirationTime;
11362 return fiber;
11363}
11364
11365function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
11366 {
11367 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
11368 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
11369 }
11370 }
11371
11372 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
11373 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
11374 fiber.elementType = REACT_PROFILER_TYPE;
11375 fiber.type = REACT_PROFILER_TYPE;
11376 fiber.expirationTime = expirationTime;
11377
11378 return fiber;
11379}
11380
11381function createFiberFromMode(pendingProps, mode, expirationTime, key) {
11382 var fiber = createFiber(Mode, pendingProps, key, mode);
11383
11384 // TODO: The Mode fiber shouldn't have a type. It has a tag.
11385 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
11386 fiber.elementType = type;
11387 fiber.type = type;
11388
11389 fiber.expirationTime = expirationTime;
11390 return fiber;
11391}
11392
11393function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
11394 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
11395
11396 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
11397 var type = REACT_SUSPENSE_TYPE;
11398 fiber.elementType = type;
11399 fiber.type = type;
11400
11401 fiber.expirationTime = expirationTime;
11402 return fiber;
11403}
11404
11405function createFiberFromText(content, mode, expirationTime) {
11406 var fiber = createFiber(HostText, content, null, mode);
11407 fiber.expirationTime = expirationTime;
11408 return fiber;
11409}
11410
11411function createFiberFromHostInstanceForDeletion() {
11412 var fiber = createFiber(HostComponent, null, null, NoContext);
11413 // TODO: These should not need a type.
11414 fiber.elementType = 'DELETED';
11415 fiber.type = 'DELETED';
11416 return fiber;
11417}
11418
11419function createFiberFromPortal(portal, mode, expirationTime) {
11420 var pendingProps = portal.children !== null ? portal.children : [];
11421 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
11422 fiber.expirationTime = expirationTime;
11423 fiber.stateNode = {
11424 containerInfo: portal.containerInfo,
11425 pendingChildren: null, // Used by persistent updates
11426 implementation: portal.implementation
11427 };
11428 return fiber;
11429}
11430
11431// Used for stashing WIP properties to replay failed work in DEV.
11432function assignFiberPropertiesInDEV(target, source) {
11433 if (target === null) {
11434 // This Fiber's initial properties will always be overwritten.
11435 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
11436 target = createFiber(IndeterminateComponent, null, null, NoContext);
11437 }
11438
11439 // This is intentionally written as a list of all properties.
11440 // We tried to use Object.assign() instead but this is called in
11441 // the hottest path, and Object.assign() was too slow:
11442 // https://github.com/facebook/react/issues/12502
11443 // This code is DEV-only so size is not a concern.
11444
11445 target.tag = source.tag;
11446 target.key = source.key;
11447 target.elementType = source.elementType;
11448 target.type = source.type;
11449 target.stateNode = source.stateNode;
11450 target.return = source.return;
11451 target.child = source.child;
11452 target.sibling = source.sibling;
11453 target.index = source.index;
11454 target.ref = source.ref;
11455 target.pendingProps = source.pendingProps;
11456 target.memoizedProps = source.memoizedProps;
11457 target.updateQueue = source.updateQueue;
11458 target.memoizedState = source.memoizedState;
11459 target.contextDependencies = source.contextDependencies;
11460 target.mode = source.mode;
11461 target.effectTag = source.effectTag;
11462 target.nextEffect = source.nextEffect;
11463 target.firstEffect = source.firstEffect;
11464 target.lastEffect = source.lastEffect;
11465 target.expirationTime = source.expirationTime;
11466 target.childExpirationTime = source.childExpirationTime;
11467 target.alternate = source.alternate;
11468 if (enableProfilerTimer) {
11469 target.actualDuration = source.actualDuration;
11470 target.actualStartTime = source.actualStartTime;
11471 target.selfBaseDuration = source.selfBaseDuration;
11472 target.treeBaseDuration = source.treeBaseDuration;
11473 }
11474 target._debugID = source._debugID;
11475 target._debugSource = source._debugSource;
11476 target._debugOwner = source._debugOwner;
11477 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
11478 target._debugHookTypes = source._debugHookTypes;
11479 return target;
11480}
11481
11482var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
11483
11484var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
11485var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
11486var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
11487var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
11488var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
11489var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
11490var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
11491var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
11492var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
11493var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
11494
11495// TODO: This should be lifted into the renderer.
11496
11497
11498// The following attributes are only used by interaction tracing builds.
11499// They enable interactions to be associated with their async work,
11500// And expose interaction metadata to the React DevTools Profiler plugin.
11501// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
11502
11503
11504// Exported FiberRoot type includes all properties,
11505// To avoid requiring potentially error-prone :any casts throughout the project.
11506// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
11507// The types are defined separately within this file to ensure they stay in sync.
11508// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
11509
11510
11511function FiberRootNode(containerInfo, hydrate) {
11512 this.current = null;
11513 this.containerInfo = containerInfo;
11514 this.pendingChildren = null;
11515 this.pingCache = null;
11516 this.pendingCommitExpirationTime = NoWork;
11517 this.finishedWork = null;
11518 this.timeoutHandle = noTimeout;
11519 this.context = null;
11520 this.pendingContext = null;
11521 this.hydrate = hydrate;
11522 this.firstBatch = null;
11523
11524 if (enableNewScheduler) {
11525 this.callbackNode = null;
11526 this.callbackExpirationTime = NoWork;
11527 this.firstPendingTime = NoWork;
11528 this.lastPendingTime = NoWork;
11529 this.pingTime = NoWork;
11530 } else {
11531 this.earliestPendingTime = NoWork;
11532 this.latestPendingTime = NoWork;
11533 this.earliestSuspendedTime = NoWork;
11534 this.latestSuspendedTime = NoWork;
11535 this.latestPingedTime = NoWork;
11536 this.didError = false;
11537 this.nextExpirationTimeToWorkOn = NoWork;
11538 this.expirationTime = NoWork;
11539 this.nextScheduledRoot = null;
11540 }
11541
11542 if (enableSchedulerTracing) {
11543 this.interactionThreadID = unstable_getThreadID();
11544 this.memoizedInteractions = new Set();
11545 this.pendingInteractionMap = new Map();
11546 }
11547}
11548
11549function createFiberRoot(containerInfo, isConcurrent, hydrate) {
11550 var root = new FiberRootNode(containerInfo, hydrate);
11551
11552 // Cyclic construction. This cheats the type system right now because
11553 // stateNode is any.
11554 var uninitializedFiber = createHostRootFiber(isConcurrent);
11555 root.current = uninitializedFiber;
11556 uninitializedFiber.stateNode = root;
11557
11558 return root;
11559}
11560
11561/**
11562 * Forked from fbjs/warning:
11563 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
11564 *
11565 * Only change is we use console.warn instead of console.error,
11566 * and do nothing when 'console' is not supported.
11567 * This really simplifies the code.
11568 * ---
11569 * Similar to invariant but only logs a warning if the condition is not met.
11570 * This can be used to log issues in development environments in critical
11571 * paths. Removing the logging code for production environments will keep the
11572 * same logic and follow the same code paths.
11573 */
11574
11575var lowPriorityWarning = function () {};
11576
11577{
11578 var printWarning$1 = function (format) {
11579 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
11580 args[_key - 1] = arguments[_key];
11581 }
11582
11583 var argIndex = 0;
11584 var message = 'Warning: ' + format.replace(/%s/g, function () {
11585 return args[argIndex++];
11586 });
11587 if (typeof console !== 'undefined') {
11588 console.warn(message);
11589 }
11590 try {
11591 // --- Welcome to debugging React ---
11592 // This error was thrown as a convenience so that you can use this stack
11593 // to find the callsite that caused this warning to fire.
11594 throw new Error(message);
11595 } catch (x) {}
11596 };
11597
11598 lowPriorityWarning = function (condition, format) {
11599 if (format === undefined) {
11600 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
11601 }
11602 if (!condition) {
11603 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
11604 args[_key2 - 2] = arguments[_key2];
11605 }
11606
11607 printWarning$1.apply(undefined, [format].concat(args));
11608 }
11609 };
11610}
11611
11612var lowPriorityWarning$1 = lowPriorityWarning;
11613
11614var ReactStrictModeWarnings = {
11615 discardPendingWarnings: function () {},
11616 flushPendingDeprecationWarnings: function () {},
11617 flushPendingUnsafeLifecycleWarnings: function () {},
11618 recordDeprecationWarnings: function (fiber, instance) {},
11619 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
11620 recordLegacyContextWarning: function (fiber, instance) {},
11621 flushLegacyContextWarning: function () {}
11622};
11623
11624{
11625 var LIFECYCLE_SUGGESTIONS = {
11626 UNSAFE_componentWillMount: 'componentDidMount',
11627 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
11628 UNSAFE_componentWillUpdate: 'componentDidUpdate'
11629 };
11630
11631 var pendingComponentWillMountWarnings = [];
11632 var pendingComponentWillReceivePropsWarnings = [];
11633 var pendingComponentWillUpdateWarnings = [];
11634 var pendingUnsafeLifecycleWarnings = new Map();
11635 var pendingLegacyContextWarning = new Map();
11636
11637 // Tracks components we have already warned about.
11638 var didWarnAboutDeprecatedLifecycles = new Set();
11639 var didWarnAboutUnsafeLifecycles = new Set();
11640 var didWarnAboutLegacyContext = new Set();
11641
11642 var setToSortedString = function (set) {
11643 var array = [];
11644 set.forEach(function (value) {
11645 array.push(value);
11646 });
11647 return array.sort().join(', ');
11648 };
11649
11650 ReactStrictModeWarnings.discardPendingWarnings = function () {
11651 pendingComponentWillMountWarnings = [];
11652 pendingComponentWillReceivePropsWarnings = [];
11653 pendingComponentWillUpdateWarnings = [];
11654 pendingUnsafeLifecycleWarnings = new Map();
11655 pendingLegacyContextWarning = new Map();
11656 };
11657
11658 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
11659 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
11660 var lifecyclesWarningMessages = [];
11661
11662 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
11663 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
11664 if (lifecycleWarnings.length > 0) {
11665 var componentNames = new Set();
11666 lifecycleWarnings.forEach(function (fiber) {
11667 componentNames.add(getComponentName(fiber.type) || 'Component');
11668 didWarnAboutUnsafeLifecycles.add(fiber.type);
11669 });
11670
11671 var formatted = lifecycle.replace('UNSAFE_', '');
11672 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
11673 var sortedComponentNames = setToSortedString(componentNames);
11674
11675 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
11676 }
11677 });
11678
11679 if (lifecyclesWarningMessages.length > 0) {
11680 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
11681
11682 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'));
11683 }
11684 });
11685
11686 pendingUnsafeLifecycleWarnings = new Map();
11687 };
11688
11689 var findStrictRoot = function (fiber) {
11690 var maybeStrictRoot = null;
11691
11692 var node = fiber;
11693 while (node !== null) {
11694 if (node.mode & StrictMode) {
11695 maybeStrictRoot = node;
11696 }
11697 node = node.return;
11698 }
11699
11700 return maybeStrictRoot;
11701 };
11702
11703 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
11704 if (pendingComponentWillMountWarnings.length > 0) {
11705 var uniqueNames = new Set();
11706 pendingComponentWillMountWarnings.forEach(function (fiber) {
11707 uniqueNames.add(getComponentName(fiber.type) || 'Component');
11708 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11709 });
11710
11711 var sortedNames = setToSortedString(uniqueNames);
11712
11713 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);
11714
11715 pendingComponentWillMountWarnings = [];
11716 }
11717
11718 if (pendingComponentWillReceivePropsWarnings.length > 0) {
11719 var _uniqueNames = new Set();
11720 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
11721 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
11722 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11723 });
11724
11725 var _sortedNames = setToSortedString(_uniqueNames);
11726
11727 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);
11728
11729 pendingComponentWillReceivePropsWarnings = [];
11730 }
11731
11732 if (pendingComponentWillUpdateWarnings.length > 0) {
11733 var _uniqueNames2 = new Set();
11734 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
11735 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
11736 didWarnAboutDeprecatedLifecycles.add(fiber.type);
11737 });
11738
11739 var _sortedNames2 = setToSortedString(_uniqueNames2);
11740
11741 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);
11742
11743 pendingComponentWillUpdateWarnings = [];
11744 }
11745 };
11746
11747 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
11748 // Dedup strategy: Warn once per component.
11749 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
11750 return;
11751 }
11752
11753 // Don't warn about react-lifecycles-compat polyfilled components.
11754 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
11755 pendingComponentWillMountWarnings.push(fiber);
11756 }
11757 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
11758 pendingComponentWillReceivePropsWarnings.push(fiber);
11759 }
11760 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
11761 pendingComponentWillUpdateWarnings.push(fiber);
11762 }
11763 };
11764
11765 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
11766 var strictRoot = findStrictRoot(fiber);
11767 if (strictRoot === null) {
11768 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.');
11769 return;
11770 }
11771
11772 // Dedup strategy: Warn once per component.
11773 // This is difficult to track any other way since component names
11774 // are often vague and are likely to collide between 3rd party libraries.
11775 // An expand property is probably okay to use here since it's DEV-only,
11776 // and will only be set in the event of serious warnings.
11777 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
11778 return;
11779 }
11780
11781 var warningsForRoot = void 0;
11782 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
11783 warningsForRoot = {
11784 UNSAFE_componentWillMount: [],
11785 UNSAFE_componentWillReceiveProps: [],
11786 UNSAFE_componentWillUpdate: []
11787 };
11788
11789 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
11790 } else {
11791 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
11792 }
11793
11794 var unsafeLifecycles = [];
11795 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
11796 unsafeLifecycles.push('UNSAFE_componentWillMount');
11797 }
11798 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
11799 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
11800 }
11801 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
11802 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
11803 }
11804
11805 if (unsafeLifecycles.length > 0) {
11806 unsafeLifecycles.forEach(function (lifecycle) {
11807 warningsForRoot[lifecycle].push(fiber);
11808 });
11809 }
11810 };
11811
11812 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
11813 var strictRoot = findStrictRoot(fiber);
11814 if (strictRoot === null) {
11815 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.');
11816 return;
11817 }
11818
11819 // Dedup strategy: Warn once per component.
11820 if (didWarnAboutLegacyContext.has(fiber.type)) {
11821 return;
11822 }
11823
11824 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
11825
11826 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
11827 if (warningsForRoot === undefined) {
11828 warningsForRoot = [];
11829 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
11830 }
11831 warningsForRoot.push(fiber);
11832 }
11833 };
11834
11835 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
11836 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
11837 var uniqueNames = new Set();
11838 fiberArray.forEach(function (fiber) {
11839 uniqueNames.add(getComponentName(fiber.type) || 'Component');
11840 didWarnAboutLegacyContext.add(fiber.type);
11841 });
11842
11843 var sortedNames = setToSortedString(uniqueNames);
11844 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
11845
11846 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);
11847 });
11848 };
11849}
11850
11851// This lets us hook into Fiber to debug what it's doing.
11852// See https://github.com/facebook/react/pull/8033.
11853// This is not part of the public API, not even for React DevTools.
11854// You may only inject a debugTool if you work on React Fiber itself.
11855var ReactFiberInstrumentation = {
11856 debugTool: null
11857};
11858
11859var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
11860
11861// TODO: Offscreen updates should never suspend. However, a promise that
11862// suspended inside an offscreen subtree should be able to ping at the priority
11863// of the outer render.
11864
11865function markPendingPriorityLevel(root, expirationTime) {
11866 // If there's a gap between completing a failed root and retrying it,
11867 // additional updates may be scheduled. Clear `didError`, in case the update
11868 // is sufficient to fix the error.
11869 root.didError = false;
11870
11871 // Update the latest and earliest pending times
11872 var earliestPendingTime = root.earliestPendingTime;
11873 if (earliestPendingTime === NoWork) {
11874 // No other pending updates.
11875 root.earliestPendingTime = root.latestPendingTime = expirationTime;
11876 } else {
11877 if (earliestPendingTime < expirationTime) {
11878 // This is the earliest pending update.
11879 root.earliestPendingTime = expirationTime;
11880 } else {
11881 var latestPendingTime = root.latestPendingTime;
11882 if (latestPendingTime > expirationTime) {
11883 // This is the latest pending update
11884 root.latestPendingTime = expirationTime;
11885 }
11886 }
11887 }
11888 findNextExpirationTimeToWorkOn(expirationTime, root);
11889}
11890
11891function markCommittedPriorityLevels(root, earliestRemainingTime) {
11892 root.didError = false;
11893
11894 if (earliestRemainingTime === NoWork) {
11895 // Fast path. There's no remaining work. Clear everything.
11896 root.earliestPendingTime = NoWork;
11897 root.latestPendingTime = NoWork;
11898 root.earliestSuspendedTime = NoWork;
11899 root.latestSuspendedTime = NoWork;
11900 root.latestPingedTime = NoWork;
11901 findNextExpirationTimeToWorkOn(NoWork, root);
11902 return;
11903 }
11904
11905 if (earliestRemainingTime < root.latestPingedTime) {
11906 root.latestPingedTime = NoWork;
11907 }
11908
11909 // Let's see if the previous latest known pending level was just flushed.
11910 var latestPendingTime = root.latestPendingTime;
11911 if (latestPendingTime !== NoWork) {
11912 if (latestPendingTime > earliestRemainingTime) {
11913 // We've flushed all the known pending levels.
11914 root.earliestPendingTime = root.latestPendingTime = NoWork;
11915 } else {
11916 var earliestPendingTime = root.earliestPendingTime;
11917 if (earliestPendingTime > earliestRemainingTime) {
11918 // We've flushed the earliest known pending level. Set this to the
11919 // latest pending time.
11920 root.earliestPendingTime = root.latestPendingTime;
11921 }
11922 }
11923 }
11924
11925 // Now let's handle the earliest remaining level in the whole tree. We need to
11926 // decide whether to treat it as a pending level or as suspended. Check
11927 // it falls within the range of known suspended levels.
11928
11929 var earliestSuspendedTime = root.earliestSuspendedTime;
11930 if (earliestSuspendedTime === NoWork) {
11931 // There's no suspended work. Treat the earliest remaining level as a
11932 // pending level.
11933 markPendingPriorityLevel(root, earliestRemainingTime);
11934 findNextExpirationTimeToWorkOn(NoWork, root);
11935 return;
11936 }
11937
11938 var latestSuspendedTime = root.latestSuspendedTime;
11939 if (earliestRemainingTime < latestSuspendedTime) {
11940 // The earliest remaining level is later than all the suspended work. That
11941 // means we've flushed all the suspended work.
11942 root.earliestSuspendedTime = NoWork;
11943 root.latestSuspendedTime = NoWork;
11944 root.latestPingedTime = NoWork;
11945
11946 // There's no suspended work. Treat the earliest remaining level as a
11947 // pending level.
11948 markPendingPriorityLevel(root, earliestRemainingTime);
11949 findNextExpirationTimeToWorkOn(NoWork, root);
11950 return;
11951 }
11952
11953 if (earliestRemainingTime > earliestSuspendedTime) {
11954 // The earliest remaining time is earlier than all the suspended work.
11955 // Treat it as a pending update.
11956 markPendingPriorityLevel(root, earliestRemainingTime);
11957 findNextExpirationTimeToWorkOn(NoWork, root);
11958 return;
11959 }
11960
11961 // The earliest remaining time falls within the range of known suspended
11962 // levels. We should treat this as suspended work.
11963 findNextExpirationTimeToWorkOn(NoWork, root);
11964}
11965
11966function hasLowerPriorityWork(root, erroredExpirationTime) {
11967 var latestPendingTime = root.latestPendingTime;
11968 var latestSuspendedTime = root.latestSuspendedTime;
11969 var latestPingedTime = root.latestPingedTime;
11970 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
11971}
11972
11973function isPriorityLevelSuspended(root, expirationTime) {
11974 var earliestSuspendedTime = root.earliestSuspendedTime;
11975 var latestSuspendedTime = root.latestSuspendedTime;
11976 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
11977}
11978
11979function markSuspendedPriorityLevel(root, suspendedTime) {
11980 root.didError = false;
11981 clearPing(root, suspendedTime);
11982
11983 // First, check the known pending levels and update them if needed.
11984 var earliestPendingTime = root.earliestPendingTime;
11985 var latestPendingTime = root.latestPendingTime;
11986 if (earliestPendingTime === suspendedTime) {
11987 if (latestPendingTime === suspendedTime) {
11988 // Both known pending levels were suspended. Clear them.
11989 root.earliestPendingTime = root.latestPendingTime = NoWork;
11990 } else {
11991 // The earliest pending level was suspended. Clear by setting it to the
11992 // latest pending level.
11993 root.earliestPendingTime = latestPendingTime;
11994 }
11995 } else if (latestPendingTime === suspendedTime) {
11996 // The latest pending level was suspended. Clear by setting it to the
11997 // latest pending level.
11998 root.latestPendingTime = earliestPendingTime;
11999 }
12000
12001 // Finally, update the known suspended levels.
12002 var earliestSuspendedTime = root.earliestSuspendedTime;
12003 var latestSuspendedTime = root.latestSuspendedTime;
12004 if (earliestSuspendedTime === NoWork) {
12005 // No other suspended levels.
12006 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
12007 } else {
12008 if (earliestSuspendedTime < suspendedTime) {
12009 // This is the earliest suspended level.
12010 root.earliestSuspendedTime = suspendedTime;
12011 } else if (latestSuspendedTime > suspendedTime) {
12012 // This is the latest suspended level
12013 root.latestSuspendedTime = suspendedTime;
12014 }
12015 }
12016
12017 findNextExpirationTimeToWorkOn(suspendedTime, root);
12018}
12019
12020function markPingedPriorityLevel(root, pingedTime) {
12021 root.didError = false;
12022
12023 // TODO: When we add back resuming, we need to ensure the progressed work
12024 // is thrown out and not reused during the restarted render. One way to
12025 // invalidate the progressed work is to restart at expirationTime + 1.
12026 var latestPingedTime = root.latestPingedTime;
12027 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
12028 root.latestPingedTime = pingedTime;
12029 }
12030 findNextExpirationTimeToWorkOn(pingedTime, root);
12031}
12032
12033function clearPing(root, completedTime) {
12034 var latestPingedTime = root.latestPingedTime;
12035 if (latestPingedTime >= completedTime) {
12036 root.latestPingedTime = NoWork;
12037 }
12038}
12039
12040function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
12041 var earliestExpirationTime = renderExpirationTime;
12042
12043 var earliestPendingTime = root.earliestPendingTime;
12044 var earliestSuspendedTime = root.earliestSuspendedTime;
12045 if (earliestPendingTime > earliestExpirationTime) {
12046 earliestExpirationTime = earliestPendingTime;
12047 }
12048 if (earliestSuspendedTime > earliestExpirationTime) {
12049 earliestExpirationTime = earliestSuspendedTime;
12050 }
12051 return earliestExpirationTime;
12052}
12053
12054function didExpireAtExpirationTime(root, currentTime) {
12055 var expirationTime = root.expirationTime;
12056 if (expirationTime !== NoWork && currentTime <= expirationTime) {
12057 // The root has expired. Flush all work up to the current time.
12058 root.nextExpirationTimeToWorkOn = currentTime;
12059 }
12060}
12061
12062function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
12063 var earliestSuspendedTime = root.earliestSuspendedTime;
12064 var latestSuspendedTime = root.latestSuspendedTime;
12065 var earliestPendingTime = root.earliestPendingTime;
12066 var latestPingedTime = root.latestPingedTime;
12067
12068 // Work on the earliest pending time. Failing that, work on the latest
12069 // pinged time.
12070 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
12071
12072 // If there is no pending or pinged work, check if there's suspended work
12073 // that's lower priority than what we just completed.
12074 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
12075 // The lowest priority suspended work is the work most likely to be
12076 // committed next. Let's start rendering it again, so that if it times out,
12077 // it's ready to commit.
12078 nextExpirationTimeToWorkOn = latestSuspendedTime;
12079 }
12080
12081 var expirationTime = nextExpirationTimeToWorkOn;
12082 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
12083 // Expire using the earliest known expiration time.
12084 expirationTime = earliestSuspendedTime;
12085 }
12086
12087 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
12088 root.expirationTime = expirationTime;
12089}
12090
12091function resolveDefaultProps(Component, baseProps) {
12092 if (Component && Component.defaultProps) {
12093 // Resolve default props. Taken from ReactElement
12094 var props = _assign({}, baseProps);
12095 var defaultProps = Component.defaultProps;
12096 for (var propName in defaultProps) {
12097 if (props[propName] === undefined) {
12098 props[propName] = defaultProps[propName];
12099 }
12100 }
12101 return props;
12102 }
12103 return baseProps;
12104}
12105
12106function readLazyComponentType(lazyComponent) {
12107 var status = lazyComponent._status;
12108 var result = lazyComponent._result;
12109 switch (status) {
12110 case Resolved:
12111 {
12112 var Component = result;
12113 return Component;
12114 }
12115 case Rejected:
12116 {
12117 var error = result;
12118 throw error;
12119 }
12120 case Pending:
12121 {
12122 var thenable = result;
12123 throw thenable;
12124 }
12125 default:
12126 {
12127 lazyComponent._status = Pending;
12128 var ctor = lazyComponent._ctor;
12129 var _thenable = ctor();
12130 _thenable.then(function (moduleObject) {
12131 if (lazyComponent._status === Pending) {
12132 var defaultExport = moduleObject.default;
12133 {
12134 if (defaultExport === undefined) {
12135 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);
12136 }
12137 }
12138 lazyComponent._status = Resolved;
12139 lazyComponent._result = defaultExport;
12140 }
12141 }, function (error) {
12142 if (lazyComponent._status === Pending) {
12143 lazyComponent._status = Rejected;
12144 lazyComponent._result = error;
12145 }
12146 });
12147 // Handle synchronous thenables.
12148 switch (lazyComponent._status) {
12149 case Resolved:
12150 return lazyComponent._result;
12151 case Rejected:
12152 throw lazyComponent._result;
12153 }
12154 lazyComponent._result = _thenable;
12155 throw _thenable;
12156 }
12157 }
12158}
12159
12160var fakeInternalInstance = {};
12161var isArray$1 = Array.isArray;
12162
12163// React.Component uses a shared frozen object by default.
12164// We'll use it to determine whether we need to initialize legacy refs.
12165var emptyRefsObject = new React.Component().refs;
12166
12167var didWarnAboutStateAssignmentForComponent = void 0;
12168var didWarnAboutUninitializedState = void 0;
12169var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
12170var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
12171var didWarnAboutUndefinedDerivedState = void 0;
12172var warnOnUndefinedDerivedState = void 0;
12173var warnOnInvalidCallback$1 = void 0;
12174var didWarnAboutDirectlyAssigningPropsToState = void 0;
12175var didWarnAboutContextTypeAndContextTypes = void 0;
12176var didWarnAboutInvalidateContextType = void 0;
12177
12178{
12179 didWarnAboutStateAssignmentForComponent = new Set();
12180 didWarnAboutUninitializedState = new Set();
12181 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
12182 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
12183 didWarnAboutDirectlyAssigningPropsToState = new Set();
12184 didWarnAboutUndefinedDerivedState = new Set();
12185 didWarnAboutContextTypeAndContextTypes = new Set();
12186 didWarnAboutInvalidateContextType = new Set();
12187
12188 var didWarnOnInvalidCallback = new Set();
12189
12190 warnOnInvalidCallback$1 = function (callback, callerName) {
12191 if (callback === null || typeof callback === 'function') {
12192 return;
12193 }
12194 var key = callerName + '_' + callback;
12195 if (!didWarnOnInvalidCallback.has(key)) {
12196 didWarnOnInvalidCallback.add(key);
12197 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
12198 }
12199 };
12200
12201 warnOnUndefinedDerivedState = function (type, partialState) {
12202 if (partialState === undefined) {
12203 var componentName = getComponentName(type) || 'Component';
12204 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
12205 didWarnAboutUndefinedDerivedState.add(componentName);
12206 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
12207 }
12208 }
12209 };
12210
12211 // This is so gross but it's at least non-critical and can be removed if
12212 // it causes problems. This is meant to give a nicer error message for
12213 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
12214 // ...)) which otherwise throws a "_processChildContext is not a function"
12215 // exception.
12216 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
12217 enumerable: false,
12218 value: function () {
12219 (function () {
12220 {
12221 {
12222 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).');
12223 }
12224 }
12225 })();
12226 }
12227 });
12228 Object.freeze(fakeInternalInstance);
12229}
12230
12231function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
12232 var prevState = workInProgress.memoizedState;
12233
12234 {
12235 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
12236 // Invoke the function an extra time to help detect side-effects.
12237 getDerivedStateFromProps(nextProps, prevState);
12238 }
12239 }
12240
12241 var partialState = getDerivedStateFromProps(nextProps, prevState);
12242
12243 {
12244 warnOnUndefinedDerivedState(ctor, partialState);
12245 }
12246 // Merge the partial state and the previous state.
12247 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
12248 workInProgress.memoizedState = memoizedState;
12249
12250 // Once the update queue is empty, persist the derived state onto the
12251 // base state.
12252 var updateQueue = workInProgress.updateQueue;
12253 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
12254 updateQueue.baseState = memoizedState;
12255 }
12256}
12257
12258var classComponentUpdater = {
12259 isMounted: isMounted,
12260 enqueueSetState: function (inst, payload, callback) {
12261 var fiber = get(inst);
12262 var currentTime = requestCurrentTime$$1();
12263 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12264
12265 var update = createUpdate(expirationTime);
12266 update.payload = payload;
12267 if (callback !== undefined && callback !== null) {
12268 {
12269 warnOnInvalidCallback$1(callback, 'setState');
12270 }
12271 update.callback = callback;
12272 }
12273
12274 flushPassiveEffects$$1();
12275 enqueueUpdate(fiber, update);
12276 scheduleWork$$1(fiber, expirationTime);
12277 },
12278 enqueueReplaceState: function (inst, payload, callback) {
12279 var fiber = get(inst);
12280 var currentTime = requestCurrentTime$$1();
12281 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12282
12283 var update = createUpdate(expirationTime);
12284 update.tag = ReplaceState;
12285 update.payload = payload;
12286
12287 if (callback !== undefined && callback !== null) {
12288 {
12289 warnOnInvalidCallback$1(callback, 'replaceState');
12290 }
12291 update.callback = callback;
12292 }
12293
12294 flushPassiveEffects$$1();
12295 enqueueUpdate(fiber, update);
12296 scheduleWork$$1(fiber, expirationTime);
12297 },
12298 enqueueForceUpdate: function (inst, callback) {
12299 var fiber = get(inst);
12300 var currentTime = requestCurrentTime$$1();
12301 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
12302
12303 var update = createUpdate(expirationTime);
12304 update.tag = ForceUpdate;
12305
12306 if (callback !== undefined && callback !== null) {
12307 {
12308 warnOnInvalidCallback$1(callback, 'forceUpdate');
12309 }
12310 update.callback = callback;
12311 }
12312
12313 flushPassiveEffects$$1();
12314 enqueueUpdate(fiber, update);
12315 scheduleWork$$1(fiber, expirationTime);
12316 }
12317};
12318
12319function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
12320 var instance = workInProgress.stateNode;
12321 if (typeof instance.shouldComponentUpdate === 'function') {
12322 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
12323 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
12324 stopPhaseTimer();
12325
12326 {
12327 !(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;
12328 }
12329
12330 return shouldUpdate;
12331 }
12332
12333 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
12334 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
12335 }
12336
12337 return true;
12338}
12339
12340function checkClassInstance(workInProgress, ctor, newProps) {
12341 var instance = workInProgress.stateNode;
12342 {
12343 var name = getComponentName(ctor) || 'Component';
12344 var renderPresent = instance.render;
12345
12346 if (!renderPresent) {
12347 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
12348 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
12349 } else {
12350 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
12351 }
12352 }
12353
12354 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
12355 !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;
12356 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
12357 !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;
12358 var noInstancePropTypes = !instance.propTypes;
12359 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
12360 var noInstanceContextType = !instance.contextType;
12361 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
12362 var noInstanceContextTypes = !instance.contextTypes;
12363 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
12364
12365 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
12366 didWarnAboutContextTypeAndContextTypes.add(ctor);
12367 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
12368 }
12369
12370 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
12371 !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;
12372 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
12373 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');
12374 }
12375 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
12376 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
12377 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
12378 !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;
12379 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
12380 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
12381 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
12382 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
12383 var hasMutatedProps = instance.props !== newProps;
12384 !(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;
12385 var noInstanceDefaultProps = !instance.defaultProps;
12386 !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;
12387
12388 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
12389 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
12390 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
12391 }
12392
12393 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
12394 !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;
12395 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
12396 !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;
12397 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
12398 !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;
12399 var _state = instance.state;
12400 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
12401 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
12402 }
12403 if (typeof instance.getChildContext === 'function') {
12404 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
12405 }
12406 }
12407}
12408
12409function adoptClassInstance(workInProgress, instance) {
12410 instance.updater = classComponentUpdater;
12411 workInProgress.stateNode = instance;
12412 // The instance needs access to the fiber so that it can schedule updates
12413 set(instance, workInProgress);
12414 {
12415 instance._reactInternalInstance = fakeInternalInstance;
12416 }
12417}
12418
12419function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
12420 var isLegacyContextConsumer = false;
12421 var unmaskedContext = emptyContextObject;
12422 var context = null;
12423 var contextType = ctor.contextType;
12424
12425 {
12426 if ('contextType' in ctor) {
12427 var isValid =
12428 // Allow null for conditional declaration
12429 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
12430
12431 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
12432 didWarnAboutInvalidateContextType.add(ctor);
12433
12434 var addendum = '';
12435 if (contextType === undefined) {
12436 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.';
12437 } else if (typeof contextType !== 'object') {
12438 addendum = ' However, it is set to a ' + typeof contextType + '.';
12439 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
12440 addendum = ' Did you accidentally pass the Context.Provider instead?';
12441 } else if (contextType._context !== undefined) {
12442 // <Context.Consumer>
12443 addendum = ' Did you accidentally pass the Context.Consumer instead?';
12444 } else {
12445 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
12446 }
12447 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
12448 }
12449 }
12450 }
12451
12452 if (typeof contextType === 'object' && contextType !== null) {
12453 context = readContext(contextType);
12454 } else {
12455 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12456 var contextTypes = ctor.contextTypes;
12457 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
12458 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
12459 }
12460
12461 // Instantiate twice to help detect side-effects.
12462 {
12463 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
12464 new ctor(props, context); // eslint-disable-line no-new
12465 }
12466 }
12467
12468 var instance = new ctor(props, context);
12469 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
12470 adoptClassInstance(workInProgress, instance);
12471
12472 {
12473 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
12474 var componentName = getComponentName(ctor) || 'Component';
12475 if (!didWarnAboutUninitializedState.has(componentName)) {
12476 didWarnAboutUninitializedState.add(componentName);
12477 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);
12478 }
12479 }
12480
12481 // If new component APIs are defined, "unsafe" lifecycles won't be called.
12482 // Warn about these lifecycles if they are present.
12483 // Don't warn about react-lifecycles-compat polyfilled methods though.
12484 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
12485 var foundWillMountName = null;
12486 var foundWillReceivePropsName = null;
12487 var foundWillUpdateName = null;
12488 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
12489 foundWillMountName = 'componentWillMount';
12490 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
12491 foundWillMountName = 'UNSAFE_componentWillMount';
12492 }
12493 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12494 foundWillReceivePropsName = 'componentWillReceiveProps';
12495 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12496 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
12497 }
12498 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12499 foundWillUpdateName = 'componentWillUpdate';
12500 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
12501 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
12502 }
12503 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
12504 var _componentName = getComponentName(ctor) || 'Component';
12505 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
12506 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
12507 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
12508 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 : '');
12509 }
12510 }
12511 }
12512 }
12513
12514 // Cache unmasked context so we can avoid recreating masked context unless necessary.
12515 // ReactFiberContext usually updates this cache but can't for newly-created instances.
12516 if (isLegacyContextConsumer) {
12517 cacheContext(workInProgress, unmaskedContext, context);
12518 }
12519
12520 return instance;
12521}
12522
12523function callComponentWillMount(workInProgress, instance) {
12524 startPhaseTimer(workInProgress, 'componentWillMount');
12525 var oldState = instance.state;
12526
12527 if (typeof instance.componentWillMount === 'function') {
12528 instance.componentWillMount();
12529 }
12530 if (typeof instance.UNSAFE_componentWillMount === 'function') {
12531 instance.UNSAFE_componentWillMount();
12532 }
12533
12534 stopPhaseTimer();
12535
12536 if (oldState !== instance.state) {
12537 {
12538 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');
12539 }
12540 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
12541 }
12542}
12543
12544function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
12545 var oldState = instance.state;
12546 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
12547 if (typeof instance.componentWillReceiveProps === 'function') {
12548 instance.componentWillReceiveProps(newProps, nextContext);
12549 }
12550 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12551 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
12552 }
12553 stopPhaseTimer();
12554
12555 if (instance.state !== oldState) {
12556 {
12557 var componentName = getComponentName(workInProgress.type) || 'Component';
12558 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
12559 didWarnAboutStateAssignmentForComponent.add(componentName);
12560 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
12561 }
12562 }
12563 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
12564 }
12565}
12566
12567// Invokes the mount life-cycles on a previously never rendered instance.
12568function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
12569 {
12570 checkClassInstance(workInProgress, ctor, newProps);
12571 }
12572
12573 var instance = workInProgress.stateNode;
12574 instance.props = newProps;
12575 instance.state = workInProgress.memoizedState;
12576 instance.refs = emptyRefsObject;
12577
12578 var contextType = ctor.contextType;
12579 if (typeof contextType === 'object' && contextType !== null) {
12580 instance.context = readContext(contextType);
12581 } else {
12582 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12583 instance.context = getMaskedContext(workInProgress, unmaskedContext);
12584 }
12585
12586 {
12587 if (instance.state === newProps) {
12588 var componentName = getComponentName(ctor) || 'Component';
12589 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
12590 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
12591 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);
12592 }
12593 }
12594
12595 if (workInProgress.mode & StrictMode) {
12596 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
12597
12598 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
12599 }
12600
12601 if (warnAboutDeprecatedLifecycles) {
12602 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
12603 }
12604 }
12605
12606 var updateQueue = workInProgress.updateQueue;
12607 if (updateQueue !== null) {
12608 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12609 instance.state = workInProgress.memoizedState;
12610 }
12611
12612 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12613 if (typeof getDerivedStateFromProps === 'function') {
12614 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12615 instance.state = workInProgress.memoizedState;
12616 }
12617
12618 // In order to support react-lifecycles-compat polyfilled components,
12619 // Unsafe lifecycles should not be invoked for components using the new APIs.
12620 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
12621 callComponentWillMount(workInProgress, instance);
12622 // If we had additional state updates during this life-cycle, let's
12623 // process them now.
12624 updateQueue = workInProgress.updateQueue;
12625 if (updateQueue !== null) {
12626 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12627 instance.state = workInProgress.memoizedState;
12628 }
12629 }
12630
12631 if (typeof instance.componentDidMount === 'function') {
12632 workInProgress.effectTag |= Update;
12633 }
12634}
12635
12636function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
12637 var instance = workInProgress.stateNode;
12638
12639 var oldProps = workInProgress.memoizedProps;
12640 instance.props = oldProps;
12641
12642 var oldContext = instance.context;
12643 var contextType = ctor.contextType;
12644 var nextContext = void 0;
12645 if (typeof contextType === 'object' && contextType !== null) {
12646 nextContext = readContext(contextType);
12647 } else {
12648 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12649 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
12650 }
12651
12652 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12653 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
12654
12655 // Note: During these life-cycles, instance.props/instance.state are what
12656 // ever the previously attempted to render - not the "current". However,
12657 // during componentDidUpdate we pass the "current" props.
12658
12659 // In order to support react-lifecycles-compat polyfilled components,
12660 // Unsafe lifecycles should not be invoked for components using the new APIs.
12661 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
12662 if (oldProps !== newProps || oldContext !== nextContext) {
12663 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
12664 }
12665 }
12666
12667 resetHasForceUpdateBeforeProcessing();
12668
12669 var oldState = workInProgress.memoizedState;
12670 var newState = instance.state = oldState;
12671 var updateQueue = workInProgress.updateQueue;
12672 if (updateQueue !== null) {
12673 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12674 newState = workInProgress.memoizedState;
12675 }
12676 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
12677 // If an update was already in progress, we should schedule an Update
12678 // effect even though we're bailing out, so that cWU/cDU are called.
12679 if (typeof instance.componentDidMount === 'function') {
12680 workInProgress.effectTag |= Update;
12681 }
12682 return false;
12683 }
12684
12685 if (typeof getDerivedStateFromProps === 'function') {
12686 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12687 newState = workInProgress.memoizedState;
12688 }
12689
12690 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
12691
12692 if (shouldUpdate) {
12693 // In order to support react-lifecycles-compat polyfilled components,
12694 // Unsafe lifecycles should not be invoked for components using the new APIs.
12695 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
12696 startPhaseTimer(workInProgress, 'componentWillMount');
12697 if (typeof instance.componentWillMount === 'function') {
12698 instance.componentWillMount();
12699 }
12700 if (typeof instance.UNSAFE_componentWillMount === 'function') {
12701 instance.UNSAFE_componentWillMount();
12702 }
12703 stopPhaseTimer();
12704 }
12705 if (typeof instance.componentDidMount === 'function') {
12706 workInProgress.effectTag |= Update;
12707 }
12708 } else {
12709 // If an update was already in progress, we should schedule an Update
12710 // effect even though we're bailing out, so that cWU/cDU are called.
12711 if (typeof instance.componentDidMount === 'function') {
12712 workInProgress.effectTag |= Update;
12713 }
12714
12715 // If shouldComponentUpdate returned false, we should still update the
12716 // memoized state to indicate that this work can be reused.
12717 workInProgress.memoizedProps = newProps;
12718 workInProgress.memoizedState = newState;
12719 }
12720
12721 // Update the existing instance's state, props, and context pointers even
12722 // if shouldComponentUpdate returns false.
12723 instance.props = newProps;
12724 instance.state = newState;
12725 instance.context = nextContext;
12726
12727 return shouldUpdate;
12728}
12729
12730// Invokes the update life-cycles and returns false if it shouldn't rerender.
12731function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
12732 var instance = workInProgress.stateNode;
12733
12734 var oldProps = workInProgress.memoizedProps;
12735 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
12736
12737 var oldContext = instance.context;
12738 var contextType = ctor.contextType;
12739 var nextContext = void 0;
12740 if (typeof contextType === 'object' && contextType !== null) {
12741 nextContext = readContext(contextType);
12742 } else {
12743 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
12744 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
12745 }
12746
12747 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
12748 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
12749
12750 // Note: During these life-cycles, instance.props/instance.state are what
12751 // ever the previously attempted to render - not the "current". However,
12752 // during componentDidUpdate we pass the "current" props.
12753
12754 // In order to support react-lifecycles-compat polyfilled components,
12755 // Unsafe lifecycles should not be invoked for components using the new APIs.
12756 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
12757 if (oldProps !== newProps || oldContext !== nextContext) {
12758 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
12759 }
12760 }
12761
12762 resetHasForceUpdateBeforeProcessing();
12763
12764 var oldState = workInProgress.memoizedState;
12765 var newState = instance.state = oldState;
12766 var updateQueue = workInProgress.updateQueue;
12767 if (updateQueue !== null) {
12768 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
12769 newState = workInProgress.memoizedState;
12770 }
12771
12772 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
12773 // If an update was already in progress, we should schedule an Update
12774 // effect even though we're bailing out, so that cWU/cDU are called.
12775 if (typeof instance.componentDidUpdate === 'function') {
12776 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12777 workInProgress.effectTag |= Update;
12778 }
12779 }
12780 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12781 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12782 workInProgress.effectTag |= Snapshot;
12783 }
12784 }
12785 return false;
12786 }
12787
12788 if (typeof getDerivedStateFromProps === 'function') {
12789 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
12790 newState = workInProgress.memoizedState;
12791 }
12792
12793 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
12794
12795 if (shouldUpdate) {
12796 // In order to support react-lifecycles-compat polyfilled components,
12797 // Unsafe lifecycles should not be invoked for components using the new APIs.
12798 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
12799 startPhaseTimer(workInProgress, 'componentWillUpdate');
12800 if (typeof instance.componentWillUpdate === 'function') {
12801 instance.componentWillUpdate(newProps, newState, nextContext);
12802 }
12803 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
12804 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
12805 }
12806 stopPhaseTimer();
12807 }
12808 if (typeof instance.componentDidUpdate === 'function') {
12809 workInProgress.effectTag |= Update;
12810 }
12811 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12812 workInProgress.effectTag |= Snapshot;
12813 }
12814 } else {
12815 // If an update was already in progress, we should schedule an Update
12816 // effect even though we're bailing out, so that cWU/cDU are called.
12817 if (typeof instance.componentDidUpdate === 'function') {
12818 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12819 workInProgress.effectTag |= Update;
12820 }
12821 }
12822 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
12823 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
12824 workInProgress.effectTag |= Snapshot;
12825 }
12826 }
12827
12828 // If shouldComponentUpdate returned false, we should still update the
12829 // memoized props/state to indicate that this work can be reused.
12830 workInProgress.memoizedProps = newProps;
12831 workInProgress.memoizedState = newState;
12832 }
12833
12834 // Update the existing instance's state, props, and context pointers even
12835 // if shouldComponentUpdate returns false.
12836 instance.props = newProps;
12837 instance.state = newState;
12838 instance.context = nextContext;
12839
12840 return shouldUpdate;
12841}
12842
12843var didWarnAboutMaps = void 0;
12844var didWarnAboutGenerators = void 0;
12845var didWarnAboutStringRefInStrictMode = void 0;
12846var ownerHasKeyUseWarning = void 0;
12847var ownerHasFunctionTypeWarning = void 0;
12848var warnForMissingKey = function (child) {};
12849
12850{
12851 didWarnAboutMaps = false;
12852 didWarnAboutGenerators = false;
12853 didWarnAboutStringRefInStrictMode = {};
12854
12855 /**
12856 * Warn if there's no key explicitly set on dynamic arrays of children or
12857 * object keys are not valid. This allows us to keep track of children between
12858 * updates.
12859 */
12860 ownerHasKeyUseWarning = {};
12861 ownerHasFunctionTypeWarning = {};
12862
12863 warnForMissingKey = function (child) {
12864 if (child === null || typeof child !== 'object') {
12865 return;
12866 }
12867 if (!child._store || child._store.validated || child.key != null) {
12868 return;
12869 }
12870 (function () {
12871 if (!(typeof child._store === 'object')) {
12872 {
12873 throw ReactError('React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.');
12874 }
12875 }
12876 })();
12877 child._store.validated = true;
12878
12879 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
12880 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
12881 return;
12882 }
12883 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
12884
12885 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
12886 };
12887}
12888
12889var isArray = Array.isArray;
12890
12891function coerceRef(returnFiber, current$$1, element) {
12892 var mixedRef = element.ref;
12893 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
12894 {
12895 if (returnFiber.mode & StrictMode) {
12896 var componentName = getComponentName(returnFiber.type) || 'Component';
12897 if (!didWarnAboutStringRefInStrictMode[componentName]) {
12898 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));
12899 didWarnAboutStringRefInStrictMode[componentName] = true;
12900 }
12901 }
12902 }
12903
12904 if (element._owner) {
12905 var owner = element._owner;
12906 var inst = void 0;
12907 if (owner) {
12908 var ownerFiber = owner;
12909 (function () {
12910 if (!(ownerFiber.tag === ClassComponent)) {
12911 {
12912 throw ReactError('Function components cannot have refs. Did you mean to use React.forwardRef()?');
12913 }
12914 }
12915 })();
12916 inst = ownerFiber.stateNode;
12917 }
12918 (function () {
12919 if (!inst) {
12920 {
12921 throw ReactError('Missing owner for string ref ' + mixedRef + '. This error is likely caused by a bug in React. Please file an issue.');
12922 }
12923 }
12924 })();
12925 var stringRef = '' + mixedRef;
12926 // Check if previous string ref matches new string ref
12927 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
12928 return current$$1.ref;
12929 }
12930 var ref = function (value) {
12931 var refs = inst.refs;
12932 if (refs === emptyRefsObject) {
12933 // This is a lazy pooled frozen object, so we need to initialize.
12934 refs = inst.refs = {};
12935 }
12936 if (value === null) {
12937 delete refs[stringRef];
12938 } else {
12939 refs[stringRef] = value;
12940 }
12941 };
12942 ref._stringRef = stringRef;
12943 return ref;
12944 } else {
12945 (function () {
12946 if (!(typeof mixedRef === 'string')) {
12947 {
12948 throw ReactError('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
12949 }
12950 }
12951 })();
12952 (function () {
12953 if (!element._owner) {
12954 {
12955 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.');
12956 }
12957 }
12958 })();
12959 }
12960 }
12961 return mixedRef;
12962}
12963
12964function throwOnInvalidObjectType(returnFiber, newChild) {
12965 if (returnFiber.type !== 'textarea') {
12966 var addendum = '';
12967 {
12968 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
12969 }
12970 (function () {
12971 {
12972 {
12973 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);
12974 }
12975 }
12976 })();
12977 }
12978}
12979
12980function warnOnFunctionType() {
12981 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();
12982
12983 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
12984 return;
12985 }
12986 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
12987
12988 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.');
12989}
12990
12991// This wrapper function exists because I expect to clone the code in each path
12992// to be able to optimize each path individually by branching early. This needs
12993// a compiler or we can do it manually. Helpers that don't need this branching
12994// live outside of this function.
12995function ChildReconciler(shouldTrackSideEffects) {
12996 function deleteChild(returnFiber, childToDelete) {
12997 if (!shouldTrackSideEffects) {
12998 // Noop.
12999 return;
13000 }
13001 // Deletions are added in reversed order so we add it to the front.
13002 // At this point, the return fiber's effect list is empty except for
13003 // deletions, so we can just append the deletion to the list. The remaining
13004 // effects aren't added until the complete phase. Once we implement
13005 // resuming, this may not be true.
13006 var last = returnFiber.lastEffect;
13007 if (last !== null) {
13008 last.nextEffect = childToDelete;
13009 returnFiber.lastEffect = childToDelete;
13010 } else {
13011 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
13012 }
13013 childToDelete.nextEffect = null;
13014 childToDelete.effectTag = Deletion;
13015 }
13016
13017 function deleteRemainingChildren(returnFiber, currentFirstChild) {
13018 if (!shouldTrackSideEffects) {
13019 // Noop.
13020 return null;
13021 }
13022
13023 // TODO: For the shouldClone case, this could be micro-optimized a bit by
13024 // assuming that after the first child we've already added everything.
13025 var childToDelete = currentFirstChild;
13026 while (childToDelete !== null) {
13027 deleteChild(returnFiber, childToDelete);
13028 childToDelete = childToDelete.sibling;
13029 }
13030 return null;
13031 }
13032
13033 function mapRemainingChildren(returnFiber, currentFirstChild) {
13034 // Add the remaining children to a temporary map so that we can find them by
13035 // keys quickly. Implicit (null) keys get added to this set with their index
13036 var existingChildren = new Map();
13037
13038 var existingChild = currentFirstChild;
13039 while (existingChild !== null) {
13040 if (existingChild.key !== null) {
13041 existingChildren.set(existingChild.key, existingChild);
13042 } else {
13043 existingChildren.set(existingChild.index, existingChild);
13044 }
13045 existingChild = existingChild.sibling;
13046 }
13047 return existingChildren;
13048 }
13049
13050 function useFiber(fiber, pendingProps, expirationTime) {
13051 // We currently set sibling to null and index to 0 here because it is easy
13052 // to forget to do before returning it. E.g. for the single child case.
13053 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
13054 clone.index = 0;
13055 clone.sibling = null;
13056 return clone;
13057 }
13058
13059 function placeChild(newFiber, lastPlacedIndex, newIndex) {
13060 newFiber.index = newIndex;
13061 if (!shouldTrackSideEffects) {
13062 // Noop.
13063 return lastPlacedIndex;
13064 }
13065 var current$$1 = newFiber.alternate;
13066 if (current$$1 !== null) {
13067 var oldIndex = current$$1.index;
13068 if (oldIndex < lastPlacedIndex) {
13069 // This is a move.
13070 newFiber.effectTag = Placement;
13071 return lastPlacedIndex;
13072 } else {
13073 // This item can stay in place.
13074 return oldIndex;
13075 }
13076 } else {
13077 // This is an insertion.
13078 newFiber.effectTag = Placement;
13079 return lastPlacedIndex;
13080 }
13081 }
13082
13083 function placeSingleChild(newFiber) {
13084 // This is simpler for the single child case. We only need to do a
13085 // placement for inserting new children.
13086 if (shouldTrackSideEffects && newFiber.alternate === null) {
13087 newFiber.effectTag = Placement;
13088 }
13089 return newFiber;
13090 }
13091
13092 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
13093 if (current$$1 === null || current$$1.tag !== HostText) {
13094 // Insert
13095 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
13096 created.return = returnFiber;
13097 return created;
13098 } else {
13099 // Update
13100 var existing = useFiber(current$$1, textContent, expirationTime);
13101 existing.return = returnFiber;
13102 return existing;
13103 }
13104 }
13105
13106 function updateElement(returnFiber, current$$1, element, expirationTime) {
13107 if (current$$1 !== null && current$$1.elementType === element.type) {
13108 // Move based on index
13109 var existing = useFiber(current$$1, element.props, expirationTime);
13110 existing.ref = coerceRef(returnFiber, current$$1, element);
13111 existing.return = returnFiber;
13112 {
13113 existing._debugSource = element._source;
13114 existing._debugOwner = element._owner;
13115 }
13116 return existing;
13117 } else {
13118 // Insert
13119 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
13120 created.ref = coerceRef(returnFiber, current$$1, element);
13121 created.return = returnFiber;
13122 return created;
13123 }
13124 }
13125
13126 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
13127 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
13128 // Insert
13129 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
13130 created.return = returnFiber;
13131 return created;
13132 } else {
13133 // Update
13134 var existing = useFiber(current$$1, portal.children || [], expirationTime);
13135 existing.return = returnFiber;
13136 return existing;
13137 }
13138 }
13139
13140 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
13141 if (current$$1 === null || current$$1.tag !== Fragment) {
13142 // Insert
13143 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
13144 created.return = returnFiber;
13145 return created;
13146 } else {
13147 // Update
13148 var existing = useFiber(current$$1, fragment, expirationTime);
13149 existing.return = returnFiber;
13150 return existing;
13151 }
13152 }
13153
13154 function createChild(returnFiber, newChild, expirationTime) {
13155 if (typeof newChild === 'string' || typeof newChild === 'number') {
13156 // Text nodes don't have keys. If the previous node is implicitly keyed
13157 // we can continue to replace it without aborting even if it is not a text
13158 // node.
13159 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
13160 created.return = returnFiber;
13161 return created;
13162 }
13163
13164 if (typeof newChild === 'object' && newChild !== null) {
13165 switch (newChild.$$typeof) {
13166 case REACT_ELEMENT_TYPE:
13167 {
13168 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
13169 _created.ref = coerceRef(returnFiber, null, newChild);
13170 _created.return = returnFiber;
13171 return _created;
13172 }
13173 case REACT_PORTAL_TYPE:
13174 {
13175 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
13176 _created2.return = returnFiber;
13177 return _created2;
13178 }
13179 }
13180
13181 if (isArray(newChild) || getIteratorFn(newChild)) {
13182 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
13183 _created3.return = returnFiber;
13184 return _created3;
13185 }
13186
13187 throwOnInvalidObjectType(returnFiber, newChild);
13188 }
13189
13190 {
13191 if (typeof newChild === 'function') {
13192 warnOnFunctionType();
13193 }
13194 }
13195
13196 return null;
13197 }
13198
13199 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
13200 // Update the fiber if the keys match, otherwise return null.
13201
13202 var key = oldFiber !== null ? oldFiber.key : null;
13203
13204 if (typeof newChild === 'string' || typeof newChild === 'number') {
13205 // Text nodes don't have keys. If the previous node is implicitly keyed
13206 // we can continue to replace it without aborting even if it is not a text
13207 // node.
13208 if (key !== null) {
13209 return null;
13210 }
13211 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
13212 }
13213
13214 if (typeof newChild === 'object' && newChild !== null) {
13215 switch (newChild.$$typeof) {
13216 case REACT_ELEMENT_TYPE:
13217 {
13218 if (newChild.key === key) {
13219 if (newChild.type === REACT_FRAGMENT_TYPE) {
13220 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
13221 }
13222 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
13223 } else {
13224 return null;
13225 }
13226 }
13227 case REACT_PORTAL_TYPE:
13228 {
13229 if (newChild.key === key) {
13230 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
13231 } else {
13232 return null;
13233 }
13234 }
13235 }
13236
13237 if (isArray(newChild) || getIteratorFn(newChild)) {
13238 if (key !== null) {
13239 return null;
13240 }
13241
13242 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
13243 }
13244
13245 throwOnInvalidObjectType(returnFiber, newChild);
13246 }
13247
13248 {
13249 if (typeof newChild === 'function') {
13250 warnOnFunctionType();
13251 }
13252 }
13253
13254 return null;
13255 }
13256
13257 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
13258 if (typeof newChild === 'string' || typeof newChild === 'number') {
13259 // Text nodes don't have keys, so we neither have to check the old nor
13260 // new node for the key. If both are text nodes, they match.
13261 var matchedFiber = existingChildren.get(newIdx) || null;
13262 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
13263 }
13264
13265 if (typeof newChild === 'object' && newChild !== null) {
13266 switch (newChild.$$typeof) {
13267 case REACT_ELEMENT_TYPE:
13268 {
13269 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13270 if (newChild.type === REACT_FRAGMENT_TYPE) {
13271 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
13272 }
13273 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
13274 }
13275 case REACT_PORTAL_TYPE:
13276 {
13277 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13278 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
13279 }
13280 }
13281
13282 if (isArray(newChild) || getIteratorFn(newChild)) {
13283 var _matchedFiber3 = existingChildren.get(newIdx) || null;
13284 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
13285 }
13286
13287 throwOnInvalidObjectType(returnFiber, newChild);
13288 }
13289
13290 {
13291 if (typeof newChild === 'function') {
13292 warnOnFunctionType();
13293 }
13294 }
13295
13296 return null;
13297 }
13298
13299 /**
13300 * Warns if there is a duplicate or missing key
13301 */
13302 function warnOnInvalidKey(child, knownKeys) {
13303 {
13304 if (typeof child !== 'object' || child === null) {
13305 return knownKeys;
13306 }
13307 switch (child.$$typeof) {
13308 case REACT_ELEMENT_TYPE:
13309 case REACT_PORTAL_TYPE:
13310 warnForMissingKey(child);
13311 var key = child.key;
13312 if (typeof key !== 'string') {
13313 break;
13314 }
13315 if (knownKeys === null) {
13316 knownKeys = new Set();
13317 knownKeys.add(key);
13318 break;
13319 }
13320 if (!knownKeys.has(key)) {
13321 knownKeys.add(key);
13322 break;
13323 }
13324 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);
13325 break;
13326 default:
13327 break;
13328 }
13329 }
13330 return knownKeys;
13331 }
13332
13333 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
13334 // This algorithm can't optimize by searching from both ends since we
13335 // don't have backpointers on fibers. I'm trying to see how far we can get
13336 // with that model. If it ends up not being worth the tradeoffs, we can
13337 // add it later.
13338
13339 // Even with a two ended optimization, we'd want to optimize for the case
13340 // where there are few changes and brute force the comparison instead of
13341 // going for the Map. It'd like to explore hitting that path first in
13342 // forward-only mode and only go for the Map once we notice that we need
13343 // lots of look ahead. This doesn't handle reversal as well as two ended
13344 // search but that's unusual. Besides, for the two ended optimization to
13345 // work on Iterables, we'd need to copy the whole set.
13346
13347 // In this first iteration, we'll just live with hitting the bad case
13348 // (adding everything to a Map) in for every insert/move.
13349
13350 // If you change this code, also update reconcileChildrenIterator() which
13351 // uses the same algorithm.
13352
13353 {
13354 // First, validate keys.
13355 var knownKeys = null;
13356 for (var i = 0; i < newChildren.length; i++) {
13357 var child = newChildren[i];
13358 knownKeys = warnOnInvalidKey(child, knownKeys);
13359 }
13360 }
13361
13362 var resultingFirstChild = null;
13363 var previousNewFiber = null;
13364
13365 var oldFiber = currentFirstChild;
13366 var lastPlacedIndex = 0;
13367 var newIdx = 0;
13368 var nextOldFiber = null;
13369 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
13370 if (oldFiber.index > newIdx) {
13371 nextOldFiber = oldFiber;
13372 oldFiber = null;
13373 } else {
13374 nextOldFiber = oldFiber.sibling;
13375 }
13376 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
13377 if (newFiber === null) {
13378 // TODO: This breaks on empty slots like null children. That's
13379 // unfortunate because it triggers the slow path all the time. We need
13380 // a better way to communicate whether this was a miss or null,
13381 // boolean, undefined, etc.
13382 if (oldFiber === null) {
13383 oldFiber = nextOldFiber;
13384 }
13385 break;
13386 }
13387 if (shouldTrackSideEffects) {
13388 if (oldFiber && newFiber.alternate === null) {
13389 // We matched the slot, but we didn't reuse the existing fiber, so we
13390 // need to delete the existing child.
13391 deleteChild(returnFiber, oldFiber);
13392 }
13393 }
13394 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13395 if (previousNewFiber === null) {
13396 // TODO: Move out of the loop. This only happens for the first run.
13397 resultingFirstChild = newFiber;
13398 } else {
13399 // TODO: Defer siblings if we're not at the right index for this slot.
13400 // I.e. if we had null values before, then we want to defer this
13401 // for each null value. However, we also don't want to call updateSlot
13402 // with the previous one.
13403 previousNewFiber.sibling = newFiber;
13404 }
13405 previousNewFiber = newFiber;
13406 oldFiber = nextOldFiber;
13407 }
13408
13409 if (newIdx === newChildren.length) {
13410 // We've reached the end of the new children. We can delete the rest.
13411 deleteRemainingChildren(returnFiber, oldFiber);
13412 return resultingFirstChild;
13413 }
13414
13415 if (oldFiber === null) {
13416 // If we don't have any more existing children we can choose a fast path
13417 // since the rest will all be insertions.
13418 for (; newIdx < newChildren.length; newIdx++) {
13419 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
13420 if (!_newFiber) {
13421 continue;
13422 }
13423 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
13424 if (previousNewFiber === null) {
13425 // TODO: Move out of the loop. This only happens for the first run.
13426 resultingFirstChild = _newFiber;
13427 } else {
13428 previousNewFiber.sibling = _newFiber;
13429 }
13430 previousNewFiber = _newFiber;
13431 }
13432 return resultingFirstChild;
13433 }
13434
13435 // Add all children to a key map for quick lookups.
13436 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
13437
13438 // Keep scanning and use the map to restore deleted items as moves.
13439 for (; newIdx < newChildren.length; newIdx++) {
13440 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
13441 if (_newFiber2) {
13442 if (shouldTrackSideEffects) {
13443 if (_newFiber2.alternate !== null) {
13444 // The new fiber is a work in progress, but if there exists a
13445 // current, that means that we reused the fiber. We need to delete
13446 // it from the child list so that we don't add it to the deletion
13447 // list.
13448 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
13449 }
13450 }
13451 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
13452 if (previousNewFiber === null) {
13453 resultingFirstChild = _newFiber2;
13454 } else {
13455 previousNewFiber.sibling = _newFiber2;
13456 }
13457 previousNewFiber = _newFiber2;
13458 }
13459 }
13460
13461 if (shouldTrackSideEffects) {
13462 // Any existing children that weren't consumed above were deleted. We need
13463 // to add them to the deletion list.
13464 existingChildren.forEach(function (child) {
13465 return deleteChild(returnFiber, child);
13466 });
13467 }
13468
13469 return resultingFirstChild;
13470 }
13471
13472 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
13473 // This is the same implementation as reconcileChildrenArray(),
13474 // but using the iterator instead.
13475
13476 var iteratorFn = getIteratorFn(newChildrenIterable);
13477 (function () {
13478 if (!(typeof iteratorFn === 'function')) {
13479 {
13480 throw ReactError('An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.');
13481 }
13482 }
13483 })();
13484
13485 {
13486 // We don't support rendering Generators because it's a mutation.
13487 // See https://github.com/facebook/react/issues/12995
13488 if (typeof Symbol === 'function' &&
13489 // $FlowFixMe Flow doesn't know about toStringTag
13490 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
13491 !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;
13492 didWarnAboutGenerators = true;
13493 }
13494
13495 // Warn about using Maps as children
13496 if (newChildrenIterable.entries === iteratorFn) {
13497 !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;
13498 didWarnAboutMaps = true;
13499 }
13500
13501 // First, validate keys.
13502 // We'll get a different iterator later for the main pass.
13503 var _newChildren = iteratorFn.call(newChildrenIterable);
13504 if (_newChildren) {
13505 var knownKeys = null;
13506 var _step = _newChildren.next();
13507 for (; !_step.done; _step = _newChildren.next()) {
13508 var child = _step.value;
13509 knownKeys = warnOnInvalidKey(child, knownKeys);
13510 }
13511 }
13512 }
13513
13514 var newChildren = iteratorFn.call(newChildrenIterable);
13515 (function () {
13516 if (!(newChildren != null)) {
13517 {
13518 throw ReactError('An iterable object provided no iterator.');
13519 }
13520 }
13521 })();
13522
13523 var resultingFirstChild = null;
13524 var previousNewFiber = null;
13525
13526 var oldFiber = currentFirstChild;
13527 var lastPlacedIndex = 0;
13528 var newIdx = 0;
13529 var nextOldFiber = null;
13530
13531 var step = newChildren.next();
13532 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
13533 if (oldFiber.index > newIdx) {
13534 nextOldFiber = oldFiber;
13535 oldFiber = null;
13536 } else {
13537 nextOldFiber = oldFiber.sibling;
13538 }
13539 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
13540 if (newFiber === null) {
13541 // TODO: This breaks on empty slots like null children. That's
13542 // unfortunate because it triggers the slow path all the time. We need
13543 // a better way to communicate whether this was a miss or null,
13544 // boolean, undefined, etc.
13545 if (!oldFiber) {
13546 oldFiber = nextOldFiber;
13547 }
13548 break;
13549 }
13550 if (shouldTrackSideEffects) {
13551 if (oldFiber && newFiber.alternate === null) {
13552 // We matched the slot, but we didn't reuse the existing fiber, so we
13553 // need to delete the existing child.
13554 deleteChild(returnFiber, oldFiber);
13555 }
13556 }
13557 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13558 if (previousNewFiber === null) {
13559 // TODO: Move out of the loop. This only happens for the first run.
13560 resultingFirstChild = newFiber;
13561 } else {
13562 // TODO: Defer siblings if we're not at the right index for this slot.
13563 // I.e. if we had null values before, then we want to defer this
13564 // for each null value. However, we also don't want to call updateSlot
13565 // with the previous one.
13566 previousNewFiber.sibling = newFiber;
13567 }
13568 previousNewFiber = newFiber;
13569 oldFiber = nextOldFiber;
13570 }
13571
13572 if (step.done) {
13573 // We've reached the end of the new children. We can delete the rest.
13574 deleteRemainingChildren(returnFiber, oldFiber);
13575 return resultingFirstChild;
13576 }
13577
13578 if (oldFiber === null) {
13579 // If we don't have any more existing children we can choose a fast path
13580 // since the rest will all be insertions.
13581 for (; !step.done; newIdx++, step = newChildren.next()) {
13582 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
13583 if (_newFiber3 === null) {
13584 continue;
13585 }
13586 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
13587 if (previousNewFiber === null) {
13588 // TODO: Move out of the loop. This only happens for the first run.
13589 resultingFirstChild = _newFiber3;
13590 } else {
13591 previousNewFiber.sibling = _newFiber3;
13592 }
13593 previousNewFiber = _newFiber3;
13594 }
13595 return resultingFirstChild;
13596 }
13597
13598 // Add all children to a key map for quick lookups.
13599 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
13600
13601 // Keep scanning and use the map to restore deleted items as moves.
13602 for (; !step.done; newIdx++, step = newChildren.next()) {
13603 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
13604 if (_newFiber4 !== null) {
13605 if (shouldTrackSideEffects) {
13606 if (_newFiber4.alternate !== null) {
13607 // The new fiber is a work in progress, but if there exists a
13608 // current, that means that we reused the fiber. We need to delete
13609 // it from the child list so that we don't add it to the deletion
13610 // list.
13611 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
13612 }
13613 }
13614 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
13615 if (previousNewFiber === null) {
13616 resultingFirstChild = _newFiber4;
13617 } else {
13618 previousNewFiber.sibling = _newFiber4;
13619 }
13620 previousNewFiber = _newFiber4;
13621 }
13622 }
13623
13624 if (shouldTrackSideEffects) {
13625 // Any existing children that weren't consumed above were deleted. We need
13626 // to add them to the deletion list.
13627 existingChildren.forEach(function (child) {
13628 return deleteChild(returnFiber, child);
13629 });
13630 }
13631
13632 return resultingFirstChild;
13633 }
13634
13635 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
13636 // There's no need to check for keys on text nodes since we don't have a
13637 // way to define them.
13638 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
13639 // We already have an existing node so let's just update it and delete
13640 // the rest.
13641 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
13642 var existing = useFiber(currentFirstChild, textContent, expirationTime);
13643 existing.return = returnFiber;
13644 return existing;
13645 }
13646 // The existing first child is not a text node so we need to create one
13647 // and delete the existing ones.
13648 deleteRemainingChildren(returnFiber, currentFirstChild);
13649 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
13650 created.return = returnFiber;
13651 return created;
13652 }
13653
13654 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
13655 var key = element.key;
13656 var child = currentFirstChild;
13657 while (child !== null) {
13658 // TODO: If key === null and child.key === null, then this only applies to
13659 // the first item in the list.
13660 if (child.key === key) {
13661 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
13662 deleteRemainingChildren(returnFiber, child.sibling);
13663 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
13664 existing.ref = coerceRef(returnFiber, child, element);
13665 existing.return = returnFiber;
13666 {
13667 existing._debugSource = element._source;
13668 existing._debugOwner = element._owner;
13669 }
13670 return existing;
13671 } else {
13672 deleteRemainingChildren(returnFiber, child);
13673 break;
13674 }
13675 } else {
13676 deleteChild(returnFiber, child);
13677 }
13678 child = child.sibling;
13679 }
13680
13681 if (element.type === REACT_FRAGMENT_TYPE) {
13682 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
13683 created.return = returnFiber;
13684 return created;
13685 } else {
13686 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
13687 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
13688 _created4.return = returnFiber;
13689 return _created4;
13690 }
13691 }
13692
13693 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
13694 var key = portal.key;
13695 var child = currentFirstChild;
13696 while (child !== null) {
13697 // TODO: If key === null and child.key === null, then this only applies to
13698 // the first item in the list.
13699 if (child.key === key) {
13700 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
13701 deleteRemainingChildren(returnFiber, child.sibling);
13702 var existing = useFiber(child, portal.children || [], expirationTime);
13703 existing.return = returnFiber;
13704 return existing;
13705 } else {
13706 deleteRemainingChildren(returnFiber, child);
13707 break;
13708 }
13709 } else {
13710 deleteChild(returnFiber, child);
13711 }
13712 child = child.sibling;
13713 }
13714
13715 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
13716 created.return = returnFiber;
13717 return created;
13718 }
13719
13720 // This API will tag the children with the side-effect of the reconciliation
13721 // itself. They will be added to the side-effect list as we pass through the
13722 // children and the parent.
13723 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
13724 // This function is not recursive.
13725 // If the top level item is an array, we treat it as a set of children,
13726 // not as a fragment. Nested arrays on the other hand will be treated as
13727 // fragment nodes. Recursion happens at the normal flow.
13728
13729 // Handle top level unkeyed fragments as if they were arrays.
13730 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
13731 // We treat the ambiguous cases above the same.
13732 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
13733 if (isUnkeyedTopLevelFragment) {
13734 newChild = newChild.props.children;
13735 }
13736
13737 // Handle object types
13738 var isObject = typeof newChild === 'object' && newChild !== null;
13739
13740 if (isObject) {
13741 switch (newChild.$$typeof) {
13742 case REACT_ELEMENT_TYPE:
13743 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
13744 case REACT_PORTAL_TYPE:
13745 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
13746 }
13747 }
13748
13749 if (typeof newChild === 'string' || typeof newChild === 'number') {
13750 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
13751 }
13752
13753 if (isArray(newChild)) {
13754 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
13755 }
13756
13757 if (getIteratorFn(newChild)) {
13758 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
13759 }
13760
13761 if (isObject) {
13762 throwOnInvalidObjectType(returnFiber, newChild);
13763 }
13764
13765 {
13766 if (typeof newChild === 'function') {
13767 warnOnFunctionType();
13768 }
13769 }
13770 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
13771 // If the new child is undefined, and the return fiber is a composite
13772 // component, throw an error. If Fiber return types are disabled,
13773 // we already threw above.
13774 switch (returnFiber.tag) {
13775 case ClassComponent:
13776 {
13777 {
13778 var instance = returnFiber.stateNode;
13779 if (instance.render._isMockFunction) {
13780 // We allow auto-mocks to proceed as if they're returning null.
13781 break;
13782 }
13783 }
13784 }
13785 // Intentionally fall through to the next case, which handles both
13786 // functions and classes
13787 // eslint-disable-next-lined no-fallthrough
13788 case FunctionComponent:
13789 {
13790 var Component = returnFiber.type;
13791 (function () {
13792 {
13793 {
13794 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.');
13795 }
13796 }
13797 })();
13798 }
13799 }
13800 }
13801
13802 // Remaining cases are all treated as empty.
13803 return deleteRemainingChildren(returnFiber, currentFirstChild);
13804 }
13805
13806 return reconcileChildFibers;
13807}
13808
13809var reconcileChildFibers = ChildReconciler(true);
13810var mountChildFibers = ChildReconciler(false);
13811
13812function cloneChildFibers(current$$1, workInProgress) {
13813 (function () {
13814 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
13815 {
13816 throw ReactError('Resuming work not yet implemented.');
13817 }
13818 }
13819 })();
13820
13821 if (workInProgress.child === null) {
13822 return;
13823 }
13824
13825 var currentChild = workInProgress.child;
13826 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
13827 workInProgress.child = newChild;
13828
13829 newChild.return = workInProgress;
13830 while (currentChild.sibling !== null) {
13831 currentChild = currentChild.sibling;
13832 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
13833 newChild.return = workInProgress;
13834 }
13835 newChild.sibling = null;
13836}
13837
13838var NO_CONTEXT = {};
13839
13840var contextStackCursor$1 = createCursor(NO_CONTEXT);
13841var contextFiberStackCursor = createCursor(NO_CONTEXT);
13842var rootInstanceStackCursor = createCursor(NO_CONTEXT);
13843
13844function requiredContext(c) {
13845 (function () {
13846 if (!(c !== NO_CONTEXT)) {
13847 {
13848 throw ReactError('Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.');
13849 }
13850 }
13851 })();
13852 return c;
13853}
13854
13855function getRootHostContainer() {
13856 var rootInstance = requiredContext(rootInstanceStackCursor.current);
13857 return rootInstance;
13858}
13859
13860function pushHostContainer(fiber, nextRootInstance) {
13861 // Push current root instance onto the stack;
13862 // This allows us to reset root when portals are popped.
13863 push(rootInstanceStackCursor, nextRootInstance, fiber);
13864 // Track the context and the Fiber that provided it.
13865 // This enables us to pop only Fibers that provide unique contexts.
13866 push(contextFiberStackCursor, fiber, fiber);
13867
13868 // Finally, we need to push the host context to the stack.
13869 // However, we can't just call getRootHostContext() and push it because
13870 // we'd have a different number of entries on the stack depending on
13871 // whether getRootHostContext() throws somewhere in renderer code or not.
13872 // So we push an empty value first. This lets us safely unwind on errors.
13873 push(contextStackCursor$1, NO_CONTEXT, fiber);
13874 var nextRootContext = getRootHostContext(nextRootInstance);
13875 // Now that we know this function doesn't throw, replace it.
13876 pop(contextStackCursor$1, fiber);
13877 push(contextStackCursor$1, nextRootContext, fiber);
13878}
13879
13880function popHostContainer(fiber) {
13881 pop(contextStackCursor$1, fiber);
13882 pop(contextFiberStackCursor, fiber);
13883 pop(rootInstanceStackCursor, fiber);
13884}
13885
13886function getHostContext() {
13887 var context = requiredContext(contextStackCursor$1.current);
13888 return context;
13889}
13890
13891function pushHostContext(fiber) {
13892 var rootInstance = requiredContext(rootInstanceStackCursor.current);
13893 var context = requiredContext(contextStackCursor$1.current);
13894 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
13895
13896 // Don't push this Fiber's context unless it's unique.
13897 if (context === nextContext) {
13898 return;
13899 }
13900
13901 // Track the context and the Fiber that provided it.
13902 // This enables us to pop only Fibers that provide unique contexts.
13903 push(contextFiberStackCursor, fiber, fiber);
13904 push(contextStackCursor$1, nextContext, fiber);
13905}
13906
13907function pushHostContextForEventComponent(fiber) {
13908 var context = requiredContext(contextStackCursor$1.current);
13909 var nextContext = getChildHostContextForEventComponent(context);
13910
13911 // Don't push this Fiber's context unless it's unique.
13912 if (context === nextContext) {
13913 return;
13914 }
13915
13916 // Track the context and the Fiber that provided it.
13917 // This enables us to pop only Fibers that provide unique contexts.
13918 push(contextFiberStackCursor, fiber, fiber);
13919 push(contextStackCursor$1, nextContext, fiber);
13920}
13921
13922function pushHostContextForEventTarget(fiber) {
13923 var context = requiredContext(contextStackCursor$1.current);
13924 var eventTargetType = fiber.type.type;
13925 var nextContext = getChildHostContextForEventTarget(context, eventTargetType);
13926
13927 // Don't push this Fiber's context unless it's unique.
13928 if (context === nextContext) {
13929 return;
13930 }
13931
13932 // Track the context and the Fiber that provided it.
13933 // This enables us to pop only Fibers that provide unique contexts.
13934 push(contextFiberStackCursor, fiber, fiber);
13935 push(contextStackCursor$1, nextContext, fiber);
13936}
13937
13938function popHostContext(fiber) {
13939 // Do not pop unless this Fiber provided the current context.
13940 // pushHostContext() only pushes Fibers that provide unique contexts.
13941 if (contextFiberStackCursor.current !== fiber) {
13942 return;
13943 }
13944
13945 pop(contextStackCursor$1, fiber);
13946 pop(contextFiberStackCursor, fiber);
13947}
13948
13949var NoEffect$1 = /* */0;
13950var UnmountSnapshot = /* */2;
13951var UnmountMutation = /* */4;
13952var MountMutation = /* */8;
13953var UnmountLayout = /* */16;
13954var MountLayout = /* */32;
13955var MountPassive = /* */64;
13956var UnmountPassive = /* */128;
13957
13958var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
13959
13960
13961var didWarnAboutMismatchedHooksForComponent = void 0;
13962{
13963 didWarnAboutMismatchedHooksForComponent = new Set();
13964}
13965
13966// These are set right before calling the component.
13967var renderExpirationTime = NoWork;
13968// The work-in-progress fiber. I've named it differently to distinguish it from
13969// the work-in-progress hook.
13970var currentlyRenderingFiber$1 = null;
13971
13972// Hooks are stored as a linked list on the fiber's memoizedState field. The
13973// current hook list is the list that belongs to the current fiber. The
13974// work-in-progress hook list is a new list that will be added to the
13975// work-in-progress fiber.
13976var currentHook = null;
13977var nextCurrentHook = null;
13978var firstWorkInProgressHook = null;
13979var workInProgressHook = null;
13980var nextWorkInProgressHook = null;
13981
13982var remainingExpirationTime = NoWork;
13983var componentUpdateQueue = null;
13984var sideEffectTag = 0;
13985
13986// Updates scheduled during render will trigger an immediate re-render at the
13987// end of the current pass. We can't store these updates on the normal queue,
13988// because if the work is aborted, they should be discarded. Because this is
13989// a relatively rare case, we also don't want to add an additional field to
13990// either the hook or queue object types. So we store them in a lazily create
13991// map of queue -> render-phase updates, which are discarded once the component
13992// completes without re-rendering.
13993
13994// Whether an update was scheduled during the currently executing render pass.
13995var didScheduleRenderPhaseUpdate = false;
13996// Lazily created map of render-phase updates
13997var renderPhaseUpdates = null;
13998// Counter to prevent infinite loops.
13999var numberOfReRenders = 0;
14000var RE_RENDER_LIMIT = 25;
14001
14002// In DEV, this is the name of the currently executing primitive hook
14003var currentHookNameInDev = null;
14004
14005// In DEV, this list ensures that hooks are called in the same order between renders.
14006// The list stores the order of hooks used during the initial render (mount).
14007// Subsequent renders (updates) reference this list.
14008var hookTypesDev = null;
14009var hookTypesUpdateIndexDev = -1;
14010
14011function mountHookTypesDev() {
14012 {
14013 var hookName = currentHookNameInDev;
14014
14015 if (hookTypesDev === null) {
14016 hookTypesDev = [hookName];
14017 } else {
14018 hookTypesDev.push(hookName);
14019 }
14020 }
14021}
14022
14023function updateHookTypesDev() {
14024 {
14025 var hookName = currentHookNameInDev;
14026
14027 if (hookTypesDev !== null) {
14028 hookTypesUpdateIndexDev++;
14029 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
14030 warnOnHookMismatchInDev(hookName);
14031 }
14032 }
14033 }
14034}
14035
14036function checkDepsAreArrayDev(deps) {
14037 {
14038 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
14039 // Verify deps, but only on mount to avoid extra checks.
14040 // It's unlikely their type would change as usually you define them inline.
14041 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);
14042 }
14043 }
14044}
14045
14046function warnOnHookMismatchInDev(currentHookName) {
14047 {
14048 var componentName = getComponentName(currentlyRenderingFiber$1.type);
14049 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
14050 didWarnAboutMismatchedHooksForComponent.add(componentName);
14051
14052 if (hookTypesDev !== null) {
14053 var table = '';
14054
14055 var secondColumnStart = 30;
14056
14057 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
14058 var oldHookName = hookTypesDev[i];
14059 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
14060
14061 var row = i + 1 + '. ' + oldHookName;
14062
14063 // Extra space so second column lines up
14064 // lol @ IE not supporting String#repeat
14065 while (row.length < secondColumnStart) {
14066 row += ' ';
14067 }
14068
14069 row += newHookName + '\n';
14070
14071 table += row;
14072 }
14073
14074 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);
14075 }
14076 }
14077 }
14078}
14079
14080function throwInvalidHookError() {
14081 (function () {
14082 {
14083 {
14084 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.');
14085 }
14086 }
14087 })();
14088}
14089
14090function areHookInputsEqual(nextDeps, prevDeps) {
14091 if (prevDeps === null) {
14092 {
14093 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);
14094 }
14095 return false;
14096 }
14097
14098 {
14099 // Don't bother comparing lengths in prod because these arrays should be
14100 // passed inline.
14101 if (nextDeps.length !== prevDeps.length) {
14102 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(', ') + ']');
14103 }
14104 }
14105 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
14106 if (is(nextDeps[i], prevDeps[i])) {
14107 continue;
14108 }
14109 return false;
14110 }
14111 return true;
14112}
14113
14114function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
14115 renderExpirationTime = nextRenderExpirationTime;
14116 currentlyRenderingFiber$1 = workInProgress;
14117 nextCurrentHook = current !== null ? current.memoizedState : null;
14118
14119 {
14120 hookTypesDev = current !== null ? current._debugHookTypes : null;
14121 hookTypesUpdateIndexDev = -1;
14122 }
14123
14124 // The following should have already been reset
14125 // currentHook = null;
14126 // workInProgressHook = null;
14127
14128 // remainingExpirationTime = NoWork;
14129 // componentUpdateQueue = null;
14130
14131 // didScheduleRenderPhaseUpdate = false;
14132 // renderPhaseUpdates = null;
14133 // numberOfReRenders = 0;
14134 // sideEffectTag = 0;
14135
14136 // TODO Warn if no hooks are used at all during mount, then some are used during update.
14137 // Currently we will identify the update render as a mount because nextCurrentHook === null.
14138 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
14139
14140 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
14141 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
14142 // so nextCurrentHook would be null during updates and mounts.
14143 {
14144 if (nextCurrentHook !== null) {
14145 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
14146 } else if (hookTypesDev !== null) {
14147 // This dispatcher handles an edge case where a component is updating,
14148 // but no stateful hooks have been used.
14149 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
14150 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
14151 // This dispatcher does that.
14152 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
14153 } else {
14154 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
14155 }
14156 }
14157
14158 var children = Component(props, refOrContext);
14159
14160 if (didScheduleRenderPhaseUpdate) {
14161 do {
14162 didScheduleRenderPhaseUpdate = false;
14163 numberOfReRenders += 1;
14164
14165 // Start over from the beginning of the list
14166 nextCurrentHook = current !== null ? current.memoizedState : null;
14167 nextWorkInProgressHook = firstWorkInProgressHook;
14168
14169 currentHook = null;
14170 workInProgressHook = null;
14171 componentUpdateQueue = null;
14172
14173 {
14174 // Also validate hook order for cascading updates.
14175 hookTypesUpdateIndexDev = -1;
14176 }
14177
14178 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
14179
14180 children = Component(props, refOrContext);
14181 } while (didScheduleRenderPhaseUpdate);
14182
14183 renderPhaseUpdates = null;
14184 numberOfReRenders = 0;
14185 }
14186
14187 // We can assume the previous dispatcher is always this one, since we set it
14188 // at the beginning of the render phase and there's no re-entrancy.
14189 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
14190
14191 var renderedWork = currentlyRenderingFiber$1;
14192
14193 renderedWork.memoizedState = firstWorkInProgressHook;
14194 renderedWork.expirationTime = remainingExpirationTime;
14195 renderedWork.updateQueue = componentUpdateQueue;
14196 renderedWork.effectTag |= sideEffectTag;
14197
14198 {
14199 renderedWork._debugHookTypes = hookTypesDev;
14200 }
14201
14202 // This check uses currentHook so that it works the same in DEV and prod bundles.
14203 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
14204 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
14205
14206 renderExpirationTime = NoWork;
14207 currentlyRenderingFiber$1 = null;
14208
14209 currentHook = null;
14210 nextCurrentHook = null;
14211 firstWorkInProgressHook = null;
14212 workInProgressHook = null;
14213 nextWorkInProgressHook = null;
14214
14215 {
14216 currentHookNameInDev = null;
14217 hookTypesDev = null;
14218 hookTypesUpdateIndexDev = -1;
14219 }
14220
14221 remainingExpirationTime = NoWork;
14222 componentUpdateQueue = null;
14223 sideEffectTag = 0;
14224
14225 // These were reset above
14226 // didScheduleRenderPhaseUpdate = false;
14227 // renderPhaseUpdates = null;
14228 // numberOfReRenders = 0;
14229
14230 (function () {
14231 if (!!didRenderTooFewHooks) {
14232 {
14233 throw ReactError('Rendered fewer hooks than expected. This may be caused by an accidental early return statement.');
14234 }
14235 }
14236 })();
14237
14238 return children;
14239}
14240
14241function bailoutHooks(current, workInProgress, expirationTime) {
14242 workInProgress.updateQueue = current.updateQueue;
14243 workInProgress.effectTag &= ~(Passive | Update);
14244 if (current.expirationTime <= expirationTime) {
14245 current.expirationTime = NoWork;
14246 }
14247}
14248
14249function resetHooks() {
14250 // We can assume the previous dispatcher is always this one, since we set it
14251 // at the beginning of the render phase and there's no re-entrancy.
14252 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
14253
14254 // This is used to reset the state of this module when a component throws.
14255 // It's also called inside mountIndeterminateComponent if we determine the
14256 // component is a module-style component.
14257 renderExpirationTime = NoWork;
14258 currentlyRenderingFiber$1 = null;
14259
14260 currentHook = null;
14261 nextCurrentHook = null;
14262 firstWorkInProgressHook = null;
14263 workInProgressHook = null;
14264 nextWorkInProgressHook = null;
14265
14266 {
14267 hookTypesDev = null;
14268 hookTypesUpdateIndexDev = -1;
14269
14270 currentHookNameInDev = null;
14271 }
14272
14273 remainingExpirationTime = NoWork;
14274 componentUpdateQueue = null;
14275 sideEffectTag = 0;
14276
14277 didScheduleRenderPhaseUpdate = false;
14278 renderPhaseUpdates = null;
14279 numberOfReRenders = 0;
14280}
14281
14282function mountWorkInProgressHook() {
14283 var hook = {
14284 memoizedState: null,
14285
14286 baseState: null,
14287 queue: null,
14288 baseUpdate: null,
14289
14290 next: null
14291 };
14292
14293 if (workInProgressHook === null) {
14294 // This is the first hook in the list
14295 firstWorkInProgressHook = workInProgressHook = hook;
14296 } else {
14297 // Append to the end of the list
14298 workInProgressHook = workInProgressHook.next = hook;
14299 }
14300 return workInProgressHook;
14301}
14302
14303function updateWorkInProgressHook() {
14304 // This function is used both for updates and for re-renders triggered by a
14305 // render phase update. It assumes there is either a current hook we can
14306 // clone, or a work-in-progress hook from a previous render pass that we can
14307 // use as a base. When we reach the end of the base list, we must switch to
14308 // the dispatcher used for mounts.
14309 if (nextWorkInProgressHook !== null) {
14310 // There's already a work-in-progress. Reuse it.
14311 workInProgressHook = nextWorkInProgressHook;
14312 nextWorkInProgressHook = workInProgressHook.next;
14313
14314 currentHook = nextCurrentHook;
14315 nextCurrentHook = currentHook !== null ? currentHook.next : null;
14316 } else {
14317 // Clone from the current hook.
14318 (function () {
14319 if (!(nextCurrentHook !== null)) {
14320 {
14321 throw ReactError('Rendered more hooks than during the previous render.');
14322 }
14323 }
14324 })();
14325 currentHook = nextCurrentHook;
14326
14327 var newHook = {
14328 memoizedState: currentHook.memoizedState,
14329
14330 baseState: currentHook.baseState,
14331 queue: currentHook.queue,
14332 baseUpdate: currentHook.baseUpdate,
14333
14334 next: null
14335 };
14336
14337 if (workInProgressHook === null) {
14338 // This is the first hook in the list.
14339 workInProgressHook = firstWorkInProgressHook = newHook;
14340 } else {
14341 // Append to the end of the list.
14342 workInProgressHook = workInProgressHook.next = newHook;
14343 }
14344 nextCurrentHook = currentHook.next;
14345 }
14346 return workInProgressHook;
14347}
14348
14349function createFunctionComponentUpdateQueue() {
14350 return {
14351 lastEffect: null
14352 };
14353}
14354
14355function basicStateReducer(state, action) {
14356 return typeof action === 'function' ? action(state) : action;
14357}
14358
14359function mountReducer(reducer, initialArg, init) {
14360 var hook = mountWorkInProgressHook();
14361 var initialState = void 0;
14362 if (init !== undefined) {
14363 initialState = init(initialArg);
14364 } else {
14365 initialState = initialArg;
14366 }
14367 hook.memoizedState = hook.baseState = initialState;
14368 var queue = hook.queue = {
14369 last: null,
14370 dispatch: null,
14371 lastRenderedReducer: reducer,
14372 lastRenderedState: initialState
14373 };
14374 var dispatch = queue.dispatch = dispatchAction.bind(null,
14375 // Flow doesn't know this is non-null, but we do.
14376 currentlyRenderingFiber$1, queue);
14377 return [hook.memoizedState, dispatch];
14378}
14379
14380function updateReducer(reducer, initialArg, init) {
14381 var hook = updateWorkInProgressHook();
14382 var queue = hook.queue;
14383 (function () {
14384 if (!(queue !== null)) {
14385 {
14386 throw ReactError('Should have a queue. This is likely a bug in React. Please file an issue.');
14387 }
14388 }
14389 })();
14390
14391 queue.lastRenderedReducer = reducer;
14392
14393 if (numberOfReRenders > 0) {
14394 // This is a re-render. Apply the new render phase updates to the previous
14395 var _dispatch = queue.dispatch;
14396 if (renderPhaseUpdates !== null) {
14397 // Render phase updates are stored in a map of queue -> linked list
14398 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
14399 if (firstRenderPhaseUpdate !== undefined) {
14400 renderPhaseUpdates.delete(queue);
14401 var newState = hook.memoizedState;
14402 var update = firstRenderPhaseUpdate;
14403 do {
14404 // Process this render phase update. We don't have to check the
14405 // priority because it will always be the same as the current
14406 // render's.
14407 var _action = update.action;
14408 newState = reducer(newState, _action);
14409 update = update.next;
14410 } while (update !== null);
14411
14412 // Mark that the fiber performed work, but only if the new state is
14413 // different from the current state.
14414 if (!is(newState, hook.memoizedState)) {
14415 markWorkInProgressReceivedUpdate();
14416 }
14417
14418 hook.memoizedState = newState;
14419 // Don't persist the state accumlated from the render phase updates to
14420 // the base state unless the queue is empty.
14421 // TODO: Not sure if this is the desired semantics, but it's what we
14422 // do for gDSFP. I can't remember why.
14423 if (hook.baseUpdate === queue.last) {
14424 hook.baseState = newState;
14425 }
14426
14427 queue.lastRenderedState = newState;
14428
14429 return [newState, _dispatch];
14430 }
14431 }
14432 return [hook.memoizedState, _dispatch];
14433 }
14434
14435 // The last update in the entire queue
14436 var last = queue.last;
14437 // The last update that is part of the base state.
14438 var baseUpdate = hook.baseUpdate;
14439 var baseState = hook.baseState;
14440
14441 // Find the first unprocessed update.
14442 var first = void 0;
14443 if (baseUpdate !== null) {
14444 if (last !== null) {
14445 // For the first update, the queue is a circular linked list where
14446 // `queue.last.next = queue.first`. Once the first update commits, and
14447 // the `baseUpdate` is no longer empty, we can unravel the list.
14448 last.next = null;
14449 }
14450 first = baseUpdate.next;
14451 } else {
14452 first = last !== null ? last.next : null;
14453 }
14454 if (first !== null) {
14455 var _newState = baseState;
14456 var newBaseState = null;
14457 var newBaseUpdate = null;
14458 var prevUpdate = baseUpdate;
14459 var _update = first;
14460 var didSkip = false;
14461 do {
14462 var updateExpirationTime = _update.expirationTime;
14463 if (updateExpirationTime < renderExpirationTime) {
14464 // Priority is insufficient. Skip this update. If this is the first
14465 // skipped update, the previous update/state is the new base
14466 // update/state.
14467 if (!didSkip) {
14468 didSkip = true;
14469 newBaseUpdate = prevUpdate;
14470 newBaseState = _newState;
14471 }
14472 // Update the remaining priority in the queue.
14473 if (updateExpirationTime > remainingExpirationTime) {
14474 remainingExpirationTime = updateExpirationTime;
14475 }
14476 } else {
14477 // Process this update.
14478 if (_update.eagerReducer === reducer) {
14479 // If this update was processed eagerly, and its reducer matches the
14480 // current reducer, we can use the eagerly computed state.
14481 _newState = _update.eagerState;
14482 } else {
14483 var _action2 = _update.action;
14484 _newState = reducer(_newState, _action2);
14485 }
14486 }
14487 prevUpdate = _update;
14488 _update = _update.next;
14489 } while (_update !== null && _update !== first);
14490
14491 if (!didSkip) {
14492 newBaseUpdate = prevUpdate;
14493 newBaseState = _newState;
14494 }
14495
14496 // Mark that the fiber performed work, but only if the new state is
14497 // different from the current state.
14498 if (!is(_newState, hook.memoizedState)) {
14499 markWorkInProgressReceivedUpdate();
14500 }
14501
14502 hook.memoizedState = _newState;
14503 hook.baseUpdate = newBaseUpdate;
14504 hook.baseState = newBaseState;
14505
14506 queue.lastRenderedState = _newState;
14507 }
14508
14509 var dispatch = queue.dispatch;
14510 return [hook.memoizedState, dispatch];
14511}
14512
14513function mountState(initialState) {
14514 var hook = mountWorkInProgressHook();
14515 if (typeof initialState === 'function') {
14516 initialState = initialState();
14517 }
14518 hook.memoizedState = hook.baseState = initialState;
14519 var queue = hook.queue = {
14520 last: null,
14521 dispatch: null,
14522 lastRenderedReducer: basicStateReducer,
14523 lastRenderedState: initialState
14524 };
14525 var dispatch = queue.dispatch = dispatchAction.bind(null,
14526 // Flow doesn't know this is non-null, but we do.
14527 currentlyRenderingFiber$1, queue);
14528 return [hook.memoizedState, dispatch];
14529}
14530
14531function updateState(initialState) {
14532 return updateReducer(basicStateReducer, initialState);
14533}
14534
14535function pushEffect(tag, create, destroy, deps) {
14536 var effect = {
14537 tag: tag,
14538 create: create,
14539 destroy: destroy,
14540 deps: deps,
14541 // Circular
14542 next: null
14543 };
14544 if (componentUpdateQueue === null) {
14545 componentUpdateQueue = createFunctionComponentUpdateQueue();
14546 componentUpdateQueue.lastEffect = effect.next = effect;
14547 } else {
14548 var _lastEffect = componentUpdateQueue.lastEffect;
14549 if (_lastEffect === null) {
14550 componentUpdateQueue.lastEffect = effect.next = effect;
14551 } else {
14552 var firstEffect = _lastEffect.next;
14553 _lastEffect.next = effect;
14554 effect.next = firstEffect;
14555 componentUpdateQueue.lastEffect = effect;
14556 }
14557 }
14558 return effect;
14559}
14560
14561function mountRef(initialValue) {
14562 var hook = mountWorkInProgressHook();
14563 var ref = { current: initialValue };
14564 {
14565 Object.seal(ref);
14566 }
14567 hook.memoizedState = ref;
14568 return ref;
14569}
14570
14571function updateRef(initialValue) {
14572 var hook = updateWorkInProgressHook();
14573 return hook.memoizedState;
14574}
14575
14576function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
14577 var hook = mountWorkInProgressHook();
14578 var nextDeps = deps === undefined ? null : deps;
14579 sideEffectTag |= fiberEffectTag;
14580 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
14581}
14582
14583function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
14584 var hook = updateWorkInProgressHook();
14585 var nextDeps = deps === undefined ? null : deps;
14586 var destroy = undefined;
14587
14588 if (currentHook !== null) {
14589 var prevEffect = currentHook.memoizedState;
14590 destroy = prevEffect.destroy;
14591 if (nextDeps !== null) {
14592 var prevDeps = prevEffect.deps;
14593 if (areHookInputsEqual(nextDeps, prevDeps)) {
14594 pushEffect(NoEffect$1, create, destroy, nextDeps);
14595 return;
14596 }
14597 }
14598 }
14599
14600 sideEffectTag |= fiberEffectTag;
14601 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
14602}
14603
14604function mountEffect(create, deps) {
14605 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
14606}
14607
14608function updateEffect(create, deps) {
14609 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
14610}
14611
14612function mountLayoutEffect(create, deps) {
14613 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
14614}
14615
14616function updateLayoutEffect(create, deps) {
14617 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
14618}
14619
14620function imperativeHandleEffect(create, ref) {
14621 if (typeof ref === 'function') {
14622 var refCallback = ref;
14623 var _inst = create();
14624 refCallback(_inst);
14625 return function () {
14626 refCallback(null);
14627 };
14628 } else if (ref !== null && ref !== undefined) {
14629 var refObject = ref;
14630 {
14631 !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;
14632 }
14633 var _inst2 = create();
14634 refObject.current = _inst2;
14635 return function () {
14636 refObject.current = null;
14637 };
14638 }
14639}
14640
14641function mountImperativeHandle(ref, create, deps) {
14642 {
14643 !(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;
14644 }
14645
14646 // TODO: If deps are provided, should we skip comparing the ref itself?
14647 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
14648
14649 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
14650}
14651
14652function updateImperativeHandle(ref, create, deps) {
14653 {
14654 !(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;
14655 }
14656
14657 // TODO: If deps are provided, should we skip comparing the ref itself?
14658 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
14659
14660 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
14661}
14662
14663function mountDebugValue(value, formatterFn) {
14664 // This hook is normally a no-op.
14665 // The react-debug-hooks package injects its own implementation
14666 // so that e.g. DevTools can display custom hook values.
14667}
14668
14669var updateDebugValue = mountDebugValue;
14670
14671function mountCallback(callback, deps) {
14672 var hook = mountWorkInProgressHook();
14673 var nextDeps = deps === undefined ? null : deps;
14674 hook.memoizedState = [callback, nextDeps];
14675 return callback;
14676}
14677
14678function updateCallback(callback, deps) {
14679 var hook = updateWorkInProgressHook();
14680 var nextDeps = deps === undefined ? null : deps;
14681 var prevState = hook.memoizedState;
14682 if (prevState !== null) {
14683 if (nextDeps !== null) {
14684 var prevDeps = prevState[1];
14685 if (areHookInputsEqual(nextDeps, prevDeps)) {
14686 return prevState[0];
14687 }
14688 }
14689 }
14690 hook.memoizedState = [callback, nextDeps];
14691 return callback;
14692}
14693
14694function mountMemo(nextCreate, deps) {
14695 var hook = mountWorkInProgressHook();
14696 var nextDeps = deps === undefined ? null : deps;
14697 var nextValue = nextCreate();
14698 hook.memoizedState = [nextValue, nextDeps];
14699 return nextValue;
14700}
14701
14702function updateMemo(nextCreate, deps) {
14703 var hook = updateWorkInProgressHook();
14704 var nextDeps = deps === undefined ? null : deps;
14705 var prevState = hook.memoizedState;
14706 if (prevState !== null) {
14707 // Assume these are defined. If they're not, areHookInputsEqual will warn.
14708 if (nextDeps !== null) {
14709 var prevDeps = prevState[1];
14710 if (areHookInputsEqual(nextDeps, prevDeps)) {
14711 return prevState[0];
14712 }
14713 }
14714 }
14715 var nextValue = nextCreate();
14716 hook.memoizedState = [nextValue, nextDeps];
14717 return nextValue;
14718}
14719
14720function dispatchAction(fiber, queue, action) {
14721 (function () {
14722 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
14723 {
14724 throw ReactError('Too many re-renders. React limits the number of renders to prevent an infinite loop.');
14725 }
14726 }
14727 })();
14728
14729 {
14730 !(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;
14731 }
14732
14733 var alternate = fiber.alternate;
14734 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
14735 // This is a render phase update. Stash it in a lazily-created map of
14736 // queue -> linked list of updates. After this render pass, we'll restart
14737 // and apply the stashed updates on top of the work-in-progress hook.
14738 didScheduleRenderPhaseUpdate = true;
14739 var update = {
14740 expirationTime: renderExpirationTime,
14741 action: action,
14742 eagerReducer: null,
14743 eagerState: null,
14744 next: null
14745 };
14746 if (renderPhaseUpdates === null) {
14747 renderPhaseUpdates = new Map();
14748 }
14749 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
14750 if (firstRenderPhaseUpdate === undefined) {
14751 renderPhaseUpdates.set(queue, update);
14752 } else {
14753 // Append the update to the end of the list.
14754 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
14755 while (lastRenderPhaseUpdate.next !== null) {
14756 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
14757 }
14758 lastRenderPhaseUpdate.next = update;
14759 }
14760 } else {
14761 flushPassiveEffects$$1();
14762
14763 var currentTime = requestCurrentTime$$1();
14764 var _expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
14765
14766 var _update2 = {
14767 expirationTime: _expirationTime,
14768 action: action,
14769 eagerReducer: null,
14770 eagerState: null,
14771 next: null
14772 };
14773
14774 // Append the update to the end of the list.
14775 var _last = queue.last;
14776 if (_last === null) {
14777 // This is the first update. Create a circular list.
14778 _update2.next = _update2;
14779 } else {
14780 var first = _last.next;
14781 if (first !== null) {
14782 // Still circular.
14783 _update2.next = first;
14784 }
14785 _last.next = _update2;
14786 }
14787 queue.last = _update2;
14788
14789 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
14790 // The queue is currently empty, which means we can eagerly compute the
14791 // next state before entering the render phase. If the new state is the
14792 // same as the current state, we may be able to bail out entirely.
14793 var _lastRenderedReducer = queue.lastRenderedReducer;
14794 if (_lastRenderedReducer !== null) {
14795 var prevDispatcher = void 0;
14796 {
14797 prevDispatcher = ReactCurrentDispatcher$1.current;
14798 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
14799 }
14800 try {
14801 var currentState = queue.lastRenderedState;
14802 var _eagerState = _lastRenderedReducer(currentState, action);
14803 // Stash the eagerly computed state, and the reducer used to compute
14804 // it, on the update object. If the reducer hasn't changed by the
14805 // time we enter the render phase, then the eager state can be used
14806 // without calling the reducer again.
14807 _update2.eagerReducer = _lastRenderedReducer;
14808 _update2.eagerState = _eagerState;
14809 if (is(_eagerState, currentState)) {
14810 // Fast path. We can bail out without scheduling React to re-render.
14811 // It's still possible that we'll need to rebase this update later,
14812 // if the component re-renders for a different reason and by that
14813 // time the reducer has changed.
14814 return;
14815 }
14816 } catch (error) {
14817 // Suppress the error. It will throw again in the render phase.
14818 } finally {
14819 {
14820 ReactCurrentDispatcher$1.current = prevDispatcher;
14821 }
14822 }
14823 }
14824 }
14825 {
14826 // jest isn't a 'global', it's just exposed to tests via a wrapped function
14827 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
14828 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
14829 if ('undefined' !== typeof jest) {
14830 warnIfNotCurrentlyActingUpdatesInDev$$1(fiber);
14831 }
14832 }
14833 scheduleWork$$1(fiber, _expirationTime);
14834 }
14835}
14836
14837var ContextOnlyDispatcher = {
14838 readContext: readContext,
14839
14840 useCallback: throwInvalidHookError,
14841 useContext: throwInvalidHookError,
14842 useEffect: throwInvalidHookError,
14843 useImperativeHandle: throwInvalidHookError,
14844 useLayoutEffect: throwInvalidHookError,
14845 useMemo: throwInvalidHookError,
14846 useReducer: throwInvalidHookError,
14847 useRef: throwInvalidHookError,
14848 useState: throwInvalidHookError,
14849 useDebugValue: throwInvalidHookError
14850};
14851
14852var HooksDispatcherOnMountInDEV = null;
14853var HooksDispatcherOnMountWithHookTypesInDEV = null;
14854var HooksDispatcherOnUpdateInDEV = null;
14855var InvalidNestedHooksDispatcherOnMountInDEV = null;
14856var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
14857
14858{
14859 var warnInvalidContextAccess = function () {
14860 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().');
14861 };
14862
14863 var warnInvalidHookAccess = function () {
14864 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');
14865 };
14866
14867 HooksDispatcherOnMountInDEV = {
14868 readContext: function (context, observedBits) {
14869 return readContext(context, observedBits);
14870 },
14871 useCallback: function (callback, deps) {
14872 currentHookNameInDev = 'useCallback';
14873 mountHookTypesDev();
14874 checkDepsAreArrayDev(deps);
14875 return mountCallback(callback, deps);
14876 },
14877 useContext: function (context, observedBits) {
14878 currentHookNameInDev = 'useContext';
14879 mountHookTypesDev();
14880 return readContext(context, observedBits);
14881 },
14882 useEffect: function (create, deps) {
14883 currentHookNameInDev = 'useEffect';
14884 mountHookTypesDev();
14885 checkDepsAreArrayDev(deps);
14886 return mountEffect(create, deps);
14887 },
14888 useImperativeHandle: function (ref, create, deps) {
14889 currentHookNameInDev = 'useImperativeHandle';
14890 mountHookTypesDev();
14891 checkDepsAreArrayDev(deps);
14892 return mountImperativeHandle(ref, create, deps);
14893 },
14894 useLayoutEffect: function (create, deps) {
14895 currentHookNameInDev = 'useLayoutEffect';
14896 mountHookTypesDev();
14897 checkDepsAreArrayDev(deps);
14898 return mountLayoutEffect(create, deps);
14899 },
14900 useMemo: function (create, deps) {
14901 currentHookNameInDev = 'useMemo';
14902 mountHookTypesDev();
14903 checkDepsAreArrayDev(deps);
14904 var prevDispatcher = ReactCurrentDispatcher$1.current;
14905 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14906 try {
14907 return mountMemo(create, deps);
14908 } finally {
14909 ReactCurrentDispatcher$1.current = prevDispatcher;
14910 }
14911 },
14912 useReducer: function (reducer, initialArg, init) {
14913 currentHookNameInDev = 'useReducer';
14914 mountHookTypesDev();
14915 var prevDispatcher = ReactCurrentDispatcher$1.current;
14916 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14917 try {
14918 return mountReducer(reducer, initialArg, init);
14919 } finally {
14920 ReactCurrentDispatcher$1.current = prevDispatcher;
14921 }
14922 },
14923 useRef: function (initialValue) {
14924 currentHookNameInDev = 'useRef';
14925 mountHookTypesDev();
14926 return mountRef(initialValue);
14927 },
14928 useState: function (initialState) {
14929 currentHookNameInDev = 'useState';
14930 mountHookTypesDev();
14931 var prevDispatcher = ReactCurrentDispatcher$1.current;
14932 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14933 try {
14934 return mountState(initialState);
14935 } finally {
14936 ReactCurrentDispatcher$1.current = prevDispatcher;
14937 }
14938 },
14939 useDebugValue: function (value, formatterFn) {
14940 currentHookNameInDev = 'useDebugValue';
14941 mountHookTypesDev();
14942 return mountDebugValue(value, formatterFn);
14943 }
14944 };
14945
14946 HooksDispatcherOnMountWithHookTypesInDEV = {
14947 readContext: function (context, observedBits) {
14948 return readContext(context, observedBits);
14949 },
14950 useCallback: function (callback, deps) {
14951 currentHookNameInDev = 'useCallback';
14952 updateHookTypesDev();
14953 return mountCallback(callback, deps);
14954 },
14955 useContext: function (context, observedBits) {
14956 currentHookNameInDev = 'useContext';
14957 updateHookTypesDev();
14958 return readContext(context, observedBits);
14959 },
14960 useEffect: function (create, deps) {
14961 currentHookNameInDev = 'useEffect';
14962 updateHookTypesDev();
14963 return mountEffect(create, deps);
14964 },
14965 useImperativeHandle: function (ref, create, deps) {
14966 currentHookNameInDev = 'useImperativeHandle';
14967 updateHookTypesDev();
14968 return mountImperativeHandle(ref, create, deps);
14969 },
14970 useLayoutEffect: function (create, deps) {
14971 currentHookNameInDev = 'useLayoutEffect';
14972 updateHookTypesDev();
14973 return mountLayoutEffect(create, deps);
14974 },
14975 useMemo: function (create, deps) {
14976 currentHookNameInDev = 'useMemo';
14977 updateHookTypesDev();
14978 var prevDispatcher = ReactCurrentDispatcher$1.current;
14979 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14980 try {
14981 return mountMemo(create, deps);
14982 } finally {
14983 ReactCurrentDispatcher$1.current = prevDispatcher;
14984 }
14985 },
14986 useReducer: function (reducer, initialArg, init) {
14987 currentHookNameInDev = 'useReducer';
14988 updateHookTypesDev();
14989 var prevDispatcher = ReactCurrentDispatcher$1.current;
14990 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
14991 try {
14992 return mountReducer(reducer, initialArg, init);
14993 } finally {
14994 ReactCurrentDispatcher$1.current = prevDispatcher;
14995 }
14996 },
14997 useRef: function (initialValue) {
14998 currentHookNameInDev = 'useRef';
14999 updateHookTypesDev();
15000 return mountRef(initialValue);
15001 },
15002 useState: function (initialState) {
15003 currentHookNameInDev = 'useState';
15004 updateHookTypesDev();
15005 var prevDispatcher = ReactCurrentDispatcher$1.current;
15006 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15007 try {
15008 return mountState(initialState);
15009 } finally {
15010 ReactCurrentDispatcher$1.current = prevDispatcher;
15011 }
15012 },
15013 useDebugValue: function (value, formatterFn) {
15014 currentHookNameInDev = 'useDebugValue';
15015 updateHookTypesDev();
15016 return mountDebugValue(value, formatterFn);
15017 }
15018 };
15019
15020 HooksDispatcherOnUpdateInDEV = {
15021 readContext: function (context, observedBits) {
15022 return readContext(context, observedBits);
15023 },
15024 useCallback: function (callback, deps) {
15025 currentHookNameInDev = 'useCallback';
15026 updateHookTypesDev();
15027 return updateCallback(callback, deps);
15028 },
15029 useContext: function (context, observedBits) {
15030 currentHookNameInDev = 'useContext';
15031 updateHookTypesDev();
15032 return readContext(context, observedBits);
15033 },
15034 useEffect: function (create, deps) {
15035 currentHookNameInDev = 'useEffect';
15036 updateHookTypesDev();
15037 return updateEffect(create, deps);
15038 },
15039 useImperativeHandle: function (ref, create, deps) {
15040 currentHookNameInDev = 'useImperativeHandle';
15041 updateHookTypesDev();
15042 return updateImperativeHandle(ref, create, deps);
15043 },
15044 useLayoutEffect: function (create, deps) {
15045 currentHookNameInDev = 'useLayoutEffect';
15046 updateHookTypesDev();
15047 return updateLayoutEffect(create, deps);
15048 },
15049 useMemo: function (create, deps) {
15050 currentHookNameInDev = 'useMemo';
15051 updateHookTypesDev();
15052 var prevDispatcher = ReactCurrentDispatcher$1.current;
15053 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15054 try {
15055 return updateMemo(create, deps);
15056 } finally {
15057 ReactCurrentDispatcher$1.current = prevDispatcher;
15058 }
15059 },
15060 useReducer: function (reducer, initialArg, init) {
15061 currentHookNameInDev = 'useReducer';
15062 updateHookTypesDev();
15063 var prevDispatcher = ReactCurrentDispatcher$1.current;
15064 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15065 try {
15066 return updateReducer(reducer, initialArg, init);
15067 } finally {
15068 ReactCurrentDispatcher$1.current = prevDispatcher;
15069 }
15070 },
15071 useRef: function (initialValue) {
15072 currentHookNameInDev = 'useRef';
15073 updateHookTypesDev();
15074 return updateRef(initialValue);
15075 },
15076 useState: function (initialState) {
15077 currentHookNameInDev = 'useState';
15078 updateHookTypesDev();
15079 var prevDispatcher = ReactCurrentDispatcher$1.current;
15080 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15081 try {
15082 return updateState(initialState);
15083 } finally {
15084 ReactCurrentDispatcher$1.current = prevDispatcher;
15085 }
15086 },
15087 useDebugValue: function (value, formatterFn) {
15088 currentHookNameInDev = 'useDebugValue';
15089 updateHookTypesDev();
15090 return updateDebugValue(value, formatterFn);
15091 }
15092 };
15093
15094 InvalidNestedHooksDispatcherOnMountInDEV = {
15095 readContext: function (context, observedBits) {
15096 warnInvalidContextAccess();
15097 return readContext(context, observedBits);
15098 },
15099 useCallback: function (callback, deps) {
15100 currentHookNameInDev = 'useCallback';
15101 warnInvalidHookAccess();
15102 mountHookTypesDev();
15103 return mountCallback(callback, deps);
15104 },
15105 useContext: function (context, observedBits) {
15106 currentHookNameInDev = 'useContext';
15107 warnInvalidHookAccess();
15108 mountHookTypesDev();
15109 return readContext(context, observedBits);
15110 },
15111 useEffect: function (create, deps) {
15112 currentHookNameInDev = 'useEffect';
15113 warnInvalidHookAccess();
15114 mountHookTypesDev();
15115 return mountEffect(create, deps);
15116 },
15117 useImperativeHandle: function (ref, create, deps) {
15118 currentHookNameInDev = 'useImperativeHandle';
15119 warnInvalidHookAccess();
15120 mountHookTypesDev();
15121 return mountImperativeHandle(ref, create, deps);
15122 },
15123 useLayoutEffect: function (create, deps) {
15124 currentHookNameInDev = 'useLayoutEffect';
15125 warnInvalidHookAccess();
15126 mountHookTypesDev();
15127 return mountLayoutEffect(create, deps);
15128 },
15129 useMemo: function (create, deps) {
15130 currentHookNameInDev = 'useMemo';
15131 warnInvalidHookAccess();
15132 mountHookTypesDev();
15133 var prevDispatcher = ReactCurrentDispatcher$1.current;
15134 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15135 try {
15136 return mountMemo(create, deps);
15137 } finally {
15138 ReactCurrentDispatcher$1.current = prevDispatcher;
15139 }
15140 },
15141 useReducer: function (reducer, initialArg, init) {
15142 currentHookNameInDev = 'useReducer';
15143 warnInvalidHookAccess();
15144 mountHookTypesDev();
15145 var prevDispatcher = ReactCurrentDispatcher$1.current;
15146 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15147 try {
15148 return mountReducer(reducer, initialArg, init);
15149 } finally {
15150 ReactCurrentDispatcher$1.current = prevDispatcher;
15151 }
15152 },
15153 useRef: function (initialValue) {
15154 currentHookNameInDev = 'useRef';
15155 warnInvalidHookAccess();
15156 mountHookTypesDev();
15157 return mountRef(initialValue);
15158 },
15159 useState: function (initialState) {
15160 currentHookNameInDev = 'useState';
15161 warnInvalidHookAccess();
15162 mountHookTypesDev();
15163 var prevDispatcher = ReactCurrentDispatcher$1.current;
15164 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
15165 try {
15166 return mountState(initialState);
15167 } finally {
15168 ReactCurrentDispatcher$1.current = prevDispatcher;
15169 }
15170 },
15171 useDebugValue: function (value, formatterFn) {
15172 currentHookNameInDev = 'useDebugValue';
15173 warnInvalidHookAccess();
15174 mountHookTypesDev();
15175 return mountDebugValue(value, formatterFn);
15176 }
15177 };
15178
15179 InvalidNestedHooksDispatcherOnUpdateInDEV = {
15180 readContext: function (context, observedBits) {
15181 warnInvalidContextAccess();
15182 return readContext(context, observedBits);
15183 },
15184 useCallback: function (callback, deps) {
15185 currentHookNameInDev = 'useCallback';
15186 warnInvalidHookAccess();
15187 updateHookTypesDev();
15188 return updateCallback(callback, deps);
15189 },
15190 useContext: function (context, observedBits) {
15191 currentHookNameInDev = 'useContext';
15192 warnInvalidHookAccess();
15193 updateHookTypesDev();
15194 return readContext(context, observedBits);
15195 },
15196 useEffect: function (create, deps) {
15197 currentHookNameInDev = 'useEffect';
15198 warnInvalidHookAccess();
15199 updateHookTypesDev();
15200 return updateEffect(create, deps);
15201 },
15202 useImperativeHandle: function (ref, create, deps) {
15203 currentHookNameInDev = 'useImperativeHandle';
15204 warnInvalidHookAccess();
15205 updateHookTypesDev();
15206 return updateImperativeHandle(ref, create, deps);
15207 },
15208 useLayoutEffect: function (create, deps) {
15209 currentHookNameInDev = 'useLayoutEffect';
15210 warnInvalidHookAccess();
15211 updateHookTypesDev();
15212 return updateLayoutEffect(create, deps);
15213 },
15214 useMemo: function (create, deps) {
15215 currentHookNameInDev = 'useMemo';
15216 warnInvalidHookAccess();
15217 updateHookTypesDev();
15218 var prevDispatcher = ReactCurrentDispatcher$1.current;
15219 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15220 try {
15221 return updateMemo(create, deps);
15222 } finally {
15223 ReactCurrentDispatcher$1.current = prevDispatcher;
15224 }
15225 },
15226 useReducer: function (reducer, initialArg, init) {
15227 currentHookNameInDev = 'useReducer';
15228 warnInvalidHookAccess();
15229 updateHookTypesDev();
15230 var prevDispatcher = ReactCurrentDispatcher$1.current;
15231 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15232 try {
15233 return updateReducer(reducer, initialArg, init);
15234 } finally {
15235 ReactCurrentDispatcher$1.current = prevDispatcher;
15236 }
15237 },
15238 useRef: function (initialValue) {
15239 currentHookNameInDev = 'useRef';
15240 warnInvalidHookAccess();
15241 updateHookTypesDev();
15242 return updateRef(initialValue);
15243 },
15244 useState: function (initialState) {
15245 currentHookNameInDev = 'useState';
15246 warnInvalidHookAccess();
15247 updateHookTypesDev();
15248 var prevDispatcher = ReactCurrentDispatcher$1.current;
15249 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
15250 try {
15251 return updateState(initialState);
15252 } finally {
15253 ReactCurrentDispatcher$1.current = prevDispatcher;
15254 }
15255 },
15256 useDebugValue: function (value, formatterFn) {
15257 currentHookNameInDev = 'useDebugValue';
15258 warnInvalidHookAccess();
15259 updateHookTypesDev();
15260 return updateDebugValue(value, formatterFn);
15261 }
15262 };
15263}
15264
15265// Intentionally not named imports because Rollup would use dynamic dispatch for
15266// CommonJS interop named imports.
15267var now$3 = unstable_now;
15268
15269
15270var commitTime = 0;
15271var profilerStartTime = -1;
15272
15273function getCommitTime() {
15274 return commitTime;
15275}
15276
15277function recordCommitTime() {
15278 if (!enableProfilerTimer) {
15279 return;
15280 }
15281 commitTime = now$3();
15282}
15283
15284function startProfilerTimer(fiber) {
15285 if (!enableProfilerTimer) {
15286 return;
15287 }
15288
15289 profilerStartTime = now$3();
15290
15291 if (fiber.actualStartTime < 0) {
15292 fiber.actualStartTime = now$3();
15293 }
15294}
15295
15296function stopProfilerTimerIfRunning(fiber) {
15297 if (!enableProfilerTimer) {
15298 return;
15299 }
15300 profilerStartTime = -1;
15301}
15302
15303function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
15304 if (!enableProfilerTimer) {
15305 return;
15306 }
15307
15308 if (profilerStartTime >= 0) {
15309 var elapsedTime = now$3() - profilerStartTime;
15310 fiber.actualDuration += elapsedTime;
15311 if (overrideBaseTime) {
15312 fiber.selfBaseDuration = elapsedTime;
15313 }
15314 profilerStartTime = -1;
15315 }
15316}
15317
15318// The deepest Fiber on the stack involved in a hydration context.
15319// This may have been an insertion or a hydration.
15320var hydrationParentFiber = null;
15321var nextHydratableInstance = null;
15322var isHydrating = false;
15323
15324function enterHydrationState(fiber) {
15325 if (!supportsHydration) {
15326 return false;
15327 }
15328
15329 var parentInstance = fiber.stateNode.containerInfo;
15330 nextHydratableInstance = getFirstHydratableChild(parentInstance);
15331 hydrationParentFiber = fiber;
15332 isHydrating = true;
15333 return true;
15334}
15335
15336function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
15337 if (!supportsHydration) {
15338 return false;
15339 }
15340
15341 var suspenseInstance = fiber.stateNode;
15342 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
15343 popToNextHostParent(fiber);
15344 isHydrating = true;
15345 return true;
15346}
15347
15348function deleteHydratableInstance(returnFiber, instance) {
15349 {
15350 switch (returnFiber.tag) {
15351 case HostRoot:
15352 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
15353 break;
15354 case HostComponent:
15355 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
15356 break;
15357 }
15358 }
15359
15360 var childToDelete = createFiberFromHostInstanceForDeletion();
15361 childToDelete.stateNode = instance;
15362 childToDelete.return = returnFiber;
15363 childToDelete.effectTag = Deletion;
15364
15365 // This might seem like it belongs on progressedFirstDeletion. However,
15366 // these children are not part of the reconciliation list of children.
15367 // Even if we abort and rereconcile the children, that will try to hydrate
15368 // again and the nodes are still in the host tree so these will be
15369 // recreated.
15370 if (returnFiber.lastEffect !== null) {
15371 returnFiber.lastEffect.nextEffect = childToDelete;
15372 returnFiber.lastEffect = childToDelete;
15373 } else {
15374 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
15375 }
15376}
15377
15378function insertNonHydratedInstance(returnFiber, fiber) {
15379 fiber.effectTag |= Placement;
15380 {
15381 switch (returnFiber.tag) {
15382 case HostRoot:
15383 {
15384 var parentContainer = returnFiber.stateNode.containerInfo;
15385 switch (fiber.tag) {
15386 case HostComponent:
15387 var type = fiber.type;
15388 var props = fiber.pendingProps;
15389 didNotFindHydratableContainerInstance(parentContainer, type, props);
15390 break;
15391 case HostText:
15392 var text = fiber.pendingProps;
15393 didNotFindHydratableContainerTextInstance(parentContainer, text);
15394 break;
15395 case SuspenseComponent:
15396
15397 break;
15398 }
15399 break;
15400 }
15401 case HostComponent:
15402 {
15403 var parentType = returnFiber.type;
15404 var parentProps = returnFiber.memoizedProps;
15405 var parentInstance = returnFiber.stateNode;
15406 switch (fiber.tag) {
15407 case HostComponent:
15408 var _type = fiber.type;
15409 var _props = fiber.pendingProps;
15410 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
15411 break;
15412 case HostText:
15413 var _text = fiber.pendingProps;
15414 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
15415 break;
15416 case SuspenseComponent:
15417 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
15418 break;
15419 }
15420 break;
15421 }
15422 default:
15423 return;
15424 }
15425 }
15426}
15427
15428function tryHydrate(fiber, nextInstance) {
15429 switch (fiber.tag) {
15430 case HostComponent:
15431 {
15432 var type = fiber.type;
15433 var props = fiber.pendingProps;
15434 var instance = canHydrateInstance(nextInstance, type, props);
15435 if (instance !== null) {
15436 fiber.stateNode = instance;
15437 return true;
15438 }
15439 return false;
15440 }
15441 case HostText:
15442 {
15443 var text = fiber.pendingProps;
15444 var textInstance = canHydrateTextInstance(nextInstance, text);
15445 if (textInstance !== null) {
15446 fiber.stateNode = textInstance;
15447 return true;
15448 }
15449 return false;
15450 }
15451 case SuspenseComponent:
15452 {
15453 if (enableSuspenseServerRenderer) {
15454 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
15455 if (suspenseInstance !== null) {
15456 // Downgrade the tag to a dehydrated component until we've hydrated it.
15457 fiber.tag = DehydratedSuspenseComponent;
15458 fiber.stateNode = suspenseInstance;
15459 return true;
15460 }
15461 }
15462 return false;
15463 }
15464 default:
15465 return false;
15466 }
15467}
15468
15469function tryToClaimNextHydratableInstance(fiber) {
15470 if (!isHydrating) {
15471 return;
15472 }
15473 var nextInstance = nextHydratableInstance;
15474 if (!nextInstance) {
15475 // Nothing to hydrate. Make it an insertion.
15476 insertNonHydratedInstance(hydrationParentFiber, fiber);
15477 isHydrating = false;
15478 hydrationParentFiber = fiber;
15479 return;
15480 }
15481 var firstAttemptedInstance = nextInstance;
15482 if (!tryHydrate(fiber, nextInstance)) {
15483 // If we can't hydrate this instance let's try the next one.
15484 // We use this as a heuristic. It's based on intuition and not data so it
15485 // might be flawed or unnecessary.
15486 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
15487 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
15488 // Nothing to hydrate. Make it an insertion.
15489 insertNonHydratedInstance(hydrationParentFiber, fiber);
15490 isHydrating = false;
15491 hydrationParentFiber = fiber;
15492 return;
15493 }
15494 // We matched the next one, we'll now assume that the first one was
15495 // superfluous and we'll delete it. Since we can't eagerly delete it
15496 // we'll have to schedule a deletion. To do that, this node needs a dummy
15497 // fiber associated with it.
15498 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
15499 }
15500 hydrationParentFiber = fiber;
15501 nextHydratableInstance = getFirstHydratableChild(nextInstance);
15502}
15503
15504function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
15505 if (!supportsHydration) {
15506 (function () {
15507 {
15508 {
15509 throw ReactError('Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15510 }
15511 }
15512 })();
15513 }
15514
15515 var instance = fiber.stateNode;
15516 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
15517 // TODO: Type this specific to this type of component.
15518 fiber.updateQueue = updatePayload;
15519 // If the update payload indicates that there is a change or if there
15520 // is a new ref we mark this as an update.
15521 if (updatePayload !== null) {
15522 return true;
15523 }
15524 return false;
15525}
15526
15527function prepareToHydrateHostTextInstance(fiber) {
15528 if (!supportsHydration) {
15529 (function () {
15530 {
15531 {
15532 throw ReactError('Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15533 }
15534 }
15535 })();
15536 }
15537
15538 var textInstance = fiber.stateNode;
15539 var textContent = fiber.memoizedProps;
15540 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
15541 {
15542 if (shouldUpdate) {
15543 // We assume that prepareToHydrateHostTextInstance is called in a context where the
15544 // hydration parent is the parent host component of this host text.
15545 var returnFiber = hydrationParentFiber;
15546 if (returnFiber !== null) {
15547 switch (returnFiber.tag) {
15548 case HostRoot:
15549 {
15550 var parentContainer = returnFiber.stateNode.containerInfo;
15551 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
15552 break;
15553 }
15554 case HostComponent:
15555 {
15556 var parentType = returnFiber.type;
15557 var parentProps = returnFiber.memoizedProps;
15558 var parentInstance = returnFiber.stateNode;
15559 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
15560 break;
15561 }
15562 }
15563 }
15564 }
15565 }
15566 return shouldUpdate;
15567}
15568
15569function skipPastDehydratedSuspenseInstance(fiber) {
15570 if (!supportsHydration) {
15571 (function () {
15572 {
15573 {
15574 throw ReactError('Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
15575 }
15576 }
15577 })();
15578 }
15579 var suspenseInstance = fiber.stateNode;
15580 (function () {
15581 if (!suspenseInstance) {
15582 {
15583 throw ReactError('Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.');
15584 }
15585 }
15586 })();
15587 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
15588}
15589
15590function popToNextHostParent(fiber) {
15591 var parent = fiber.return;
15592 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
15593 parent = parent.return;
15594 }
15595 hydrationParentFiber = parent;
15596}
15597
15598function popHydrationState(fiber) {
15599 if (!supportsHydration) {
15600 return false;
15601 }
15602 if (fiber !== hydrationParentFiber) {
15603 // We're deeper than the current hydration context, inside an inserted
15604 // tree.
15605 return false;
15606 }
15607 if (!isHydrating) {
15608 // If we're not currently hydrating but we're in a hydration context, then
15609 // we were an insertion and now need to pop up reenter hydration of our
15610 // siblings.
15611 popToNextHostParent(fiber);
15612 isHydrating = true;
15613 return false;
15614 }
15615
15616 var type = fiber.type;
15617
15618 // If we have any remaining hydratable nodes, we need to delete them now.
15619 // We only do this deeper than head and body since they tend to have random
15620 // other nodes in them. We also ignore components with pure text content in
15621 // side of them.
15622 // TODO: Better heuristic.
15623 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
15624 var nextInstance = nextHydratableInstance;
15625 while (nextInstance) {
15626 deleteHydratableInstance(fiber, nextInstance);
15627 nextInstance = getNextHydratableSibling(nextInstance);
15628 }
15629 }
15630
15631 popToNextHostParent(fiber);
15632 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
15633 return true;
15634}
15635
15636function resetHydrationState() {
15637 if (!supportsHydration) {
15638 return;
15639 }
15640
15641 hydrationParentFiber = null;
15642 nextHydratableInstance = null;
15643 isHydrating = false;
15644}
15645
15646var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
15647
15648var didReceiveUpdate = false;
15649
15650var didWarnAboutBadClass = void 0;
15651var didWarnAboutModulePatternComponent = void 0;
15652var didWarnAboutContextTypeOnFunctionComponent = void 0;
15653var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
15654var didWarnAboutFunctionRefs = void 0;
15655var didWarnAboutReassigningProps = void 0;
15656var didWarnAboutMaxDuration = void 0;
15657
15658{
15659 didWarnAboutBadClass = {};
15660 didWarnAboutModulePatternComponent = {};
15661 didWarnAboutContextTypeOnFunctionComponent = {};
15662 didWarnAboutGetDerivedStateOnFunctionComponent = {};
15663 didWarnAboutFunctionRefs = {};
15664 didWarnAboutReassigningProps = false;
15665 didWarnAboutMaxDuration = false;
15666}
15667
15668function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
15669 if (current$$1 === null) {
15670 // If this is a fresh new component that hasn't been rendered yet, we
15671 // won't update its child set by applying minimal side-effects. Instead,
15672 // we will add them all to the child before it gets rendered. That means
15673 // we can optimize this reconciliation pass by not tracking side-effects.
15674 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15675 } else {
15676 // If the current child is the same as the work in progress, it means that
15677 // we haven't yet started any work on these children. Therefore, we use
15678 // the clone algorithm to create a copy of all the current children.
15679
15680 // If we had any progressed work already, that is invalid at this point so
15681 // let's throw it out.
15682 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
15683 }
15684}
15685
15686function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
15687 // This function is fork of reconcileChildren. It's used in cases where we
15688 // want to reconcile without matching against the existing set. This has the
15689 // effect of all current children being unmounted; even if the type and key
15690 // are the same, the old child is unmounted and a new child is created.
15691 //
15692 // To do this, we're going to go through the reconcile algorithm twice. In
15693 // the first pass, we schedule a deletion for all the current children by
15694 // passing null.
15695 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
15696 // In the second pass, we mount the new children. The trick here is that we
15697 // pass null in place of where we usually pass the current child set. This has
15698 // the effect of remounting all children regardless of whether their their
15699 // identity matches.
15700 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
15701}
15702
15703function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15704 // TODO: current can be non-null here even if the component
15705 // hasn't yet mounted. This happens after the first render suspends.
15706 // We'll need to figure out if this is fine or can cause issues.
15707
15708 {
15709 if (workInProgress.type !== workInProgress.elementType) {
15710 // Lazy component props can't be validated in createElement
15711 // because they're only guaranteed to be resolved here.
15712 var innerPropTypes = Component.propTypes;
15713 if (innerPropTypes) {
15714 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15715 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15716 }
15717 }
15718 }
15719
15720 var render = Component.render;
15721 var ref = workInProgress.ref;
15722
15723 // The rest is a fork of updateFunctionComponent
15724 var nextChildren = void 0;
15725 prepareToReadContext(workInProgress, renderExpirationTime);
15726 {
15727 ReactCurrentOwner$3.current = workInProgress;
15728 setCurrentPhase('render');
15729 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
15730 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15731 // Only double-render components with Hooks
15732 if (workInProgress.memoizedState !== null) {
15733 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
15734 }
15735 }
15736 setCurrentPhase(null);
15737 }
15738
15739 if (current$$1 !== null && !didReceiveUpdate) {
15740 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
15741 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15742 }
15743
15744 // React DevTools reads this flag.
15745 workInProgress.effectTag |= PerformedWork;
15746 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15747 return workInProgress.child;
15748}
15749
15750function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
15751 if (current$$1 === null) {
15752 var type = Component.type;
15753 if (isSimpleFunctionComponent(type) && Component.compare === null &&
15754 // SimpleMemoComponent codepath doesn't resolve outer props either.
15755 Component.defaultProps === undefined) {
15756 // If this is a plain function component without default props,
15757 // and with only the default shallow comparison, we upgrade it
15758 // to a SimpleMemoComponent to allow fast path updates.
15759 workInProgress.tag = SimpleMemoComponent;
15760 workInProgress.type = type;
15761 {
15762 validateFunctionComponentInDev(workInProgress, type);
15763 }
15764 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
15765 }
15766 {
15767 var innerPropTypes = type.propTypes;
15768 if (innerPropTypes) {
15769 // Inner memo component props aren't currently validated in createElement.
15770 // We could move it there, but we'd still need this for lazy code path.
15771 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15772 'prop', getComponentName(type), getCurrentFiberStackInDev);
15773 }
15774 }
15775 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
15776 child.ref = workInProgress.ref;
15777 child.return = workInProgress;
15778 workInProgress.child = child;
15779 return child;
15780 }
15781 {
15782 var _type = Component.type;
15783 var _innerPropTypes = _type.propTypes;
15784 if (_innerPropTypes) {
15785 // Inner memo component props aren't currently validated in createElement.
15786 // We could move it there, but we'd still need this for lazy code path.
15787 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
15788 'prop', getComponentName(_type), getCurrentFiberStackInDev);
15789 }
15790 }
15791 var currentChild = current$$1.child; // This is always exactly one child
15792 if (updateExpirationTime < renderExpirationTime) {
15793 // This will be the props with resolved defaultProps,
15794 // unlike current.memoizedProps which will be the unresolved ones.
15795 var prevProps = currentChild.memoizedProps;
15796 // Default to shallow comparison
15797 var compare = Component.compare;
15798 compare = compare !== null ? compare : shallowEqual;
15799 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
15800 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15801 }
15802 }
15803 // React DevTools reads this flag.
15804 workInProgress.effectTag |= PerformedWork;
15805 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
15806 newChild.ref = workInProgress.ref;
15807 newChild.return = workInProgress;
15808 workInProgress.child = newChild;
15809 return newChild;
15810}
15811
15812function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
15813 // TODO: current can be non-null here even if the component
15814 // hasn't yet mounted. This happens when the inner render suspends.
15815 // We'll need to figure out if this is fine or can cause issues.
15816
15817 {
15818 if (workInProgress.type !== workInProgress.elementType) {
15819 // Lazy component props can't be validated in createElement
15820 // because they're only guaranteed to be resolved here.
15821 var outerMemoType = workInProgress.elementType;
15822 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
15823 // We warn when you define propTypes on lazy()
15824 // so let's just skip over it to find memo() outer wrapper.
15825 // Inner props for memo are validated later.
15826 outerMemoType = refineResolvedLazyComponent(outerMemoType);
15827 }
15828 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
15829 if (outerPropTypes) {
15830 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
15831 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
15832 }
15833 // Inner propTypes will be validated in the function component path.
15834 }
15835 }
15836 if (current$$1 !== null) {
15837 var prevProps = current$$1.memoizedProps;
15838 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
15839 didReceiveUpdate = false;
15840 if (updateExpirationTime < renderExpirationTime) {
15841 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15842 }
15843 }
15844 }
15845 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
15846}
15847
15848function updateFragment(current$$1, workInProgress, renderExpirationTime) {
15849 var nextChildren = workInProgress.pendingProps;
15850 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15851 return workInProgress.child;
15852}
15853
15854function updateMode(current$$1, workInProgress, renderExpirationTime) {
15855 var nextChildren = workInProgress.pendingProps.children;
15856 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15857 return workInProgress.child;
15858}
15859
15860function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
15861 if (enableProfilerTimer) {
15862 workInProgress.effectTag |= Update;
15863 }
15864 var nextProps = workInProgress.pendingProps;
15865 var nextChildren = nextProps.children;
15866 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15867 return workInProgress.child;
15868}
15869
15870function markRef(current$$1, workInProgress) {
15871 var ref = workInProgress.ref;
15872 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
15873 // Schedule a Ref effect
15874 workInProgress.effectTag |= Ref;
15875 }
15876}
15877
15878function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15879 {
15880 if (workInProgress.type !== workInProgress.elementType) {
15881 // Lazy component props can't be validated in createElement
15882 // because they're only guaranteed to be resolved here.
15883 var innerPropTypes = Component.propTypes;
15884 if (innerPropTypes) {
15885 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15886 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15887 }
15888 }
15889 }
15890
15891 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
15892 var context = getMaskedContext(workInProgress, unmaskedContext);
15893
15894 var nextChildren = void 0;
15895 prepareToReadContext(workInProgress, renderExpirationTime);
15896 {
15897 ReactCurrentOwner$3.current = workInProgress;
15898 setCurrentPhase('render');
15899 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
15900 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
15901 // Only double-render components with Hooks
15902 if (workInProgress.memoizedState !== null) {
15903 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
15904 }
15905 }
15906 setCurrentPhase(null);
15907 }
15908
15909 if (current$$1 !== null && !didReceiveUpdate) {
15910 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
15911 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15912 }
15913
15914 // React DevTools reads this flag.
15915 workInProgress.effectTag |= PerformedWork;
15916 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
15917 return workInProgress.child;
15918}
15919
15920function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
15921 {
15922 if (workInProgress.type !== workInProgress.elementType) {
15923 // Lazy component props can't be validated in createElement
15924 // because they're only guaranteed to be resolved here.
15925 var innerPropTypes = Component.propTypes;
15926 if (innerPropTypes) {
15927 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
15928 'prop', getComponentName(Component), getCurrentFiberStackInDev);
15929 }
15930 }
15931 }
15932
15933 // Push context providers early to prevent context stack mismatches.
15934 // During mounting we don't know the child context yet as the instance doesn't exist.
15935 // We will invalidate the child context in finishClassComponent() right after rendering.
15936 var hasContext = void 0;
15937 if (isContextProvider(Component)) {
15938 hasContext = true;
15939 pushContextProvider(workInProgress);
15940 } else {
15941 hasContext = false;
15942 }
15943 prepareToReadContext(workInProgress, renderExpirationTime);
15944
15945 var instance = workInProgress.stateNode;
15946 var shouldUpdate = void 0;
15947 if (instance === null) {
15948 if (current$$1 !== null) {
15949 // An class component without an instance only mounts if it suspended
15950 // inside a non- concurrent tree, in an inconsistent state. We want to
15951 // tree it like a new mount, even though an empty version of it already
15952 // committed. Disconnect the alternate pointers.
15953 current$$1.alternate = null;
15954 workInProgress.alternate = null;
15955 // Since this is conceptually a new fiber, schedule a Placement effect
15956 workInProgress.effectTag |= Placement;
15957 }
15958 // In the initial pass we might need to construct the instance.
15959 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15960 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15961 shouldUpdate = true;
15962 } else if (current$$1 === null) {
15963 // In a resume, we'll already have an instance we can reuse.
15964 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
15965 } else {
15966 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
15967 }
15968 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
15969 {
15970 var inst = workInProgress.stateNode;
15971 if (inst.props !== nextProps) {
15972 !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;
15973 didWarnAboutReassigningProps = true;
15974 }
15975 }
15976 return nextUnitOfWork;
15977}
15978
15979function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
15980 // Refs should update even if shouldComponentUpdate returns false
15981 markRef(current$$1, workInProgress);
15982
15983 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
15984
15985 if (!shouldUpdate && !didCaptureError) {
15986 // Context providers should defer to sCU for rendering
15987 if (hasContext) {
15988 invalidateContextProvider(workInProgress, Component, false);
15989 }
15990
15991 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
15992 }
15993
15994 var instance = workInProgress.stateNode;
15995
15996 // Rerender
15997 ReactCurrentOwner$3.current = workInProgress;
15998 var nextChildren = void 0;
15999 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
16000 // If we captured an error, but getDerivedStateFrom catch is not defined,
16001 // unmount all the children. componentDidCatch will schedule an update to
16002 // re-render a fallback. This is temporary until we migrate everyone to
16003 // the new API.
16004 // TODO: Warn in a future release.
16005 nextChildren = null;
16006
16007 if (enableProfilerTimer) {
16008 stopProfilerTimerIfRunning(workInProgress);
16009 }
16010 } else {
16011 {
16012 setCurrentPhase('render');
16013 nextChildren = instance.render();
16014 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16015 instance.render();
16016 }
16017 setCurrentPhase(null);
16018 }
16019 }
16020
16021 // React DevTools reads this flag.
16022 workInProgress.effectTag |= PerformedWork;
16023 if (current$$1 !== null && didCaptureError) {
16024 // If we're recovering from an error, reconcile without reusing any of
16025 // the existing children. Conceptually, the normal children and the children
16026 // that are shown on error are two different sets, so we shouldn't reuse
16027 // normal children even if their identities match.
16028 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
16029 } else {
16030 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16031 }
16032
16033 // Memoize state using the values we just used to render.
16034 // TODO: Restructure so we never read values from the instance.
16035 workInProgress.memoizedState = instance.state;
16036
16037 // The context might have changed so we need to recalculate it.
16038 if (hasContext) {
16039 invalidateContextProvider(workInProgress, Component, true);
16040 }
16041
16042 return workInProgress.child;
16043}
16044
16045function pushHostRootContext(workInProgress) {
16046 var root = workInProgress.stateNode;
16047 if (root.pendingContext) {
16048 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
16049 } else if (root.context) {
16050 // Should always be set
16051 pushTopLevelContextObject(workInProgress, root.context, false);
16052 }
16053 pushHostContainer(workInProgress, root.containerInfo);
16054}
16055
16056function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
16057 pushHostRootContext(workInProgress);
16058 var updateQueue = workInProgress.updateQueue;
16059 (function () {
16060 if (!(updateQueue !== null)) {
16061 {
16062 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.');
16063 }
16064 }
16065 })();
16066 var nextProps = workInProgress.pendingProps;
16067 var prevState = workInProgress.memoizedState;
16068 var prevChildren = prevState !== null ? prevState.element : null;
16069 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
16070 var nextState = workInProgress.memoizedState;
16071 // Caution: React DevTools currently depends on this property
16072 // being called "element".
16073 var nextChildren = nextState.element;
16074 if (nextChildren === prevChildren) {
16075 // If the state is the same as before, that's a bailout because we had
16076 // no work that expires at this time.
16077 resetHydrationState();
16078 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16079 }
16080 var root = workInProgress.stateNode;
16081 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
16082 // If we don't have any current children this might be the first pass.
16083 // We always try to hydrate. If this isn't a hydration pass there won't
16084 // be any children to hydrate which is effectively the same thing as
16085 // not hydrating.
16086
16087 // This is a bit of a hack. We track the host root as a placement to
16088 // know that we're currently in a mounting state. That way isMounted
16089 // works as expected. We must reset this before committing.
16090 // TODO: Delete this when we delete isMounted and findDOMNode.
16091 workInProgress.effectTag |= Placement;
16092
16093 // Ensure that children mount into this root without tracking
16094 // side-effects. This ensures that we don't store Placement effects on
16095 // nodes that will be hydrated.
16096 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16097 } else {
16098 // Otherwise reset hydration state in case we aborted and resumed another
16099 // root.
16100 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16101 resetHydrationState();
16102 }
16103 return workInProgress.child;
16104}
16105
16106function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
16107 pushHostContext(workInProgress);
16108
16109 if (current$$1 === null) {
16110 tryToClaimNextHydratableInstance(workInProgress);
16111 }
16112
16113 var type = workInProgress.type;
16114 var nextProps = workInProgress.pendingProps;
16115 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
16116
16117 var nextChildren = nextProps.children;
16118 var isDirectTextChild = shouldSetTextContent(type, nextProps);
16119
16120 if (isDirectTextChild) {
16121 // We special case a direct text child of a host node. This is a common
16122 // case. We won't handle it as a reified child. We will instead handle
16123 // this in the host environment that also have access to this prop. That
16124 // avoids allocating another HostText fiber and traversing it.
16125 nextChildren = null;
16126 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
16127 // If we're switching from a direct text child to a normal child, or to
16128 // empty, we need to schedule the text content to be reset.
16129 workInProgress.effectTag |= ContentReset;
16130 }
16131
16132 markRef(current$$1, workInProgress);
16133
16134 // Check the host config to see if the children are offscreen/hidden.
16135 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
16136 // Schedule this fiber to re-render at offscreen priority. Then bailout.
16137 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
16138 return null;
16139 }
16140
16141 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16142 return workInProgress.child;
16143}
16144
16145function updateHostText(current$$1, workInProgress) {
16146 if (current$$1 === null) {
16147 tryToClaimNextHydratableInstance(workInProgress);
16148 }
16149 // Nothing to do here. This is terminal. We'll do the completion step
16150 // immediately after.
16151 return null;
16152}
16153
16154function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
16155 if (_current !== null) {
16156 // An lazy component only mounts if it suspended inside a non-
16157 // concurrent tree, in an inconsistent state. We want to treat it like
16158 // a new mount, even though an empty version of it already committed.
16159 // Disconnect the alternate pointers.
16160 _current.alternate = null;
16161 workInProgress.alternate = null;
16162 // Since this is conceptually a new fiber, schedule a Placement effect
16163 workInProgress.effectTag |= Placement;
16164 }
16165
16166 var props = workInProgress.pendingProps;
16167 // We can't start a User Timing measurement with correct label yet.
16168 // Cancel and resume right after we know the tag.
16169 cancelWorkTimer(workInProgress);
16170 var Component = readLazyComponentType(elementType);
16171 // Store the unwrapped component in the type.
16172 workInProgress.type = Component;
16173 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
16174 startWorkTimer(workInProgress);
16175 var resolvedProps = resolveDefaultProps(Component, props);
16176 var child = void 0;
16177 switch (resolvedTag) {
16178 case FunctionComponent:
16179 {
16180 {
16181 validateFunctionComponentInDev(workInProgress, Component);
16182 }
16183 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16184 break;
16185 }
16186 case ClassComponent:
16187 {
16188 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16189 break;
16190 }
16191 case ForwardRef:
16192 {
16193 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
16194 break;
16195 }
16196 case MemoComponent:
16197 {
16198 {
16199 if (workInProgress.type !== workInProgress.elementType) {
16200 var outerPropTypes = Component.propTypes;
16201 if (outerPropTypes) {
16202 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
16203 'prop', getComponentName(Component), getCurrentFiberStackInDev);
16204 }
16205 }
16206 }
16207 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
16208 updateExpirationTime, renderExpirationTime);
16209 break;
16210 }
16211 default:
16212 {
16213 var hint = '';
16214 {
16215 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
16216 hint = ' Did you wrap a component in React.lazy() more than once?';
16217 }
16218 }
16219 // This message intentionally doesn't mention ForwardRef or MemoComponent
16220 // because the fact that it's a separate type of work is an
16221 // implementation detail.
16222 (function () {
16223 {
16224 {
16225 throw ReactError('Element type is invalid. Received a promise that resolves to: ' + Component + '. Lazy element type must resolve to a class or function.' + hint);
16226 }
16227 }
16228 })();
16229 }
16230 }
16231 return child;
16232}
16233
16234function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
16235 if (_current !== null) {
16236 // An incomplete component only mounts if it suspended inside a non-
16237 // concurrent tree, in an inconsistent state. We want to treat it like
16238 // a new mount, even though an empty version of it already committed.
16239 // Disconnect the alternate pointers.
16240 _current.alternate = null;
16241 workInProgress.alternate = null;
16242 // Since this is conceptually a new fiber, schedule a Placement effect
16243 workInProgress.effectTag |= Placement;
16244 }
16245
16246 // Promote the fiber to a class and try rendering again.
16247 workInProgress.tag = ClassComponent;
16248
16249 // The rest of this function is a fork of `updateClassComponent`
16250
16251 // Push context providers early to prevent context stack mismatches.
16252 // During mounting we don't know the child context yet as the instance doesn't exist.
16253 // We will invalidate the child context in finishClassComponent() right after rendering.
16254 var hasContext = void 0;
16255 if (isContextProvider(Component)) {
16256 hasContext = true;
16257 pushContextProvider(workInProgress);
16258 } else {
16259 hasContext = false;
16260 }
16261 prepareToReadContext(workInProgress, renderExpirationTime);
16262
16263 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
16264 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
16265
16266 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
16267}
16268
16269function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
16270 if (_current !== null) {
16271 // An indeterminate component only mounts if it suspended inside a non-
16272 // concurrent tree, in an inconsistent state. We want to treat it like
16273 // a new mount, even though an empty version of it already committed.
16274 // Disconnect the alternate pointers.
16275 _current.alternate = null;
16276 workInProgress.alternate = null;
16277 // Since this is conceptually a new fiber, schedule a Placement effect
16278 workInProgress.effectTag |= Placement;
16279 }
16280
16281 var props = workInProgress.pendingProps;
16282 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
16283 var context = getMaskedContext(workInProgress, unmaskedContext);
16284
16285 prepareToReadContext(workInProgress, renderExpirationTime);
16286
16287 var value = void 0;
16288
16289 {
16290 if (Component.prototype && typeof Component.prototype.render === 'function') {
16291 var componentName = getComponentName(Component) || 'Unknown';
16292
16293 if (!didWarnAboutBadClass[componentName]) {
16294 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);
16295 didWarnAboutBadClass[componentName] = true;
16296 }
16297 }
16298
16299 if (workInProgress.mode & StrictMode) {
16300 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
16301 }
16302
16303 ReactCurrentOwner$3.current = workInProgress;
16304 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
16305 }
16306 // React DevTools reads this flag.
16307 workInProgress.effectTag |= PerformedWork;
16308
16309 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
16310 {
16311 var _componentName = getComponentName(Component) || 'Unknown';
16312 if (!didWarnAboutModulePatternComponent[_componentName]) {
16313 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);
16314 didWarnAboutModulePatternComponent[_componentName] = true;
16315 }
16316 }
16317
16318 // Proceed under the assumption that this is a class instance
16319 workInProgress.tag = ClassComponent;
16320
16321 // Throw out any hooks that were used.
16322 resetHooks();
16323
16324 // Push context providers early to prevent context stack mismatches.
16325 // During mounting we don't know the child context yet as the instance doesn't exist.
16326 // We will invalidate the child context in finishClassComponent() right after rendering.
16327 var hasContext = false;
16328 if (isContextProvider(Component)) {
16329 hasContext = true;
16330 pushContextProvider(workInProgress);
16331 } else {
16332 hasContext = false;
16333 }
16334
16335 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
16336
16337 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
16338 if (typeof getDerivedStateFromProps === 'function') {
16339 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
16340 }
16341
16342 adoptClassInstance(workInProgress, value);
16343 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
16344 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
16345 } else {
16346 // Proceed under the assumption that this is a function component
16347 workInProgress.tag = FunctionComponent;
16348 {
16349 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
16350 // Only double-render components with Hooks
16351 if (workInProgress.memoizedState !== null) {
16352 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
16353 }
16354 }
16355 }
16356 reconcileChildren(null, workInProgress, value, renderExpirationTime);
16357 {
16358 validateFunctionComponentInDev(workInProgress, Component);
16359 }
16360 return workInProgress.child;
16361 }
16362}
16363
16364function validateFunctionComponentInDev(workInProgress, Component) {
16365 if (Component) {
16366 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
16367 }
16368 if (workInProgress.ref !== null) {
16369 var info = '';
16370 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
16371 if (ownerName) {
16372 info += '\n\nCheck the render method of `' + ownerName + '`.';
16373 }
16374
16375 var warningKey = ownerName || workInProgress._debugID || '';
16376 var debugSource = workInProgress._debugSource;
16377 if (debugSource) {
16378 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
16379 }
16380 if (!didWarnAboutFunctionRefs[warningKey]) {
16381 didWarnAboutFunctionRefs[warningKey] = true;
16382 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);
16383 }
16384 }
16385
16386 if (typeof Component.getDerivedStateFromProps === 'function') {
16387 var componentName = getComponentName(Component) || 'Unknown';
16388
16389 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
16390 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
16391 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
16392 }
16393 }
16394
16395 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
16396 var _componentName2 = getComponentName(Component) || 'Unknown';
16397
16398 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) {
16399 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName2);
16400 didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true;
16401 }
16402 }
16403}
16404
16405function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
16406 var mode = workInProgress.mode;
16407 var nextProps = workInProgress.pendingProps;
16408
16409 // We should attempt to render the primary children unless this boundary
16410 // already suspended during this render (`alreadyCaptured` is true).
16411 var nextState = workInProgress.memoizedState;
16412
16413 var nextDidTimeout = void 0;
16414 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
16415 // This is the first attempt.
16416 nextState = null;
16417 nextDidTimeout = false;
16418 } else {
16419 // Something in this boundary's subtree already suspended. Switch to
16420 // rendering the fallback children.
16421 nextState = {
16422 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
16423 };
16424 nextDidTimeout = true;
16425 workInProgress.effectTag &= ~DidCapture;
16426 }
16427
16428 {
16429 if ('maxDuration' in nextProps) {
16430 if (!didWarnAboutMaxDuration) {
16431 didWarnAboutMaxDuration = true;
16432 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
16433 }
16434 }
16435 }
16436
16437 // This next part is a bit confusing. If the children timeout, we switch to
16438 // showing the fallback children in place of the "primary" children.
16439 // However, we don't want to delete the primary children because then their
16440 // state will be lost (both the React state and the host state, e.g.
16441 // uncontrolled form inputs). Instead we keep them mounted and hide them.
16442 // Both the fallback children AND the primary children are rendered at the
16443 // same time. Once the primary children are un-suspended, we can delete
16444 // the fallback children — don't need to preserve their state.
16445 //
16446 // The two sets of children are siblings in the host environment, but
16447 // semantically, for purposes of reconciliation, they are two separate sets.
16448 // So we store them using two fragment fibers.
16449 //
16450 // However, we want to avoid allocating extra fibers for every placeholder.
16451 // They're only necessary when the children time out, because that's the
16452 // only time when both sets are mounted.
16453 //
16454 // So, the extra fragment fibers are only used if the children time out.
16455 // Otherwise, we render the primary children directly. This requires some
16456 // custom reconciliation logic to preserve the state of the primary
16457 // children. It's essentially a very basic form of re-parenting.
16458
16459 // `child` points to the child fiber. In the normal case, this is the first
16460 // fiber of the primary children set. In the timed-out case, it's a
16461 // a fragment fiber containing the primary children.
16462 var child = void 0;
16463 // `next` points to the next fiber React should render. In the normal case,
16464 // it's the same as `child`: the first fiber of the primary children set.
16465 // In the timed-out case, it's a fragment fiber containing the *fallback*
16466 // children -- we skip over the primary children entirely.
16467 var next = void 0;
16468 if (current$$1 === null) {
16469 if (enableSuspenseServerRenderer) {
16470 // If we're currently hydrating, try to hydrate this boundary.
16471 // But only if this has a fallback.
16472 if (nextProps.fallback !== undefined) {
16473 tryToClaimNextHydratableInstance(workInProgress);
16474 // This could've changed the tag if this was a dehydrated suspense component.
16475 if (workInProgress.tag === DehydratedSuspenseComponent) {
16476 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
16477 }
16478 }
16479 }
16480
16481 // This is the initial mount. This branch is pretty simple because there's
16482 // no previous state that needs to be preserved.
16483 if (nextDidTimeout) {
16484 // Mount separate fragments for primary and fallback children.
16485 var nextFallbackChildren = nextProps.fallback;
16486 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
16487
16488 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16489 // Outside of concurrent mode, we commit the effects from the
16490 var progressedState = workInProgress.memoizedState;
16491 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
16492 primaryChildFragment.child = progressedPrimaryChild;
16493 }
16494
16495 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
16496 primaryChildFragment.sibling = fallbackChildFragment;
16497 child = primaryChildFragment;
16498 // Skip the primary children, and continue working on the
16499 // fallback children.
16500 next = fallbackChildFragment;
16501 child.return = next.return = workInProgress;
16502 } else {
16503 // Mount the primary children without an intermediate fragment fiber.
16504 var nextPrimaryChildren = nextProps.children;
16505 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
16506 }
16507 } else {
16508 // This is an update. This branch is more complicated because we need to
16509 // ensure the state of the primary children is preserved.
16510 var prevState = current$$1.memoizedState;
16511 var prevDidTimeout = prevState !== null;
16512 if (prevDidTimeout) {
16513 // The current tree already timed out. That means each child set is
16514 var currentPrimaryChildFragment = current$$1.child;
16515 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
16516 if (nextDidTimeout) {
16517 // Still timed out. Reuse the current primary children by cloning
16518 // its fragment. We're going to skip over these entirely.
16519 var _nextFallbackChildren = nextProps.fallback;
16520 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
16521
16522 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16523 // Outside of concurrent mode, we commit the effects from the
16524 var _progressedState = workInProgress.memoizedState;
16525 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
16526 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
16527 _primaryChildFragment.child = _progressedPrimaryChild;
16528 }
16529 }
16530
16531 // Because primaryChildFragment is a new fiber that we're inserting as the
16532 // parent of a new tree, we need to set its treeBaseDuration.
16533 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
16534 // treeBaseDuration is the sum of all the child tree base durations.
16535 var treeBaseDuration = 0;
16536 var hiddenChild = _primaryChildFragment.child;
16537 while (hiddenChild !== null) {
16538 treeBaseDuration += hiddenChild.treeBaseDuration;
16539 hiddenChild = hiddenChild.sibling;
16540 }
16541 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
16542 }
16543
16544 // Clone the fallback child fragment, too. These we'll continue
16545 // working on.
16546 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
16547 child = _primaryChildFragment;
16548 _primaryChildFragment.childExpirationTime = NoWork;
16549 // Skip the primary children, and continue working on the
16550 // fallback children.
16551 next = _fallbackChildFragment;
16552 child.return = next.return = workInProgress;
16553 } else {
16554 // No longer suspended. Switch back to showing the primary children,
16555 // and remove the intermediate fragment fiber.
16556 var _nextPrimaryChildren = nextProps.children;
16557 var currentPrimaryChild = currentPrimaryChildFragment.child;
16558 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
16559
16560 // If this render doesn't suspend, we need to delete the fallback
16561 // children. Wait until the complete phase, after we've confirmed the
16562 // fallback is no longer needed.
16563 // TODO: Would it be better to store the fallback fragment on
16564 // the stateNode?
16565
16566 // Continue rendering the children, like we normally do.
16567 child = next = primaryChild;
16568 }
16569 } else {
16570 // The current tree has not already timed out. That means the primary
16571 // children are not wrapped in a fragment fiber.
16572 var _currentPrimaryChild = current$$1.child;
16573 if (nextDidTimeout) {
16574 // Timed out. Wrap the children in a fragment fiber to keep them
16575 // separate from the fallback children.
16576 var _nextFallbackChildren2 = nextProps.fallback;
16577 var _primaryChildFragment2 = createFiberFromFragment(
16578 // It shouldn't matter what the pending props are because we aren't
16579 // going to render this fragment.
16580 null, mode, NoWork, null);
16581 _primaryChildFragment2.child = _currentPrimaryChild;
16582
16583 // Even though we're creating a new fiber, there are no new children,
16584 // because we're reusing an already mounted tree. So we don't need to
16585 // schedule a placement.
16586 // primaryChildFragment.effectTag |= Placement;
16587
16588 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
16589 // Outside of concurrent mode, we commit the effects from the
16590 var _progressedState2 = workInProgress.memoizedState;
16591 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
16592 _primaryChildFragment2.child = _progressedPrimaryChild2;
16593 }
16594
16595 // Because primaryChildFragment is a new fiber that we're inserting as the
16596 // parent of a new tree, we need to set its treeBaseDuration.
16597 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
16598 // treeBaseDuration is the sum of all the child tree base durations.
16599 var _treeBaseDuration = 0;
16600 var _hiddenChild = _primaryChildFragment2.child;
16601 while (_hiddenChild !== null) {
16602 _treeBaseDuration += _hiddenChild.treeBaseDuration;
16603 _hiddenChild = _hiddenChild.sibling;
16604 }
16605 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
16606 }
16607
16608 // Create a fragment from the fallback children, too.
16609 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
16610 _fallbackChildFragment2.effectTag |= Placement;
16611 child = _primaryChildFragment2;
16612 _primaryChildFragment2.childExpirationTime = NoWork;
16613 // Skip the primary children, and continue working on the
16614 // fallback children.
16615 next = _fallbackChildFragment2;
16616 child.return = next.return = workInProgress;
16617 } else {
16618 // Still haven't timed out. Continue rendering the children, like we
16619 // normally do.
16620 var _nextPrimaryChildren2 = nextProps.children;
16621 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
16622 }
16623 }
16624 workInProgress.stateNode = current$$1.stateNode;
16625 }
16626
16627 workInProgress.memoizedState = nextState;
16628 workInProgress.child = child;
16629 return next;
16630}
16631
16632function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
16633 // Detach from the current dehydrated boundary.
16634 current$$1.alternate = null;
16635 workInProgress.alternate = null;
16636
16637 // Insert a deletion in the effect list.
16638 var returnFiber = workInProgress.return;
16639 (function () {
16640 if (!(returnFiber !== null)) {
16641 {
16642 throw ReactError('Suspense boundaries are never on the root. This is probably a bug in React.');
16643 }
16644 }
16645 })();
16646 var last = returnFiber.lastEffect;
16647 if (last !== null) {
16648 last.nextEffect = current$$1;
16649 returnFiber.lastEffect = current$$1;
16650 } else {
16651 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
16652 }
16653 current$$1.nextEffect = null;
16654 current$$1.effectTag = Deletion;
16655
16656 // Upgrade this work in progress to a real Suspense component.
16657 workInProgress.tag = SuspenseComponent;
16658 workInProgress.stateNode = null;
16659 workInProgress.memoizedState = null;
16660 // This is now an insertion.
16661 workInProgress.effectTag |= Placement;
16662 // Retry as a real Suspense component.
16663 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
16664}
16665
16666function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
16667 var suspenseInstance = workInProgress.stateNode;
16668 if (current$$1 === null) {
16669 // During the first pass, we'll bail out and not drill into the children.
16670 // Instead, we'll leave the content in place and try to hydrate it later.
16671 if (isSuspenseInstanceFallback(suspenseInstance)) {
16672 // This is a client-only boundary. Since we won't get any content from the server
16673 // for this, we need to schedule that at a higher priority based on when it would
16674 // have timed out. In theory we could render it in this pass but it would have the
16675 // wrong priority associated with it and will prevent hydration of parent path.
16676 // Instead, we'll leave work left on it to render it in a separate commit.
16677
16678 // TODO This time should be the time at which the server rendered response that is
16679 // a parent to this boundary was displayed. However, since we currently don't have
16680 // a protocol to transfer that time, we'll just estimate it by using the current
16681 // time. This will mean that Suspense timeouts are slightly shifted to later than
16682 // they should be.
16683 var serverDisplayTime = requestCurrentTime$$1();
16684 // Schedule a normal pri update to render this content.
16685 workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime);
16686 } else {
16687 // We'll continue hydrating the rest at offscreen priority since we'll already
16688 // be showing the right content coming from the server, it is no rush.
16689 workInProgress.expirationTime = Never;
16690 }
16691 return null;
16692 }
16693 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
16694 // Something suspended. Leave the existing children in place.
16695 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
16696 workInProgress.child = null;
16697 return null;
16698 }
16699 if (isSuspenseInstanceFallback(suspenseInstance)) {
16700 // This boundary is in a permanent fallback state. In this case, we'll never
16701 // get an update and we'll never be able to hydrate the final content. Let's just try the
16702 // client side render instead.
16703 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
16704 }
16705 // We use childExpirationTime to indicate that a child might depend on context, so if
16706 // any context has changed, we need to treat is as if the input might have changed.
16707 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
16708 if (didReceiveUpdate || hasContextChanged$$1) {
16709 // This boundary has changed since the first render. This means that we are now unable to
16710 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
16711 // during this render we can't. Instead, we're going to delete the whole subtree and
16712 // instead inject a new real Suspense boundary to take its place, which may render content
16713 // or fallback. The real Suspense boundary will suspend for a while so we have some time
16714 // to ensure it can produce real content, but all state and pending events will be lost.
16715 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
16716 } else if (isSuspenseInstancePending(suspenseInstance)) {
16717 // This component is still pending more data from the server, so we can't hydrate its
16718 // content. We treat it as if this component suspended itself. It might seem as if
16719 // we could just try to render it client-side instead. However, this will perform a
16720 // lot of unnecessary work and is unlikely to complete since it often will suspend
16721 // on missing data anyway. Additionally, the server might be able to render more
16722 // than we can on the client yet. In that case we'd end up with more fallback states
16723 // on the client than if we just leave it alone. If the server times out or errors
16724 // these should update this boundary to the permanent Fallback state instead.
16725 // Mark it as having captured (i.e. suspended).
16726 workInProgress.effectTag |= DidCapture;
16727 // Leave the children in place. I.e. empty.
16728 workInProgress.child = null;
16729 // Register a callback to retry this boundary once the server has sent the result.
16730 registerSuspenseInstanceRetry(suspenseInstance, retryTimedOutBoundary$$1.bind(null, current$$1));
16731 return null;
16732 } else {
16733 // This is the first attempt.
16734 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
16735 var nextProps = workInProgress.pendingProps;
16736 var nextChildren = nextProps.children;
16737 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16738 return workInProgress.child;
16739 }
16740}
16741
16742function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
16743 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
16744 var nextChildren = workInProgress.pendingProps;
16745 if (current$$1 === null) {
16746 // Portals are special because we don't append the children during mount
16747 // but at commit. Therefore we need to track insertions which the normal
16748 // flow doesn't do during mount. This doesn't happen at the root because
16749 // the root always starts with a "current" with a null child.
16750 // TODO: Consider unifying this with how the root works.
16751 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
16752 } else {
16753 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16754 }
16755 return workInProgress.child;
16756}
16757
16758function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
16759 var providerType = workInProgress.type;
16760 var context = providerType._context;
16761
16762 var newProps = workInProgress.pendingProps;
16763 var oldProps = workInProgress.memoizedProps;
16764
16765 var newValue = newProps.value;
16766
16767 {
16768 var providerPropTypes = workInProgress.type.propTypes;
16769
16770 if (providerPropTypes) {
16771 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
16772 }
16773 }
16774
16775 pushProvider(workInProgress, newValue);
16776
16777 if (oldProps !== null) {
16778 var oldValue = oldProps.value;
16779 var changedBits = calculateChangedBits(context, newValue, oldValue);
16780 if (changedBits === 0) {
16781 // No change. Bailout early if children are the same.
16782 if (oldProps.children === newProps.children && !hasContextChanged()) {
16783 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16784 }
16785 } else {
16786 // The context value changed. Search for matching consumers and schedule
16787 // them to update.
16788 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
16789 }
16790 }
16791
16792 var newChildren = newProps.children;
16793 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
16794 return workInProgress.child;
16795}
16796
16797var hasWarnedAboutUsingContextAsConsumer = false;
16798
16799function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
16800 var context = workInProgress.type;
16801 // The logic below for Context differs depending on PROD or DEV mode. In
16802 // DEV mode, we create a separate object for Context.Consumer that acts
16803 // like a proxy to Context. This proxy object adds unnecessary code in PROD
16804 // so we use the old behaviour (Context.Consumer references Context) to
16805 // reduce size and overhead. The separate object references context via
16806 // a property called "_context", which also gives us the ability to check
16807 // in DEV mode if this property exists or not and warn if it does not.
16808 {
16809 if (context._context === undefined) {
16810 // This may be because it's a Context (rather than a Consumer).
16811 // Or it may be because it's older React where they're the same thing.
16812 // We only want to warn if we're sure it's a new React.
16813 if (context !== context.Consumer) {
16814 if (!hasWarnedAboutUsingContextAsConsumer) {
16815 hasWarnedAboutUsingContextAsConsumer = true;
16816 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?');
16817 }
16818 }
16819 } else {
16820 context = context._context;
16821 }
16822 }
16823 var newProps = workInProgress.pendingProps;
16824 var render = newProps.children;
16825
16826 {
16827 !(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;
16828 }
16829
16830 prepareToReadContext(workInProgress, renderExpirationTime);
16831 var newValue = readContext(context, newProps.unstable_observedBits);
16832 var newChildren = void 0;
16833 {
16834 ReactCurrentOwner$3.current = workInProgress;
16835 setCurrentPhase('render');
16836 newChildren = render(newValue);
16837 setCurrentPhase(null);
16838 }
16839
16840 // React DevTools reads this flag.
16841 workInProgress.effectTag |= PerformedWork;
16842 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
16843 return workInProgress.child;
16844}
16845
16846function updateEventComponent(current$$1, workInProgress, renderExpirationTime) {
16847 var nextProps = workInProgress.pendingProps;
16848 var nextChildren = nextProps.children;
16849
16850 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16851 pushHostContextForEventComponent(workInProgress);
16852 return workInProgress.child;
16853}
16854
16855function updateEventTarget(current$$1, workInProgress, renderExpirationTime) {
16856 var nextProps = workInProgress.pendingProps;
16857 var nextChildren = nextProps.children;
16858
16859 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
16860 pushHostContextForEventTarget(workInProgress);
16861 return workInProgress.child;
16862}
16863
16864function markWorkInProgressReceivedUpdate() {
16865 didReceiveUpdate = true;
16866}
16867
16868function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
16869 cancelWorkTimer(workInProgress);
16870
16871 if (current$$1 !== null) {
16872 // Reuse previous context list
16873 workInProgress.contextDependencies = current$$1.contextDependencies;
16874 }
16875
16876 if (enableProfilerTimer) {
16877 // Don't update "base" render times for bailouts.
16878 stopProfilerTimerIfRunning(workInProgress);
16879 }
16880
16881 // Check if the children have any pending work.
16882 var childExpirationTime = workInProgress.childExpirationTime;
16883 if (childExpirationTime < renderExpirationTime) {
16884 // The children don't have any work either. We can skip them.
16885 // TODO: Once we add back resuming, we should check if the children are
16886 // a work-in-progress set. If so, we need to transfer their effects.
16887 return null;
16888 } else {
16889 // This fiber doesn't have work, but its subtree does. Clone the child
16890 // fibers and continue.
16891 cloneChildFibers(current$$1, workInProgress);
16892 return workInProgress.child;
16893 }
16894}
16895
16896function beginWork(current$$1, workInProgress, renderExpirationTime) {
16897 var updateExpirationTime = workInProgress.expirationTime;
16898
16899 if (current$$1 !== null) {
16900 var oldProps = current$$1.memoizedProps;
16901 var newProps = workInProgress.pendingProps;
16902
16903 if (oldProps !== newProps || hasContextChanged()) {
16904 // If props or context changed, mark the fiber as having performed work.
16905 // This may be unset if the props are determined to be equal later (memo).
16906 didReceiveUpdate = true;
16907 } else if (updateExpirationTime < renderExpirationTime) {
16908 didReceiveUpdate = false;
16909 // This fiber does not have any pending work. Bailout without entering
16910 // the begin phase. There's still some bookkeeping we that needs to be done
16911 // in this optimized path, mostly pushing stuff onto the stack.
16912 switch (workInProgress.tag) {
16913 case HostRoot:
16914 pushHostRootContext(workInProgress);
16915 resetHydrationState();
16916 break;
16917 case HostComponent:
16918 pushHostContext(workInProgress);
16919 break;
16920 case ClassComponent:
16921 {
16922 var Component = workInProgress.type;
16923 if (isContextProvider(Component)) {
16924 pushContextProvider(workInProgress);
16925 }
16926 break;
16927 }
16928 case HostPortal:
16929 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
16930 break;
16931 case ContextProvider:
16932 {
16933 var newValue = workInProgress.memoizedProps.value;
16934 pushProvider(workInProgress, newValue);
16935 break;
16936 }
16937 case Profiler:
16938 if (enableProfilerTimer) {
16939 workInProgress.effectTag |= Update;
16940 }
16941 break;
16942 case SuspenseComponent:
16943 {
16944 var state = workInProgress.memoizedState;
16945 var didTimeout = state !== null;
16946 if (didTimeout) {
16947 // If this boundary is currently timed out, we need to decide
16948 // whether to retry the primary children, or to skip over it and
16949 // go straight to the fallback. Check the priority of the primary
16950 var primaryChildFragment = workInProgress.child;
16951 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
16952 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
16953 // The primary children have pending work. Use the normal path
16954 // to attempt to render the primary children again.
16955 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
16956 } else {
16957 // The primary children do not have pending work with sufficient
16958 // priority. Bailout.
16959 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16960 if (child !== null) {
16961 // The fallback children have pending work. Skip over the
16962 // primary children and work on the fallback.
16963 return child.sibling;
16964 } else {
16965 return null;
16966 }
16967 }
16968 }
16969 break;
16970 }
16971 case DehydratedSuspenseComponent:
16972 {
16973 if (enableSuspenseServerRenderer) {
16974 // We know that this component will suspend again because if it has
16975 // been unsuspended it has committed as a regular Suspense component.
16976 // If it needs to be retried, it should have work scheduled on it.
16977 workInProgress.effectTag |= DidCapture;
16978 }
16979 break;
16980 }
16981 case EventComponent:
16982 if (enableEventAPI) {
16983 pushHostContextForEventComponent(workInProgress);
16984 }
16985 break;
16986 case EventTarget:
16987 {
16988 if (enableEventAPI) {
16989 pushHostContextForEventTarget(workInProgress);
16990 }
16991 break;
16992 }
16993 }
16994 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
16995 }
16996 } else {
16997 didReceiveUpdate = false;
16998 }
16999
17000 // Before entering the begin phase, clear the expiration time.
17001 workInProgress.expirationTime = NoWork;
17002
17003 switch (workInProgress.tag) {
17004 case IndeterminateComponent:
17005 {
17006 var elementType = workInProgress.elementType;
17007 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
17008 }
17009 case LazyComponent:
17010 {
17011 var _elementType = workInProgress.elementType;
17012 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
17013 }
17014 case FunctionComponent:
17015 {
17016 var _Component = workInProgress.type;
17017 var unresolvedProps = workInProgress.pendingProps;
17018 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
17019 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
17020 }
17021 case ClassComponent:
17022 {
17023 var _Component2 = workInProgress.type;
17024 var _unresolvedProps = workInProgress.pendingProps;
17025 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
17026 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
17027 }
17028 case HostRoot:
17029 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
17030 case HostComponent:
17031 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
17032 case HostText:
17033 return updateHostText(current$$1, workInProgress);
17034 case SuspenseComponent:
17035 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
17036 case HostPortal:
17037 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
17038 case ForwardRef:
17039 {
17040 var type = workInProgress.type;
17041 var _unresolvedProps2 = workInProgress.pendingProps;
17042 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
17043 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
17044 }
17045 case Fragment:
17046 return updateFragment(current$$1, workInProgress, renderExpirationTime);
17047 case Mode:
17048 return updateMode(current$$1, workInProgress, renderExpirationTime);
17049 case Profiler:
17050 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
17051 case ContextProvider:
17052 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
17053 case ContextConsumer:
17054 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
17055 case MemoComponent:
17056 {
17057 var _type2 = workInProgress.type;
17058 var _unresolvedProps3 = workInProgress.pendingProps;
17059 // Resolve outer props first, then resolve inner props.
17060 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
17061 {
17062 if (workInProgress.type !== workInProgress.elementType) {
17063 var outerPropTypes = _type2.propTypes;
17064 if (outerPropTypes) {
17065 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
17066 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
17067 }
17068 }
17069 }
17070 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
17071 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
17072 }
17073 case SimpleMemoComponent:
17074 {
17075 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
17076 }
17077 case IncompleteClassComponent:
17078 {
17079 var _Component3 = workInProgress.type;
17080 var _unresolvedProps4 = workInProgress.pendingProps;
17081 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
17082 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
17083 }
17084 case DehydratedSuspenseComponent:
17085 {
17086 if (enableSuspenseServerRenderer) {
17087 return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
17088 }
17089 break;
17090 }
17091 case EventComponent:
17092 {
17093 if (enableEventAPI) {
17094 return updateEventComponent(current$$1, workInProgress, renderExpirationTime);
17095 }
17096 break;
17097 }
17098 case EventTarget:
17099 {
17100 if (enableEventAPI) {
17101 return updateEventTarget(current$$1, workInProgress, renderExpirationTime);
17102 }
17103 break;
17104 }
17105 }
17106 (function () {
17107 {
17108 {
17109 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
17110 }
17111 }
17112 })();
17113}
17114
17115var valueCursor = createCursor(null);
17116
17117var rendererSigil = void 0;
17118{
17119 // Use this to detect multiple renderers using the same context
17120 rendererSigil = {};
17121}
17122
17123var currentlyRenderingFiber = null;
17124var lastContextDependency = null;
17125var lastContextWithAllBitsObserved = null;
17126
17127var isDisallowedContextReadInDEV = false;
17128
17129function resetContextDependences() {
17130 // This is called right before React yields execution, to ensure `readContext`
17131 // cannot be called outside the render phase.
17132 currentlyRenderingFiber = null;
17133 lastContextDependency = null;
17134 lastContextWithAllBitsObserved = null;
17135 {
17136 isDisallowedContextReadInDEV = false;
17137 }
17138}
17139
17140function enterDisallowedContextReadInDEV() {
17141 {
17142 isDisallowedContextReadInDEV = true;
17143 }
17144}
17145
17146function exitDisallowedContextReadInDEV() {
17147 {
17148 isDisallowedContextReadInDEV = false;
17149 }
17150}
17151
17152function pushProvider(providerFiber, nextValue) {
17153 var context = providerFiber.type._context;
17154
17155 if (isPrimaryRenderer) {
17156 push(valueCursor, context._currentValue, providerFiber);
17157
17158 context._currentValue = nextValue;
17159 {
17160 !(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;
17161 context._currentRenderer = rendererSigil;
17162 }
17163 } else {
17164 push(valueCursor, context._currentValue2, providerFiber);
17165
17166 context._currentValue2 = nextValue;
17167 {
17168 !(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;
17169 context._currentRenderer2 = rendererSigil;
17170 }
17171 }
17172}
17173
17174function popProvider(providerFiber) {
17175 var currentValue = valueCursor.current;
17176
17177 pop(valueCursor, providerFiber);
17178
17179 var context = providerFiber.type._context;
17180 if (isPrimaryRenderer) {
17181 context._currentValue = currentValue;
17182 } else {
17183 context._currentValue2 = currentValue;
17184 }
17185}
17186
17187function calculateChangedBits(context, newValue, oldValue) {
17188 if (is(oldValue, newValue)) {
17189 // No change
17190 return 0;
17191 } else {
17192 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
17193
17194 {
17195 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
17196 }
17197 return changedBits | 0;
17198 }
17199}
17200
17201function scheduleWorkOnParentPath(parent, renderExpirationTime) {
17202 // Update the child expiration time of all the ancestors, including
17203 // the alternates.
17204 var node = parent;
17205 while (node !== null) {
17206 var alternate = node.alternate;
17207 if (node.childExpirationTime < renderExpirationTime) {
17208 node.childExpirationTime = renderExpirationTime;
17209 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
17210 alternate.childExpirationTime = renderExpirationTime;
17211 }
17212 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
17213 alternate.childExpirationTime = renderExpirationTime;
17214 } else {
17215 // Neither alternate was updated, which means the rest of the
17216 // ancestor path already has sufficient priority.
17217 break;
17218 }
17219 node = node.return;
17220 }
17221}
17222
17223function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
17224 var fiber = workInProgress.child;
17225 if (fiber !== null) {
17226 // Set the return pointer of the child to the work-in-progress fiber.
17227 fiber.return = workInProgress;
17228 }
17229 while (fiber !== null) {
17230 var nextFiber = void 0;
17231
17232 // Visit this fiber.
17233 var list = fiber.contextDependencies;
17234 if (list !== null) {
17235 nextFiber = fiber.child;
17236
17237 var dependency = list.first;
17238 while (dependency !== null) {
17239 // Check if the context matches.
17240 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
17241 // Match! Schedule an update on this fiber.
17242
17243 if (fiber.tag === ClassComponent) {
17244 // Schedule a force update on the work-in-progress.
17245 var update = createUpdate(renderExpirationTime);
17246 update.tag = ForceUpdate;
17247 // TODO: Because we don't have a work-in-progress, this will add the
17248 // update to the current fiber, too, which means it will persist even if
17249 // this render is thrown away. Since it's a race condition, not sure it's
17250 // worth fixing.
17251 enqueueUpdate(fiber, update);
17252 }
17253
17254 if (fiber.expirationTime < renderExpirationTime) {
17255 fiber.expirationTime = renderExpirationTime;
17256 }
17257 var alternate = fiber.alternate;
17258 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
17259 alternate.expirationTime = renderExpirationTime;
17260 }
17261
17262 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
17263
17264 // Mark the expiration time on the list, too.
17265 if (list.expirationTime < renderExpirationTime) {
17266 list.expirationTime = renderExpirationTime;
17267 }
17268
17269 // Since we already found a match, we can stop traversing the
17270 // dependency list.
17271 break;
17272 }
17273 dependency = dependency.next;
17274 }
17275 } else if (fiber.tag === ContextProvider) {
17276 // Don't scan deeper if this is a matching provider
17277 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
17278 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
17279 // If a dehydrated suspense component is in this subtree, we don't know
17280 // if it will have any context consumers in it. The best we can do is
17281 // mark it as having updates on its children.
17282 if (fiber.expirationTime < renderExpirationTime) {
17283 fiber.expirationTime = renderExpirationTime;
17284 }
17285 var _alternate = fiber.alternate;
17286 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
17287 _alternate.expirationTime = renderExpirationTime;
17288 }
17289 // This is intentionally passing this fiber as the parent
17290 // because we want to schedule this fiber as having work
17291 // on its children. We'll use the childExpirationTime on
17292 // this fiber to indicate that a context has changed.
17293 scheduleWorkOnParentPath(fiber, renderExpirationTime);
17294 nextFiber = fiber.sibling;
17295 } else {
17296 // Traverse down.
17297 nextFiber = fiber.child;
17298 }
17299
17300 if (nextFiber !== null) {
17301 // Set the return pointer of the child to the work-in-progress fiber.
17302 nextFiber.return = fiber;
17303 } else {
17304 // No child. Traverse to next sibling.
17305 nextFiber = fiber;
17306 while (nextFiber !== null) {
17307 if (nextFiber === workInProgress) {
17308 // We're back to the root of this subtree. Exit.
17309 nextFiber = null;
17310 break;
17311 }
17312 var sibling = nextFiber.sibling;
17313 if (sibling !== null) {
17314 // Set the return pointer of the sibling to the work-in-progress fiber.
17315 sibling.return = nextFiber.return;
17316 nextFiber = sibling;
17317 break;
17318 }
17319 // No more siblings. Traverse up.
17320 nextFiber = nextFiber.return;
17321 }
17322 }
17323 fiber = nextFiber;
17324 }
17325}
17326
17327function prepareToReadContext(workInProgress, renderExpirationTime) {
17328 currentlyRenderingFiber = workInProgress;
17329 lastContextDependency = null;
17330 lastContextWithAllBitsObserved = null;
17331
17332 var currentDependencies = workInProgress.contextDependencies;
17333 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
17334 // Context list has a pending update. Mark that this fiber performed work.
17335 markWorkInProgressReceivedUpdate();
17336 }
17337
17338 // Reset the work-in-progress list
17339 workInProgress.contextDependencies = null;
17340}
17341
17342function readContext(context, observedBits) {
17343 {
17344 // This warning would fire if you read context inside a Hook like useMemo.
17345 // Unlike the class check below, it's not enforced in production for perf.
17346 !!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;
17347 }
17348
17349 if (lastContextWithAllBitsObserved === context) {
17350 // Nothing to do. We already observe everything in this context.
17351 } else if (observedBits === false || observedBits === 0) {
17352 // Do not observe any updates.
17353 } else {
17354 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
17355 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
17356 // Observe all updates.
17357 lastContextWithAllBitsObserved = context;
17358 resolvedObservedBits = maxSigned31BitInt;
17359 } else {
17360 resolvedObservedBits = observedBits;
17361 }
17362
17363 var contextItem = {
17364 context: context,
17365 observedBits: resolvedObservedBits,
17366 next: null
17367 };
17368
17369 if (lastContextDependency === null) {
17370 (function () {
17371 if (!(currentlyRenderingFiber !== null)) {
17372 {
17373 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().');
17374 }
17375 }
17376 })();
17377
17378 // This is the first dependency for this component. Create a new list.
17379 lastContextDependency = contextItem;
17380 currentlyRenderingFiber.contextDependencies = {
17381 first: contextItem,
17382 expirationTime: NoWork
17383 };
17384 } else {
17385 // Append a new context item.
17386 lastContextDependency = lastContextDependency.next = contextItem;
17387 }
17388 }
17389 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
17390}
17391
17392// UpdateQueue is a linked list of prioritized updates.
17393//
17394// Like fibers, update queues come in pairs: a current queue, which represents
17395// the visible state of the screen, and a work-in-progress queue, which can be
17396// mutated and processed asynchronously before it is committed — a form of
17397// double buffering. If a work-in-progress render is discarded before finishing,
17398// we create a new work-in-progress by cloning the current queue.
17399//
17400// Both queues share a persistent, singly-linked list structure. To schedule an
17401// update, we append it to the end of both queues. Each queue maintains a
17402// pointer to first update in the persistent list that hasn't been processed.
17403// The work-in-progress pointer always has a position equal to or greater than
17404// the current queue, since we always work on that one. The current queue's
17405// pointer is only updated during the commit phase, when we swap in the
17406// work-in-progress.
17407//
17408// For example:
17409//
17410// Current pointer: A - B - C - D - E - F
17411// Work-in-progress pointer: D - E - F
17412// ^
17413// The work-in-progress queue has
17414// processed more updates than current.
17415//
17416// The reason we append to both queues is because otherwise we might drop
17417// updates without ever processing them. For example, if we only add updates to
17418// the work-in-progress queue, some updates could be lost whenever a work-in
17419// -progress render restarts by cloning from current. Similarly, if we only add
17420// updates to the current queue, the updates will be lost whenever an already
17421// in-progress queue commits and swaps with the current queue. However, by
17422// adding to both queues, we guarantee that the update will be part of the next
17423// work-in-progress. (And because the work-in-progress queue becomes the
17424// current queue once it commits, there's no danger of applying the same
17425// update twice.)
17426//
17427// Prioritization
17428// --------------
17429//
17430// Updates are not sorted by priority, but by insertion; new updates are always
17431// appended to the end of the list.
17432//
17433// The priority is still important, though. When processing the update queue
17434// during the render phase, only the updates with sufficient priority are
17435// included in the result. If we skip an update because it has insufficient
17436// priority, it remains in the queue to be processed later, during a lower
17437// priority render. Crucially, all updates subsequent to a skipped update also
17438// remain in the queue *regardless of their priority*. That means high priority
17439// updates are sometimes processed twice, at two separate priorities. We also
17440// keep track of a base state, that represents the state before the first
17441// update in the queue is applied.
17442//
17443// For example:
17444//
17445// Given a base state of '', and the following queue of updates
17446//
17447// A1 - B2 - C1 - D2
17448//
17449// where the number indicates the priority, and the update is applied to the
17450// previous state by appending a letter, React will process these updates as
17451// two separate renders, one per distinct priority level:
17452//
17453// First render, at priority 1:
17454// Base state: ''
17455// Updates: [A1, C1]
17456// Result state: 'AC'
17457//
17458// Second render, at priority 2:
17459// Base state: 'A' <- The base state does not include C1,
17460// because B2 was skipped.
17461// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
17462// Result state: 'ABCD'
17463//
17464// Because we process updates in insertion order, and rebase high priority
17465// updates when preceding updates are skipped, the final result is deterministic
17466// regardless of priority. Intermediate state may vary according to system
17467// resources, but the final state is always the same.
17468
17469var UpdateState = 0;
17470var ReplaceState = 1;
17471var ForceUpdate = 2;
17472var CaptureUpdate = 3;
17473
17474// Global state that is reset at the beginning of calling `processUpdateQueue`.
17475// It should only be read right after calling `processUpdateQueue`, via
17476// `checkHasForceUpdateAfterProcessing`.
17477var hasForceUpdate = false;
17478
17479var didWarnUpdateInsideUpdate = void 0;
17480var currentlyProcessingQueue = void 0;
17481var resetCurrentlyProcessingQueue = void 0;
17482{
17483 didWarnUpdateInsideUpdate = false;
17484 currentlyProcessingQueue = null;
17485 resetCurrentlyProcessingQueue = function () {
17486 currentlyProcessingQueue = null;
17487 };
17488}
17489
17490function createUpdateQueue(baseState) {
17491 var queue = {
17492 baseState: baseState,
17493 firstUpdate: null,
17494 lastUpdate: null,
17495 firstCapturedUpdate: null,
17496 lastCapturedUpdate: null,
17497 firstEffect: null,
17498 lastEffect: null,
17499 firstCapturedEffect: null,
17500 lastCapturedEffect: null
17501 };
17502 return queue;
17503}
17504
17505function cloneUpdateQueue(currentQueue) {
17506 var queue = {
17507 baseState: currentQueue.baseState,
17508 firstUpdate: currentQueue.firstUpdate,
17509 lastUpdate: currentQueue.lastUpdate,
17510
17511 // TODO: With resuming, if we bail out and resuse the child tree, we should
17512 // keep these effects.
17513 firstCapturedUpdate: null,
17514 lastCapturedUpdate: null,
17515
17516 firstEffect: null,
17517 lastEffect: null,
17518
17519 firstCapturedEffect: null,
17520 lastCapturedEffect: null
17521 };
17522 return queue;
17523}
17524
17525function createUpdate(expirationTime) {
17526 return {
17527 expirationTime: expirationTime,
17528
17529 tag: UpdateState,
17530 payload: null,
17531 callback: null,
17532
17533 next: null,
17534 nextEffect: null
17535 };
17536}
17537
17538function appendUpdateToQueue(queue, update) {
17539 // Append the update to the end of the list.
17540 if (queue.lastUpdate === null) {
17541 // Queue is empty
17542 queue.firstUpdate = queue.lastUpdate = update;
17543 } else {
17544 queue.lastUpdate.next = update;
17545 queue.lastUpdate = update;
17546 }
17547}
17548
17549function enqueueUpdate(fiber, update) {
17550 // Update queues are created lazily.
17551 var alternate = fiber.alternate;
17552 var queue1 = void 0;
17553 var queue2 = void 0;
17554 if (alternate === null) {
17555 // There's only one fiber.
17556 queue1 = fiber.updateQueue;
17557 queue2 = null;
17558 if (queue1 === null) {
17559 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
17560 }
17561 } else {
17562 // There are two owners.
17563 queue1 = fiber.updateQueue;
17564 queue2 = alternate.updateQueue;
17565 if (queue1 === null) {
17566 if (queue2 === null) {
17567 // Neither fiber has an update queue. Create new ones.
17568 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
17569 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
17570 } else {
17571 // Only one fiber has an update queue. Clone to create a new one.
17572 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
17573 }
17574 } else {
17575 if (queue2 === null) {
17576 // Only one fiber has an update queue. Clone to create a new one.
17577 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
17578 } else {
17579 // Both owners have an update queue.
17580 }
17581 }
17582 }
17583 if (queue2 === null || queue1 === queue2) {
17584 // There's only a single queue.
17585 appendUpdateToQueue(queue1, update);
17586 } else {
17587 // There are two queues. We need to append the update to both queues,
17588 // while accounting for the persistent structure of the list — we don't
17589 // want the same update to be added multiple times.
17590 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
17591 // One of the queues is not empty. We must add the update to both queues.
17592 appendUpdateToQueue(queue1, update);
17593 appendUpdateToQueue(queue2, update);
17594 } else {
17595 // Both queues are non-empty. The last update is the same in both lists,
17596 // because of structural sharing. So, only append to one of the lists.
17597 appendUpdateToQueue(queue1, update);
17598 // But we still need to update the `lastUpdate` pointer of queue2.
17599 queue2.lastUpdate = update;
17600 }
17601 }
17602
17603 {
17604 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
17605 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.');
17606 didWarnUpdateInsideUpdate = true;
17607 }
17608 }
17609}
17610
17611function enqueueCapturedUpdate(workInProgress, update) {
17612 // Captured updates go into a separate list, and only on the work-in-
17613 // progress queue.
17614 var workInProgressQueue = workInProgress.updateQueue;
17615 if (workInProgressQueue === null) {
17616 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
17617 } else {
17618 // TODO: I put this here rather than createWorkInProgress so that we don't
17619 // clone the queue unnecessarily. There's probably a better way to
17620 // structure this.
17621 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
17622 }
17623
17624 // Append the update to the end of the list.
17625 if (workInProgressQueue.lastCapturedUpdate === null) {
17626 // This is the first render phase update
17627 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
17628 } else {
17629 workInProgressQueue.lastCapturedUpdate.next = update;
17630 workInProgressQueue.lastCapturedUpdate = update;
17631 }
17632}
17633
17634function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
17635 var current = workInProgress.alternate;
17636 if (current !== null) {
17637 // If the work-in-progress queue is equal to the current queue,
17638 // we need to clone it first.
17639 if (queue === current.updateQueue) {
17640 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
17641 }
17642 }
17643 return queue;
17644}
17645
17646function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
17647 switch (update.tag) {
17648 case ReplaceState:
17649 {
17650 var _payload = update.payload;
17651 if (typeof _payload === 'function') {
17652 // Updater function
17653 {
17654 enterDisallowedContextReadInDEV();
17655 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
17656 _payload.call(instance, prevState, nextProps);
17657 }
17658 }
17659 var nextState = _payload.call(instance, prevState, nextProps);
17660 {
17661 exitDisallowedContextReadInDEV();
17662 }
17663 return nextState;
17664 }
17665 // State object
17666 return _payload;
17667 }
17668 case CaptureUpdate:
17669 {
17670 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
17671 }
17672 // Intentional fallthrough
17673 case UpdateState:
17674 {
17675 var _payload2 = update.payload;
17676 var partialState = void 0;
17677 if (typeof _payload2 === 'function') {
17678 // Updater function
17679 {
17680 enterDisallowedContextReadInDEV();
17681 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
17682 _payload2.call(instance, prevState, nextProps);
17683 }
17684 }
17685 partialState = _payload2.call(instance, prevState, nextProps);
17686 {
17687 exitDisallowedContextReadInDEV();
17688 }
17689 } else {
17690 // Partial state object
17691 partialState = _payload2;
17692 }
17693 if (partialState === null || partialState === undefined) {
17694 // Null and undefined are treated as no-ops.
17695 return prevState;
17696 }
17697 // Merge the partial state and the previous state.
17698 return _assign({}, prevState, partialState);
17699 }
17700 case ForceUpdate:
17701 {
17702 hasForceUpdate = true;
17703 return prevState;
17704 }
17705 }
17706 return prevState;
17707}
17708
17709function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
17710 hasForceUpdate = false;
17711
17712 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
17713
17714 {
17715 currentlyProcessingQueue = queue;
17716 }
17717
17718 // These values may change as we process the queue.
17719 var newBaseState = queue.baseState;
17720 var newFirstUpdate = null;
17721 var newExpirationTime = NoWork;
17722
17723 // Iterate through the list of updates to compute the result.
17724 var update = queue.firstUpdate;
17725 var resultState = newBaseState;
17726 while (update !== null) {
17727 var updateExpirationTime = update.expirationTime;
17728 if (updateExpirationTime < renderExpirationTime) {
17729 // This update does not have sufficient priority. Skip it.
17730 if (newFirstUpdate === null) {
17731 // This is the first skipped update. It will be the first update in
17732 // the new list.
17733 newFirstUpdate = update;
17734 // Since this is the first update that was skipped, the current result
17735 // is the new base state.
17736 newBaseState = resultState;
17737 }
17738 // Since this update will remain in the list, update the remaining
17739 // expiration time.
17740 if (newExpirationTime < updateExpirationTime) {
17741 newExpirationTime = updateExpirationTime;
17742 }
17743 } else {
17744 // This update does have sufficient priority. Process it and compute
17745 // a new result.
17746 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
17747 var _callback = update.callback;
17748 if (_callback !== null) {
17749 workInProgress.effectTag |= Callback;
17750 // Set this to null, in case it was mutated during an aborted render.
17751 update.nextEffect = null;
17752 if (queue.lastEffect === null) {
17753 queue.firstEffect = queue.lastEffect = update;
17754 } else {
17755 queue.lastEffect.nextEffect = update;
17756 queue.lastEffect = update;
17757 }
17758 }
17759 }
17760 // Continue to the next update.
17761 update = update.next;
17762 }
17763
17764 // Separately, iterate though the list of captured updates.
17765 var newFirstCapturedUpdate = null;
17766 update = queue.firstCapturedUpdate;
17767 while (update !== null) {
17768 var _updateExpirationTime = update.expirationTime;
17769 if (_updateExpirationTime < renderExpirationTime) {
17770 // This update does not have sufficient priority. Skip it.
17771 if (newFirstCapturedUpdate === null) {
17772 // This is the first skipped captured update. It will be the first
17773 // update in the new list.
17774 newFirstCapturedUpdate = update;
17775 // If this is the first update that was skipped, the current result is
17776 // the new base state.
17777 if (newFirstUpdate === null) {
17778 newBaseState = resultState;
17779 }
17780 }
17781 // Since this update will remain in the list, update the remaining
17782 // expiration time.
17783 if (newExpirationTime < _updateExpirationTime) {
17784 newExpirationTime = _updateExpirationTime;
17785 }
17786 } else {
17787 // This update does have sufficient priority. Process it and compute
17788 // a new result.
17789 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
17790 var _callback2 = update.callback;
17791 if (_callback2 !== null) {
17792 workInProgress.effectTag |= Callback;
17793 // Set this to null, in case it was mutated during an aborted render.
17794 update.nextEffect = null;
17795 if (queue.lastCapturedEffect === null) {
17796 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
17797 } else {
17798 queue.lastCapturedEffect.nextEffect = update;
17799 queue.lastCapturedEffect = update;
17800 }
17801 }
17802 }
17803 update = update.next;
17804 }
17805
17806 if (newFirstUpdate === null) {
17807 queue.lastUpdate = null;
17808 }
17809 if (newFirstCapturedUpdate === null) {
17810 queue.lastCapturedUpdate = null;
17811 } else {
17812 workInProgress.effectTag |= Callback;
17813 }
17814 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
17815 // We processed every update, without skipping. That means the new base
17816 // state is the same as the result state.
17817 newBaseState = resultState;
17818 }
17819
17820 queue.baseState = newBaseState;
17821 queue.firstUpdate = newFirstUpdate;
17822 queue.firstCapturedUpdate = newFirstCapturedUpdate;
17823
17824 // Set the remaining expiration time to be whatever is remaining in the queue.
17825 // This should be fine because the only two other things that contribute to
17826 // expiration time are props and context. We're already in the middle of the
17827 // begin phase by the time we start processing the queue, so we've already
17828 // dealt with the props. Context in components that specify
17829 // shouldComponentUpdate is tricky; but we'll have to account for
17830 // that regardless.
17831 workInProgress.expirationTime = newExpirationTime;
17832 workInProgress.memoizedState = resultState;
17833
17834 {
17835 currentlyProcessingQueue = null;
17836 }
17837}
17838
17839function callCallback(callback, context) {
17840 (function () {
17841 if (!(typeof callback === 'function')) {
17842 {
17843 throw ReactError('Invalid argument passed as callback. Expected a function. Instead received: ' + callback);
17844 }
17845 }
17846 })();
17847 callback.call(context);
17848}
17849
17850function resetHasForceUpdateBeforeProcessing() {
17851 hasForceUpdate = false;
17852}
17853
17854function checkHasForceUpdateAfterProcessing() {
17855 return hasForceUpdate;
17856}
17857
17858function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
17859 // If the finished render included captured updates, and there are still
17860 // lower priority updates left over, we need to keep the captured updates
17861 // in the queue so that they are rebased and not dropped once we process the
17862 // queue again at the lower priority.
17863 if (finishedQueue.firstCapturedUpdate !== null) {
17864 // Join the captured update list to the end of the normal list.
17865 if (finishedQueue.lastUpdate !== null) {
17866 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
17867 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
17868 }
17869 // Clear the list of captured updates.
17870 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
17871 }
17872
17873 // Commit the effects
17874 commitUpdateEffects(finishedQueue.firstEffect, instance);
17875 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
17876
17877 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
17878 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
17879}
17880
17881function commitUpdateEffects(effect, instance) {
17882 while (effect !== null) {
17883 var _callback3 = effect.callback;
17884 if (_callback3 !== null) {
17885 effect.callback = null;
17886 callCallback(_callback3, instance);
17887 }
17888 effect = effect.nextEffect;
17889 }
17890}
17891
17892function createCapturedValue(value, source) {
17893 // If the value is an error, call this function immediately after it is thrown
17894 // so the stack is accurate.
17895 return {
17896 value: value,
17897 source: source,
17898 stack: getStackByFiberInDevAndProd(source)
17899 };
17900}
17901
17902function markUpdate(workInProgress) {
17903 // Tag the fiber with an update effect. This turns a Placement into
17904 // a PlacementAndUpdate.
17905 workInProgress.effectTag |= Update;
17906}
17907
17908function markRef$1(workInProgress) {
17909 workInProgress.effectTag |= Ref;
17910}
17911
17912var appendAllChildren = void 0;
17913var updateHostContainer = void 0;
17914var updateHostComponent$1 = void 0;
17915var updateHostText$1 = void 0;
17916if (supportsMutation) {
17917 // Mutation mode
17918
17919 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
17920 // We only have the top Fiber that was created but we need recurse down its
17921 // children to find all the terminal nodes.
17922 var node = workInProgress.child;
17923 while (node !== null) {
17924 if (node.tag === HostComponent || node.tag === HostText) {
17925 appendInitialChild(parent, node.stateNode);
17926 } else if (node.tag === HostPortal) {
17927 // If we have a portal child, then we don't want to traverse
17928 // down its children. Instead, we'll get insertions from each child in
17929 // the portal directly.
17930 } else if (node.child !== null) {
17931 node.child.return = node;
17932 node = node.child;
17933 continue;
17934 }
17935 if (node === workInProgress) {
17936 return;
17937 }
17938 while (node.sibling === null) {
17939 if (node.return === null || node.return === workInProgress) {
17940 return;
17941 }
17942 node = node.return;
17943 }
17944 node.sibling.return = node.return;
17945 node = node.sibling;
17946 }
17947 };
17948
17949 updateHostContainer = function (workInProgress) {
17950 // Noop
17951 };
17952 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
17953 // If we have an alternate, that means this is an update and we need to
17954 // schedule a side-effect to do the updates.
17955 var oldProps = current.memoizedProps;
17956 if (oldProps === newProps) {
17957 // In mutation mode, this is sufficient for a bailout because
17958 // we won't touch this node even if children changed.
17959 return;
17960 }
17961
17962 // If we get updated because one of our children updated, we don't
17963 // have newProps so we'll have to reuse them.
17964 // TODO: Split the update API as separate for the props vs. children.
17965 // Even better would be if children weren't special cased at all tho.
17966 var instance = workInProgress.stateNode;
17967 var currentHostContext = getHostContext();
17968 // TODO: Experiencing an error where oldProps is null. Suggests a host
17969 // component is hitting the resume path. Figure out why. Possibly
17970 // related to `hidden`.
17971 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
17972 // TODO: Type this specific to this type of component.
17973 workInProgress.updateQueue = updatePayload;
17974 // If the update payload indicates that there is a change or if there
17975 // is a new ref we mark this as an update. All the work is done in commitWork.
17976 if (updatePayload) {
17977 markUpdate(workInProgress);
17978 }
17979 };
17980 updateHostText$1 = function (current, workInProgress, oldText, newText) {
17981 // If the text differs, mark it as an update. All the work in done in commitWork.
17982 if (oldText !== newText) {
17983 markUpdate(workInProgress);
17984 }
17985 };
17986} else if (supportsPersistence) {
17987 // Persistent host tree mode
17988
17989 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
17990 // We only have the top Fiber that was created but we need recurse down its
17991 // children to find all the terminal nodes.
17992 var node = workInProgress.child;
17993 while (node !== null) {
17994 // eslint-disable-next-line no-labels
17995 branches: if (node.tag === HostComponent) {
17996 var instance = node.stateNode;
17997 if (needsVisibilityToggle && isHidden) {
17998 // This child is inside a timed out tree. Hide it.
17999 var props = node.memoizedProps;
18000 var type = node.type;
18001 instance = cloneHiddenInstance(instance, type, props, node);
18002 }
18003 appendInitialChild(parent, instance);
18004 } else if (node.tag === HostText) {
18005 var _instance = node.stateNode;
18006 if (needsVisibilityToggle && isHidden) {
18007 // This child is inside a timed out tree. Hide it.
18008 var text = node.memoizedProps;
18009 _instance = cloneHiddenTextInstance(_instance, text, node);
18010 }
18011 appendInitialChild(parent, _instance);
18012 } else if (node.tag === HostPortal) {
18013 // If we have a portal child, then we don't want to traverse
18014 // down its children. Instead, we'll get insertions from each child in
18015 // the portal directly.
18016 } else if (node.tag === SuspenseComponent) {
18017 if ((node.effectTag & Update) !== NoEffect) {
18018 // Need to toggle the visibility of the primary children.
18019 var newIsHidden = node.memoizedState !== null;
18020 if (newIsHidden) {
18021 var primaryChildParent = node.child;
18022 if (primaryChildParent !== null) {
18023 if (primaryChildParent.child !== null) {
18024 primaryChildParent.child.return = primaryChildParent;
18025 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
18026 }
18027 var fallbackChildParent = primaryChildParent.sibling;
18028 if (fallbackChildParent !== null) {
18029 fallbackChildParent.return = node;
18030 node = fallbackChildParent;
18031 continue;
18032 }
18033 }
18034 }
18035 }
18036 if (node.child !== null) {
18037 // Continue traversing like normal
18038 node.child.return = node;
18039 node = node.child;
18040 continue;
18041 }
18042 } else if (node.child !== null) {
18043 node.child.return = node;
18044 node = node.child;
18045 continue;
18046 }
18047 // $FlowFixMe This is correct but Flow is confused by the labeled break.
18048 node = node;
18049 if (node === workInProgress) {
18050 return;
18051 }
18052 while (node.sibling === null) {
18053 if (node.return === null || node.return === workInProgress) {
18054 return;
18055 }
18056 node = node.return;
18057 }
18058 node.sibling.return = node.return;
18059 node = node.sibling;
18060 }
18061 };
18062
18063 // An unfortunate fork of appendAllChildren because we have two different parent types.
18064 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
18065 // We only have the top Fiber that was created but we need recurse down its
18066 // children to find all the terminal nodes.
18067 var node = workInProgress.child;
18068 while (node !== null) {
18069 // eslint-disable-next-line no-labels
18070 branches: if (node.tag === HostComponent) {
18071 var instance = node.stateNode;
18072 if (needsVisibilityToggle && isHidden) {
18073 // This child is inside a timed out tree. Hide it.
18074 var props = node.memoizedProps;
18075 var type = node.type;
18076 instance = cloneHiddenInstance(instance, type, props, node);
18077 }
18078 appendChildToContainerChildSet(containerChildSet, instance);
18079 } else if (node.tag === HostText) {
18080 var _instance2 = node.stateNode;
18081 if (needsVisibilityToggle && isHidden) {
18082 // This child is inside a timed out tree. Hide it.
18083 var text = node.memoizedProps;
18084 _instance2 = cloneHiddenTextInstance(_instance2, text, node);
18085 }
18086 appendChildToContainerChildSet(containerChildSet, _instance2);
18087 } else if (node.tag === HostPortal) {
18088 // If we have a portal child, then we don't want to traverse
18089 // down its children. Instead, we'll get insertions from each child in
18090 // the portal directly.
18091 } else if (node.tag === SuspenseComponent) {
18092 if ((node.effectTag & Update) !== NoEffect) {
18093 // Need to toggle the visibility of the primary children.
18094 var newIsHidden = node.memoizedState !== null;
18095 if (newIsHidden) {
18096 var primaryChildParent = node.child;
18097 if (primaryChildParent !== null) {
18098 if (primaryChildParent.child !== null) {
18099 primaryChildParent.child.return = primaryChildParent;
18100 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
18101 }
18102 var fallbackChildParent = primaryChildParent.sibling;
18103 if (fallbackChildParent !== null) {
18104 fallbackChildParent.return = node;
18105 node = fallbackChildParent;
18106 continue;
18107 }
18108 }
18109 }
18110 }
18111 if (node.child !== null) {
18112 // Continue traversing like normal
18113 node.child.return = node;
18114 node = node.child;
18115 continue;
18116 }
18117 } else if (node.child !== null) {
18118 node.child.return = node;
18119 node = node.child;
18120 continue;
18121 }
18122 // $FlowFixMe This is correct but Flow is confused by the labeled break.
18123 node = node;
18124 if (node === workInProgress) {
18125 return;
18126 }
18127 while (node.sibling === null) {
18128 if (node.return === null || node.return === workInProgress) {
18129 return;
18130 }
18131 node = node.return;
18132 }
18133 node.sibling.return = node.return;
18134 node = node.sibling;
18135 }
18136 };
18137 updateHostContainer = function (workInProgress) {
18138 var portalOrRoot = workInProgress.stateNode;
18139 var childrenUnchanged = workInProgress.firstEffect === null;
18140 if (childrenUnchanged) {
18141 // No changes, just reuse the existing instance.
18142 } else {
18143 var container = portalOrRoot.containerInfo;
18144 var newChildSet = createContainerChildSet(container);
18145 // If children might have changed, we have to add them all to the set.
18146 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
18147 portalOrRoot.pendingChildren = newChildSet;
18148 // Schedule an update on the container to swap out the container.
18149 markUpdate(workInProgress);
18150 finalizeContainerChildren(container, newChildSet);
18151 }
18152 };
18153 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
18154 var currentInstance = current.stateNode;
18155 var oldProps = current.memoizedProps;
18156 // If there are no effects associated with this node, then none of our children had any updates.
18157 // This guarantees that we can reuse all of them.
18158 var childrenUnchanged = workInProgress.firstEffect === null;
18159 if (childrenUnchanged && oldProps === newProps) {
18160 // No changes, just reuse the existing instance.
18161 // Note that this might release a previous clone.
18162 workInProgress.stateNode = currentInstance;
18163 return;
18164 }
18165 var recyclableInstance = workInProgress.stateNode;
18166 var currentHostContext = getHostContext();
18167 var updatePayload = null;
18168 if (oldProps !== newProps) {
18169 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
18170 }
18171 if (childrenUnchanged && updatePayload === null) {
18172 // No changes, just reuse the existing instance.
18173 // Note that this might release a previous clone.
18174 workInProgress.stateNode = currentInstance;
18175 return;
18176 }
18177 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
18178 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
18179 markUpdate(workInProgress);
18180 }
18181 workInProgress.stateNode = newInstance;
18182 if (childrenUnchanged) {
18183 // If there are no other effects in this tree, we need to flag this node as having one.
18184 // Even though we're not going to use it for anything.
18185 // Otherwise parents won't know that there are new children to propagate upwards.
18186 markUpdate(workInProgress);
18187 } else {
18188 // If children might have changed, we have to add them all to the set.
18189 appendAllChildren(newInstance, workInProgress, false, false);
18190 }
18191 };
18192 updateHostText$1 = function (current, workInProgress, oldText, newText) {
18193 if (oldText !== newText) {
18194 // If the text content differs, we'll create a new text instance for it.
18195 var rootContainerInstance = getRootHostContainer();
18196 var currentHostContext = getHostContext();
18197 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
18198 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
18199 // This lets the parents know that at least one of their children has changed.
18200 markUpdate(workInProgress);
18201 }
18202 };
18203} else {
18204 // No host operations
18205 updateHostContainer = function (workInProgress) {
18206 // Noop
18207 };
18208 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
18209 // Noop
18210 };
18211 updateHostText$1 = function (current, workInProgress, oldText, newText) {
18212 // Noop
18213 };
18214}
18215
18216function completeWork(current, workInProgress, renderExpirationTime) {
18217 var newProps = workInProgress.pendingProps;
18218
18219 switch (workInProgress.tag) {
18220 case IndeterminateComponent:
18221 break;
18222 case LazyComponent:
18223 break;
18224 case SimpleMemoComponent:
18225 case FunctionComponent:
18226 break;
18227 case ClassComponent:
18228 {
18229 var Component = workInProgress.type;
18230 if (isContextProvider(Component)) {
18231 popContext(workInProgress);
18232 }
18233 break;
18234 }
18235 case HostRoot:
18236 {
18237 popHostContainer(workInProgress);
18238 popTopLevelContextObject(workInProgress);
18239 var fiberRoot = workInProgress.stateNode;
18240 if (fiberRoot.pendingContext) {
18241 fiberRoot.context = fiberRoot.pendingContext;
18242 fiberRoot.pendingContext = null;
18243 }
18244 if (current === null || current.child === null) {
18245 // If we hydrated, pop so that we can delete any remaining children
18246 // that weren't hydrated.
18247 popHydrationState(workInProgress);
18248 // This resets the hacky state to fix isMounted before committing.
18249 // TODO: Delete this when we delete isMounted and findDOMNode.
18250 workInProgress.effectTag &= ~Placement;
18251 }
18252 updateHostContainer(workInProgress);
18253 break;
18254 }
18255 case HostComponent:
18256 {
18257 popHostContext(workInProgress);
18258 var rootContainerInstance = getRootHostContainer();
18259 var type = workInProgress.type;
18260 if (current !== null && workInProgress.stateNode != null) {
18261 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
18262
18263 if (current.ref !== workInProgress.ref) {
18264 markRef$1(workInProgress);
18265 }
18266 } else {
18267 if (!newProps) {
18268 (function () {
18269 if (!(workInProgress.stateNode !== null)) {
18270 {
18271 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
18272 }
18273 }
18274 })();
18275 // This can happen when we abort work.
18276 break;
18277 }
18278
18279 var currentHostContext = getHostContext();
18280 // TODO: Move createInstance to beginWork and keep it on a context
18281 // "stack" as the parent. Then append children as we go in beginWork
18282 // or completeWork depending on we want to add then top->down or
18283 // bottom->up. Top->down is faster in IE11.
18284 var wasHydrated = popHydrationState(workInProgress);
18285 if (wasHydrated) {
18286 // TODO: Move this and createInstance step into the beginPhase
18287 // to consolidate.
18288 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
18289 // If changes to the hydrated node needs to be applied at the
18290 // commit-phase we mark this as such.
18291 markUpdate(workInProgress);
18292 }
18293 } else {
18294 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
18295
18296 appendAllChildren(instance, workInProgress, false, false);
18297
18298 // Certain renderers require commit-time effects for initial mount.
18299 // (eg DOM renderer supports auto-focus for certain elements).
18300 // Make sure such renderers get scheduled for later work.
18301 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
18302 markUpdate(workInProgress);
18303 }
18304 workInProgress.stateNode = instance;
18305 }
18306
18307 if (workInProgress.ref !== null) {
18308 // If there is a ref on a host node we need to schedule a callback
18309 markRef$1(workInProgress);
18310 }
18311 }
18312 break;
18313 }
18314 case HostText:
18315 {
18316 var newText = newProps;
18317 if (current && workInProgress.stateNode != null) {
18318 var oldText = current.memoizedProps;
18319 // If we have an alternate, that means this is an update and we need
18320 // to schedule a side-effect to do the updates.
18321 updateHostText$1(current, workInProgress, oldText, newText);
18322 } else {
18323 if (typeof newText !== 'string') {
18324 (function () {
18325 if (!(workInProgress.stateNode !== null)) {
18326 {
18327 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
18328 }
18329 }
18330 })();
18331 // This can happen when we abort work.
18332 }
18333 var _rootContainerInstance = getRootHostContainer();
18334 var _currentHostContext = getHostContext();
18335 var _wasHydrated = popHydrationState(workInProgress);
18336 if (_wasHydrated) {
18337 if (prepareToHydrateHostTextInstance(workInProgress)) {
18338 markUpdate(workInProgress);
18339 }
18340 } else {
18341 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
18342 }
18343 }
18344 break;
18345 }
18346 case ForwardRef:
18347 break;
18348 case SuspenseComponent:
18349 {
18350 var nextState = workInProgress.memoizedState;
18351 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
18352 // Something suspended. Re-render with the fallback children.
18353 workInProgress.expirationTime = renderExpirationTime;
18354 // Do not reset the effect list.
18355 return workInProgress;
18356 }
18357
18358 var nextDidTimeout = nextState !== null;
18359 var prevDidTimeout = current !== null && current.memoizedState !== null;
18360
18361 if (current === null) {
18362 // In cases where we didn't find a suitable hydration boundary we never
18363 // downgraded this to a DehydratedSuspenseComponent, but we still need to
18364 // pop the hydration state since we might be inside the insertion tree.
18365 popHydrationState(workInProgress);
18366 } else if (!nextDidTimeout && prevDidTimeout) {
18367 // We just switched from the fallback to the normal children. Delete
18368 // the fallback.
18369 // TODO: Would it be better to store the fallback fragment on
18370 var currentFallbackChild = current.child.sibling;
18371 if (currentFallbackChild !== null) {
18372 // Deletions go at the beginning of the return fiber's effect list
18373 var first = workInProgress.firstEffect;
18374 if (first !== null) {
18375 workInProgress.firstEffect = currentFallbackChild;
18376 currentFallbackChild.nextEffect = first;
18377 } else {
18378 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
18379 currentFallbackChild.nextEffect = null;
18380 }
18381 currentFallbackChild.effectTag = Deletion;
18382 }
18383 }
18384
18385 if (supportsPersistence) {
18386 if (nextDidTimeout) {
18387 // If this boundary just timed out, schedule an effect to attach a
18388 // retry listener to the proimse. This flag is also used to hide the
18389 // primary children.
18390 workInProgress.effectTag |= Update;
18391 }
18392 }
18393 if (supportsMutation) {
18394 if (nextDidTimeout || prevDidTimeout) {
18395 // If this boundary just timed out, schedule an effect to attach a
18396 // retry listener to the proimse. This flag is also used to hide the
18397 // primary children. In mutation mode, we also need the flag to
18398 // *unhide* children that were previously hidden, so check if the
18399 // is currently timed out, too.
18400 workInProgress.effectTag |= Update;
18401 }
18402 }
18403 break;
18404 }
18405 case Fragment:
18406 break;
18407 case Mode:
18408 break;
18409 case Profiler:
18410 break;
18411 case HostPortal:
18412 popHostContainer(workInProgress);
18413 updateHostContainer(workInProgress);
18414 break;
18415 case ContextProvider:
18416 // Pop provider fiber
18417 popProvider(workInProgress);
18418 break;
18419 case ContextConsumer:
18420 break;
18421 case MemoComponent:
18422 break;
18423 case IncompleteClassComponent:
18424 {
18425 // Same as class component case. I put it down here so that the tags are
18426 // sequential to ensure this switch is compiled to a jump table.
18427 var _Component = workInProgress.type;
18428 if (isContextProvider(_Component)) {
18429 popContext(workInProgress);
18430 }
18431 break;
18432 }
18433 case DehydratedSuspenseComponent:
18434 {
18435 if (enableSuspenseServerRenderer) {
18436 if (current === null) {
18437 var _wasHydrated2 = popHydrationState(workInProgress);
18438 (function () {
18439 if (!_wasHydrated2) {
18440 {
18441 throw ReactError('A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.');
18442 }
18443 }
18444 })();
18445 skipPastDehydratedSuspenseInstance(workInProgress);
18446 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
18447 // This boundary did not suspend so it's now hydrated.
18448 // To handle any future suspense cases, we're going to now upgrade it
18449 // to a Suspense component. We detach it from the existing current fiber.
18450 current.alternate = null;
18451 workInProgress.alternate = null;
18452 workInProgress.tag = SuspenseComponent;
18453 workInProgress.memoizedState = null;
18454 workInProgress.stateNode = null;
18455 }
18456 }
18457 break;
18458 }
18459 case EventComponent:
18460 {
18461 if (enableEventAPI) {
18462 popHostContext(workInProgress);
18463 var _rootContainerInstance2 = getRootHostContainer();
18464 var responder = workInProgress.type.responder;
18465 // Update the props on the event component state node
18466 workInProgress.stateNode.props = newProps;
18467 handleEventComponent(responder, _rootContainerInstance2, workInProgress);
18468 }
18469 break;
18470 }
18471 case EventTarget:
18472 {
18473 if (enableEventAPI) {
18474 popHostContext(workInProgress);
18475 var _type = workInProgress.type.type;
18476 var node = workInProgress.return;
18477 var parentHostInstance = null;
18478 // Traverse up the fiber tree till we find a host component fiber
18479 while (node !== null) {
18480 if (node.tag === HostComponent) {
18481 parentHostInstance = node.stateNode;
18482 break;
18483 }
18484 node = node.return;
18485 }
18486
18487 }
18488 break;
18489 }
18490 default:
18491 (function () {
18492 {
18493 {
18494 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
18495 }
18496 }
18497 })();
18498 }
18499
18500 return null;
18501}
18502
18503function shouldCaptureSuspense(workInProgress) {
18504 // In order to capture, the Suspense component must have a fallback prop.
18505 if (workInProgress.memoizedProps.fallback === undefined) {
18506 return false;
18507 }
18508 // If it was the primary children that just suspended, capture and render the
18509 // fallback. Otherwise, don't capture and bubble to the next boundary.
18510 var nextState = workInProgress.memoizedState;
18511 return nextState === null;
18512}
18513
18514// This module is forked in different environments.
18515// By default, return `true` to log errors to the console.
18516// Forks can return `false` if this isn't desirable.
18517function showErrorDialog(capturedError) {
18518 return true;
18519}
18520
18521function logCapturedError(capturedError) {
18522 var logError = showErrorDialog(capturedError);
18523
18524 // Allow injected showErrorDialog() to prevent default console.error logging.
18525 // This enables renderers like ReactNative to better manage redbox behavior.
18526 if (logError === false) {
18527 return;
18528 }
18529
18530 var error = capturedError.error;
18531 {
18532 var componentName = capturedError.componentName,
18533 componentStack = capturedError.componentStack,
18534 errorBoundaryName = capturedError.errorBoundaryName,
18535 errorBoundaryFound = capturedError.errorBoundaryFound,
18536 willRetry = capturedError.willRetry;
18537
18538 // Browsers support silencing uncaught errors by calling
18539 // `preventDefault()` in window `error` handler.
18540 // We record this information as an expando on the error.
18541
18542 if (error != null && error._suppressLogging) {
18543 if (errorBoundaryFound && willRetry) {
18544 // The error is recoverable and was silenced.
18545 // Ignore it and don't print the stack addendum.
18546 // This is handy for testing error boundaries without noise.
18547 return;
18548 }
18549 // The error is fatal. Since the silencing might have
18550 // been accidental, we'll surface it anyway.
18551 // However, the browser would have silenced the original error
18552 // so we'll print it first, and then print the stack addendum.
18553 console.error(error);
18554 // For a more detailed description of this block, see:
18555 // https://github.com/facebook/react/pull/13384
18556 }
18557
18558 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
18559
18560 var errorBoundaryMessage = void 0;
18561 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
18562 if (errorBoundaryFound && errorBoundaryName) {
18563 if (willRetry) {
18564 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
18565 } else {
18566 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
18567 }
18568 } else {
18569 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.';
18570 }
18571 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
18572
18573 // In development, we provide our own message with just the component stack.
18574 // We don't include the original error message and JS stack because the browser
18575 // has already printed it. Even if the application swallows the error, it is still
18576 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
18577 console.error(combinedMessage);
18578 }
18579}
18580
18581var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
18582{
18583 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
18584}
18585
18586var PossiblyWeakSet$2 = typeof WeakSet === 'function' ? WeakSet : Set;
18587
18588function logError(boundary, errorInfo) {
18589 var source = errorInfo.source;
18590 var stack = errorInfo.stack;
18591 if (stack === null && source !== null) {
18592 stack = getStackByFiberInDevAndProd(source);
18593 }
18594
18595 var capturedError = {
18596 componentName: source !== null ? getComponentName(source.type) : null,
18597 componentStack: stack !== null ? stack : '',
18598 error: errorInfo.value,
18599 errorBoundary: null,
18600 errorBoundaryName: null,
18601 errorBoundaryFound: false,
18602 willRetry: false
18603 };
18604
18605 if (boundary !== null && boundary.tag === ClassComponent) {
18606 capturedError.errorBoundary = boundary.stateNode;
18607 capturedError.errorBoundaryName = getComponentName(boundary.type);
18608 capturedError.errorBoundaryFound = true;
18609 capturedError.willRetry = true;
18610 }
18611
18612 try {
18613 logCapturedError(capturedError);
18614 } catch (e) {
18615 // This method must not throw, or React internal state will get messed up.
18616 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
18617 // we want to report this error outside of the normal stack as a last resort.
18618 // https://github.com/facebook/react/issues/13188
18619 setTimeout(function () {
18620 throw e;
18621 });
18622 }
18623}
18624
18625var callComponentWillUnmountWithTimer = function (current$$1, instance) {
18626 startPhaseTimer(current$$1, 'componentWillUnmount');
18627 instance.props = current$$1.memoizedProps;
18628 instance.state = current$$1.memoizedState;
18629 instance.componentWillUnmount();
18630 stopPhaseTimer();
18631};
18632
18633// Capture errors so they don't interrupt unmounting.
18634function safelyCallComponentWillUnmount(current$$1, instance) {
18635 {
18636 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
18637 if (hasCaughtError()) {
18638 var unmountError = clearCaughtError();
18639 captureCommitPhaseError$$1(current$$1, unmountError);
18640 }
18641 }
18642}
18643
18644function safelyDetachRef(current$$1) {
18645 var ref = current$$1.ref;
18646 if (ref !== null) {
18647 if (typeof ref === 'function') {
18648 {
18649 invokeGuardedCallback(null, ref, null, null);
18650 if (hasCaughtError()) {
18651 var refError = clearCaughtError();
18652 captureCommitPhaseError$$1(current$$1, refError);
18653 }
18654 }
18655 } else {
18656 ref.current = null;
18657 }
18658 }
18659}
18660
18661function safelyCallDestroy(current$$1, destroy) {
18662 {
18663 invokeGuardedCallback(null, destroy, null);
18664 if (hasCaughtError()) {
18665 var error = clearCaughtError();
18666 captureCommitPhaseError$$1(current$$1, error);
18667 }
18668 }
18669}
18670
18671function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
18672 switch (finishedWork.tag) {
18673 case FunctionComponent:
18674 case ForwardRef:
18675 case SimpleMemoComponent:
18676 {
18677 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
18678 return;
18679 }
18680 case ClassComponent:
18681 {
18682 if (finishedWork.effectTag & Snapshot) {
18683 if (current$$1 !== null) {
18684 var prevProps = current$$1.memoizedProps;
18685 var prevState = current$$1.memoizedState;
18686 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
18687 var instance = finishedWork.stateNode;
18688 // We could update instance props and state here,
18689 // but instead we rely on them being set during last render.
18690 // TODO: revisit this when we implement resuming.
18691 {
18692 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18693 !(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;
18694 !(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;
18695 }
18696 }
18697 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
18698 {
18699 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
18700 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
18701 didWarnSet.add(finishedWork.type);
18702 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
18703 }
18704 }
18705 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
18706 stopPhaseTimer();
18707 }
18708 }
18709 return;
18710 }
18711 case HostRoot:
18712 case HostComponent:
18713 case HostText:
18714 case HostPortal:
18715 case IncompleteClassComponent:
18716 // Nothing to do for these component types
18717 return;
18718 default:
18719 {
18720 (function () {
18721 {
18722 {
18723 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.');
18724 }
18725 }
18726 })();
18727 }
18728 }
18729}
18730
18731function commitHookEffectList(unmountTag, mountTag, finishedWork) {
18732 var updateQueue = finishedWork.updateQueue;
18733 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
18734 if (lastEffect !== null) {
18735 var firstEffect = lastEffect.next;
18736 var effect = firstEffect;
18737 do {
18738 if ((effect.tag & unmountTag) !== NoEffect$1) {
18739 // Unmount
18740 var destroy = effect.destroy;
18741 effect.destroy = undefined;
18742 if (destroy !== undefined) {
18743 destroy();
18744 }
18745 }
18746 if ((effect.tag & mountTag) !== NoEffect$1) {
18747 // Mount
18748 var create = effect.create;
18749 effect.destroy = create();
18750
18751 {
18752 var _destroy = effect.destroy;
18753 if (_destroy !== undefined && typeof _destroy !== 'function') {
18754 var addendum = void 0;
18755 if (_destroy === null) {
18756 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
18757 } else if (typeof _destroy.then === 'function') {
18758 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';
18759 } else {
18760 addendum = ' You returned: ' + _destroy;
18761 }
18762 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
18763 }
18764 }
18765 }
18766 effect = effect.next;
18767 } while (effect !== firstEffect);
18768 }
18769}
18770
18771function commitPassiveHookEffects(finishedWork) {
18772 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
18773 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
18774}
18775
18776function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
18777 switch (finishedWork.tag) {
18778 case FunctionComponent:
18779 case ForwardRef:
18780 case SimpleMemoComponent:
18781 {
18782 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
18783 break;
18784 }
18785 case ClassComponent:
18786 {
18787 var instance = finishedWork.stateNode;
18788 if (finishedWork.effectTag & Update) {
18789 if (current$$1 === null) {
18790 startPhaseTimer(finishedWork, 'componentDidMount');
18791 // We could update instance props and state here,
18792 // but instead we rely on them being set during last render.
18793 // TODO: revisit this when we implement resuming.
18794 {
18795 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18796 !(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;
18797 !(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;
18798 }
18799 }
18800 instance.componentDidMount();
18801 stopPhaseTimer();
18802 } else {
18803 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
18804 var prevState = current$$1.memoizedState;
18805 startPhaseTimer(finishedWork, 'componentDidUpdate');
18806 // We could update instance props and state here,
18807 // but instead we rely on them being set during last render.
18808 // TODO: revisit this when we implement resuming.
18809 {
18810 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18811 !(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;
18812 !(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;
18813 }
18814 }
18815 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
18816 stopPhaseTimer();
18817 }
18818 }
18819 var updateQueue = finishedWork.updateQueue;
18820 if (updateQueue !== null) {
18821 {
18822 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
18823 !(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;
18824 !(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;
18825 }
18826 }
18827 // We could update instance props and state here,
18828 // but instead we rely on them being set during last render.
18829 // TODO: revisit this when we implement resuming.
18830 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
18831 }
18832 return;
18833 }
18834 case HostRoot:
18835 {
18836 var _updateQueue = finishedWork.updateQueue;
18837 if (_updateQueue !== null) {
18838 var _instance = null;
18839 if (finishedWork.child !== null) {
18840 switch (finishedWork.child.tag) {
18841 case HostComponent:
18842 _instance = getPublicInstance(finishedWork.child.stateNode);
18843 break;
18844 case ClassComponent:
18845 _instance = finishedWork.child.stateNode;
18846 break;
18847 }
18848 }
18849 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
18850 }
18851 return;
18852 }
18853 case HostComponent:
18854 {
18855 var _instance2 = finishedWork.stateNode;
18856
18857 // Renderers may schedule work to be done after host components are mounted
18858 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
18859 // These effects should only be committed when components are first mounted,
18860 // aka when there is no current/alternate.
18861 if (current$$1 === null && finishedWork.effectTag & Update) {
18862 var type = finishedWork.type;
18863 var props = finishedWork.memoizedProps;
18864 commitMount(_instance2, type, props, finishedWork);
18865 }
18866
18867 return;
18868 }
18869 case HostText:
18870 {
18871 // We have no life-cycles associated with text.
18872 return;
18873 }
18874 case HostPortal:
18875 {
18876 // We have no life-cycles associated with portals.
18877 return;
18878 }
18879 case Profiler:
18880 {
18881 if (enableProfilerTimer) {
18882 var onRender = finishedWork.memoizedProps.onRender;
18883
18884 if (enableSchedulerTracing) {
18885 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
18886 } else {
18887 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
18888 }
18889 }
18890 return;
18891 }
18892 case SuspenseComponent:
18893 case IncompleteClassComponent:
18894 break;
18895 default:
18896 {
18897 (function () {
18898 {
18899 {
18900 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.');
18901 }
18902 }
18903 })();
18904 }
18905 }
18906}
18907
18908function hideOrUnhideAllChildren(finishedWork, isHidden) {
18909 if (supportsMutation) {
18910 // We only have the top Fiber that was inserted but we need to recurse down its
18911 var node = finishedWork;
18912 while (true) {
18913 if (node.tag === HostComponent) {
18914 var instance = node.stateNode;
18915 if (isHidden) {
18916 hideInstance(instance);
18917 } else {
18918 unhideInstance(node.stateNode, node.memoizedProps);
18919 }
18920 } else if (node.tag === HostText) {
18921 var _instance3 = node.stateNode;
18922 if (isHidden) {
18923 hideTextInstance(_instance3);
18924 } else {
18925 unhideTextInstance(_instance3, node.memoizedProps);
18926 }
18927 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
18928 // Found a nested Suspense component that timed out. Skip over the
18929 var fallbackChildFragment = node.child.sibling;
18930 fallbackChildFragment.return = node;
18931 node = fallbackChildFragment;
18932 continue;
18933 } else if (node.child !== null) {
18934 node.child.return = node;
18935 node = node.child;
18936 continue;
18937 }
18938 if (node === finishedWork) {
18939 return;
18940 }
18941 while (node.sibling === null) {
18942 if (node.return === null || node.return === finishedWork) {
18943 return;
18944 }
18945 node = node.return;
18946 }
18947 node.sibling.return = node.return;
18948 node = node.sibling;
18949 }
18950 }
18951}
18952
18953function commitAttachRef(finishedWork) {
18954 var ref = finishedWork.ref;
18955 if (ref !== null) {
18956 var instance = finishedWork.stateNode;
18957 var instanceToUse = void 0;
18958 switch (finishedWork.tag) {
18959 case HostComponent:
18960 instanceToUse = getPublicInstance(instance);
18961 break;
18962 default:
18963 instanceToUse = instance;
18964 }
18965 if (typeof ref === 'function') {
18966 ref(instanceToUse);
18967 } else {
18968 {
18969 if (!ref.hasOwnProperty('current')) {
18970 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
18971 }
18972 }
18973
18974 ref.current = instanceToUse;
18975 }
18976 }
18977}
18978
18979function commitDetachRef(current$$1) {
18980 var currentRef = current$$1.ref;
18981 if (currentRef !== null) {
18982 if (typeof currentRef === 'function') {
18983 currentRef(null);
18984 } else {
18985 currentRef.current = null;
18986 }
18987 }
18988}
18989
18990// User-originating errors (lifecycles and refs) should not interrupt
18991// deletion, so don't let them throw. Host-originating errors should
18992// interrupt deletion, so it's okay
18993function commitUnmount(current$$1) {
18994 onCommitUnmount(current$$1);
18995
18996 switch (current$$1.tag) {
18997 case FunctionComponent:
18998 case ForwardRef:
18999 case MemoComponent:
19000 case SimpleMemoComponent:
19001 {
19002 var updateQueue = current$$1.updateQueue;
19003 if (updateQueue !== null) {
19004 var lastEffect = updateQueue.lastEffect;
19005 if (lastEffect !== null) {
19006 var firstEffect = lastEffect.next;
19007 var effect = firstEffect;
19008 do {
19009 var destroy = effect.destroy;
19010 if (destroy !== undefined) {
19011 safelyCallDestroy(current$$1, destroy);
19012 }
19013 effect = effect.next;
19014 } while (effect !== firstEffect);
19015 }
19016 }
19017 break;
19018 }
19019 case ClassComponent:
19020 {
19021 safelyDetachRef(current$$1);
19022 var instance = current$$1.stateNode;
19023 if (typeof instance.componentWillUnmount === 'function') {
19024 safelyCallComponentWillUnmount(current$$1, instance);
19025 }
19026 return;
19027 }
19028 case HostComponent:
19029 {
19030 safelyDetachRef(current$$1);
19031 return;
19032 }
19033 case HostPortal:
19034 {
19035 // TODO: this is recursive.
19036 // We are also not using this parent because
19037 // the portal will get pushed immediately.
19038 if (supportsMutation) {
19039 unmountHostComponents(current$$1);
19040 } else if (supportsPersistence) {
19041 emptyPortalContainer(current$$1);
19042 }
19043 return;
19044 }
19045 }
19046}
19047
19048function commitNestedUnmounts(root) {
19049 // While we're inside a removed host node we don't want to call
19050 // removeChild on the inner nodes because they're removed by the top
19051 // call anyway. We also want to call componentWillUnmount on all
19052 // composites before this host node is removed from the tree. Therefore
19053 var node = root;
19054 while (true) {
19055 commitUnmount(node);
19056 // Visit children because they may contain more composite or host nodes.
19057 // Skip portals because commitUnmount() currently visits them recursively.
19058 if (node.child !== null && (
19059 // If we use mutation we drill down into portals using commitUnmount above.
19060 // If we don't use mutation we drill down into portals here instead.
19061 !supportsMutation || node.tag !== HostPortal)) {
19062 node.child.return = node;
19063 node = node.child;
19064 continue;
19065 }
19066 if (node === root) {
19067 return;
19068 }
19069 while (node.sibling === null) {
19070 if (node.return === null || node.return === root) {
19071 return;
19072 }
19073 node = node.return;
19074 }
19075 node.sibling.return = node.return;
19076 node = node.sibling;
19077 }
19078}
19079
19080function detachFiber(current$$1) {
19081 // Cut off the return pointers to disconnect it from the tree. Ideally, we
19082 // should clear the child pointer of the parent alternate to let this
19083 // get GC:ed but we don't know which for sure which parent is the current
19084 // one so we'll settle for GC:ing the subtree of this child. This child
19085 // itself will be GC:ed when the parent updates the next time.
19086 current$$1.return = null;
19087 current$$1.child = null;
19088 current$$1.memoizedState = null;
19089 current$$1.updateQueue = null;
19090 var alternate = current$$1.alternate;
19091 if (alternate !== null) {
19092 alternate.return = null;
19093 alternate.child = null;
19094 alternate.memoizedState = null;
19095 alternate.updateQueue = null;
19096 }
19097}
19098
19099function emptyPortalContainer(current$$1) {
19100 if (!supportsPersistence) {
19101 return;
19102 }
19103
19104 var portal = current$$1.stateNode;
19105 var containerInfo = portal.containerInfo;
19106
19107 var emptyChildSet = createContainerChildSet(containerInfo);
19108 replaceContainerChildren(containerInfo, emptyChildSet);
19109}
19110
19111function commitContainer(finishedWork) {
19112 if (!supportsPersistence) {
19113 return;
19114 }
19115
19116 switch (finishedWork.tag) {
19117 case ClassComponent:
19118 case HostComponent:
19119 case HostText:
19120 {
19121 return;
19122 }
19123 case HostRoot:
19124 case HostPortal:
19125 {
19126 var portalOrRoot = finishedWork.stateNode;
19127 var containerInfo = portalOrRoot.containerInfo,
19128 _pendingChildren = portalOrRoot.pendingChildren;
19129
19130 replaceContainerChildren(containerInfo, _pendingChildren);
19131 return;
19132 }
19133 default:
19134 {
19135 (function () {
19136 {
19137 {
19138 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.');
19139 }
19140 }
19141 })();
19142 }
19143 }
19144}
19145
19146function getHostParentFiber(fiber) {
19147 var parent = fiber.return;
19148 while (parent !== null) {
19149 if (isHostParent(parent)) {
19150 return parent;
19151 }
19152 parent = parent.return;
19153 }
19154 (function () {
19155 {
19156 {
19157 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
19158 }
19159 }
19160 })();
19161}
19162
19163function isHostParent(fiber) {
19164 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
19165}
19166
19167function getHostSibling(fiber) {
19168 // We're going to search forward into the tree until we find a sibling host
19169 // node. Unfortunately, if multiple insertions are done in a row we have to
19170 // search past them. This leads to exponential search for the next sibling.
19171 var node = fiber;
19172 siblings: while (true) {
19173 // If we didn't find anything, let's try the next sibling.
19174 while (node.sibling === null) {
19175 if (node.return === null || isHostParent(node.return)) {
19176 // If we pop out of the root or hit the parent the fiber we are the
19177 // last sibling.
19178 return null;
19179 }
19180 node = node.return;
19181 }
19182 node.sibling.return = node.return;
19183 node = node.sibling;
19184 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
19185 // If it is not host node and, we might have a host node inside it.
19186 // Try to search down until we find one.
19187 if (node.effectTag & Placement) {
19188 // If we don't have a child, try the siblings instead.
19189 continue siblings;
19190 }
19191 // If we don't have a child, try the siblings instead.
19192 // We also skip portals because they are not part of this host tree.
19193 if (node.child === null || node.tag === HostPortal) {
19194 continue siblings;
19195 } else {
19196 node.child.return = node;
19197 node = node.child;
19198 }
19199 }
19200 // Check if this host node is stable or about to be placed.
19201 if (!(node.effectTag & Placement)) {
19202 // Found it!
19203 return node.stateNode;
19204 }
19205 }
19206}
19207
19208function commitPlacement(finishedWork) {
19209 if (!supportsMutation) {
19210 return;
19211 }
19212
19213 // Recursively insert all host nodes into the parent.
19214 var parentFiber = getHostParentFiber(finishedWork);
19215
19216 // Note: these two variables *must* always be updated together.
19217 var parent = void 0;
19218 var isContainer = void 0;
19219
19220 switch (parentFiber.tag) {
19221 case HostComponent:
19222 parent = parentFiber.stateNode;
19223 isContainer = false;
19224 break;
19225 case HostRoot:
19226 parent = parentFiber.stateNode.containerInfo;
19227 isContainer = true;
19228 break;
19229 case HostPortal:
19230 parent = parentFiber.stateNode.containerInfo;
19231 isContainer = true;
19232 break;
19233 default:
19234 (function () {
19235 {
19236 {
19237 throw ReactError('Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
19238 }
19239 }
19240 })();
19241 }
19242 if (parentFiber.effectTag & ContentReset) {
19243 // Reset the text content of the parent before doing any insertions
19244 resetTextContent(parent);
19245 // Clear ContentReset from the effect tag
19246 parentFiber.effectTag &= ~ContentReset;
19247 }
19248
19249 var before = getHostSibling(finishedWork);
19250 // We only have the top Fiber that was inserted but we need to recurse down its
19251 // children to find all the terminal nodes.
19252 var node = finishedWork;
19253 while (true) {
19254 if (node.tag === HostComponent || node.tag === HostText) {
19255 if (before) {
19256 if (isContainer) {
19257 insertInContainerBefore(parent, node.stateNode, before);
19258 } else {
19259 insertBefore(parent, node.stateNode, before);
19260 }
19261 } else {
19262 if (isContainer) {
19263 appendChildToContainer(parent, node.stateNode);
19264 } else {
19265 appendChild(parent, node.stateNode);
19266 }
19267 }
19268 } else if (node.tag === HostPortal) {
19269 // If the insertion itself is a portal, then we don't want to traverse
19270 // down its children. Instead, we'll get insertions from each child in
19271 // the portal directly.
19272 } else if (node.child !== null) {
19273 node.child.return = node;
19274 node = node.child;
19275 continue;
19276 }
19277 if (node === finishedWork) {
19278 return;
19279 }
19280 while (node.sibling === null) {
19281 if (node.return === null || node.return === finishedWork) {
19282 return;
19283 }
19284 node = node.return;
19285 }
19286 node.sibling.return = node.return;
19287 node = node.sibling;
19288 }
19289}
19290
19291function unmountHostComponents(current$$1) {
19292 // We only have the top Fiber that was deleted but we need to recurse down its
19293 var node = current$$1;
19294
19295 // Each iteration, currentParent is populated with node's host parent if not
19296 // currentParentIsValid.
19297 var currentParentIsValid = false;
19298
19299 // Note: these two variables *must* always be updated together.
19300 var currentParent = void 0;
19301 var currentParentIsContainer = void 0;
19302
19303 while (true) {
19304 if (!currentParentIsValid) {
19305 var parent = node.return;
19306 findParent: while (true) {
19307 (function () {
19308 if (!(parent !== null)) {
19309 {
19310 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
19311 }
19312 }
19313 })();
19314 switch (parent.tag) {
19315 case HostComponent:
19316 currentParent = parent.stateNode;
19317 currentParentIsContainer = false;
19318 break findParent;
19319 case HostRoot:
19320 currentParent = parent.stateNode.containerInfo;
19321 currentParentIsContainer = true;
19322 break findParent;
19323 case HostPortal:
19324 currentParent = parent.stateNode.containerInfo;
19325 currentParentIsContainer = true;
19326 break findParent;
19327 }
19328 parent = parent.return;
19329 }
19330 currentParentIsValid = true;
19331 }
19332
19333 if (node.tag === HostComponent || node.tag === HostText) {
19334 commitNestedUnmounts(node);
19335 // After all the children have unmounted, it is now safe to remove the
19336 // node from the tree.
19337 if (currentParentIsContainer) {
19338 removeChildFromContainer(currentParent, node.stateNode);
19339 } else {
19340 removeChild(currentParent, node.stateNode);
19341 }
19342 // Don't visit children because we already visited them.
19343 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
19344 // Delete the dehydrated suspense boundary and all of its content.
19345 if (currentParentIsContainer) {
19346 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
19347 } else {
19348 clearSuspenseBoundary(currentParent, node.stateNode);
19349 }
19350 } else if (node.tag === HostPortal) {
19351 if (node.child !== null) {
19352 // When we go into a portal, it becomes the parent to remove from.
19353 // We will reassign it back when we pop the portal on the way up.
19354 currentParent = node.stateNode.containerInfo;
19355 currentParentIsContainer = true;
19356 // Visit children because portals might contain host components.
19357 node.child.return = node;
19358 node = node.child;
19359 continue;
19360 }
19361 } else {
19362 commitUnmount(node);
19363 // Visit children because we may find more host components below.
19364 if (node.child !== null) {
19365 node.child.return = node;
19366 node = node.child;
19367 continue;
19368 }
19369 }
19370 if (node === current$$1) {
19371 return;
19372 }
19373 while (node.sibling === null) {
19374 if (node.return === null || node.return === current$$1) {
19375 return;
19376 }
19377 node = node.return;
19378 if (node.tag === HostPortal) {
19379 // When we go out of the portal, we need to restore the parent.
19380 // Since we don't keep a stack of them, we will search for it.
19381 currentParentIsValid = false;
19382 }
19383 }
19384 node.sibling.return = node.return;
19385 node = node.sibling;
19386 }
19387}
19388
19389function commitDeletion(current$$1) {
19390 if (supportsMutation) {
19391 // Recursively delete all host nodes from the parent.
19392 // Detach refs and call componentWillUnmount() on the whole subtree.
19393 unmountHostComponents(current$$1);
19394 } else {
19395 // Detach refs and call componentWillUnmount() on the whole subtree.
19396 commitNestedUnmounts(current$$1);
19397 }
19398 detachFiber(current$$1);
19399}
19400
19401function commitWork(current$$1, finishedWork) {
19402 if (!supportsMutation) {
19403 switch (finishedWork.tag) {
19404 case FunctionComponent:
19405 case ForwardRef:
19406 case MemoComponent:
19407 case SimpleMemoComponent:
19408 {
19409 // Note: We currently never use MountMutation, but useLayout uses
19410 // UnmountMutation.
19411 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
19412 return;
19413 }
19414 case Profiler:
19415 {
19416 return;
19417 }
19418 case SuspenseComponent:
19419 {
19420 commitSuspenseComponent(finishedWork);
19421 return;
19422 }
19423 }
19424
19425 commitContainer(finishedWork);
19426 return;
19427 }
19428
19429 switch (finishedWork.tag) {
19430 case FunctionComponent:
19431 case ForwardRef:
19432 case MemoComponent:
19433 case SimpleMemoComponent:
19434 {
19435 // Note: We currently never use MountMutation, but useLayout uses
19436 // UnmountMutation.
19437 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
19438 return;
19439 }
19440 case ClassComponent:
19441 {
19442 return;
19443 }
19444 case HostComponent:
19445 {
19446 var instance = finishedWork.stateNode;
19447 if (instance != null) {
19448 // Commit the work prepared earlier.
19449 var newProps = finishedWork.memoizedProps;
19450 // For hydration we reuse the update path but we treat the oldProps
19451 // as the newProps. The updatePayload will contain the real change in
19452 // this case.
19453 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
19454 var type = finishedWork.type;
19455 // TODO: Type the updateQueue to be specific to host components.
19456 var updatePayload = finishedWork.updateQueue;
19457 finishedWork.updateQueue = null;
19458 if (updatePayload !== null) {
19459 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
19460 }
19461 }
19462 return;
19463 }
19464 case HostText:
19465 {
19466 (function () {
19467 if (!(finishedWork.stateNode !== null)) {
19468 {
19469 throw ReactError('This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.');
19470 }
19471 }
19472 })();
19473 var textInstance = finishedWork.stateNode;
19474 var newText = finishedWork.memoizedProps;
19475 // For hydration we reuse the update path but we treat the oldProps
19476 // as the newProps. The updatePayload will contain the real change in
19477 // this case.
19478 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
19479 commitTextUpdate(textInstance, oldText, newText);
19480 return;
19481 }
19482 case HostRoot:
19483 {
19484 return;
19485 }
19486 case Profiler:
19487 {
19488 return;
19489 }
19490 case SuspenseComponent:
19491 {
19492 commitSuspenseComponent(finishedWork);
19493 return;
19494 }
19495 case IncompleteClassComponent:
19496 {
19497 return;
19498 }
19499 default:
19500 {
19501 (function () {
19502 {
19503 {
19504 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.');
19505 }
19506 }
19507 })();
19508 }
19509 }
19510}
19511
19512function commitSuspenseComponent(finishedWork) {
19513 var newState = finishedWork.memoizedState;
19514
19515 var newDidTimeout = void 0;
19516 var primaryChildParent = finishedWork;
19517 if (newState === null) {
19518 newDidTimeout = false;
19519 } else {
19520 newDidTimeout = true;
19521 primaryChildParent = finishedWork.child;
19522 if (newState.timedOutAt === NoWork) {
19523 // If the children had not already timed out, record the time.
19524 // This is used to compute the elapsed time during subsequent
19525 // attempts to render the children.
19526 newState.timedOutAt = requestCurrentTime$$1();
19527 }
19528 }
19529
19530 if (supportsMutation && primaryChildParent !== null) {
19531 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
19532 }
19533
19534 // If this boundary just timed out, then it will have a set of thenables.
19535 // For each thenable, attach a listener so that when it resolves, React
19536 // attempts to re-render the boundary in the primary (pre-timeout) state.
19537 var thenables = finishedWork.updateQueue;
19538 if (thenables !== null) {
19539 finishedWork.updateQueue = null;
19540 var retryCache = finishedWork.stateNode;
19541 if (retryCache === null) {
19542 retryCache = finishedWork.stateNode = new PossiblyWeakSet$2();
19543 }
19544 thenables.forEach(function (thenable) {
19545 // Memoize using the boundary fiber to prevent redundant listeners.
19546 var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable);
19547 if (enableSchedulerTracing) {
19548 retry = unstable_wrap(retry);
19549 }
19550 if (!retryCache.has(thenable)) {
19551 retryCache.add(thenable);
19552 thenable.then(retry, retry);
19553 }
19554 });
19555 }
19556}
19557
19558function commitResetTextContent(current$$1) {
19559 if (!supportsMutation) {
19560 return;
19561 }
19562 resetTextContent(current$$1.stateNode);
19563}
19564
19565var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
19566var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
19567
19568function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
19569 var update = createUpdate(expirationTime);
19570 // Unmount the root by rendering null.
19571 update.tag = CaptureUpdate;
19572 // Caution: React DevTools currently depends on this property
19573 // being called "element".
19574 update.payload = { element: null };
19575 var error = errorInfo.value;
19576 update.callback = function () {
19577 onUncaughtError$$1(error);
19578 logError(fiber, errorInfo);
19579 };
19580 return update;
19581}
19582
19583function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
19584 var update = createUpdate(expirationTime);
19585 update.tag = CaptureUpdate;
19586 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
19587 if (typeof getDerivedStateFromError === 'function') {
19588 var error = errorInfo.value;
19589 update.payload = function () {
19590 return getDerivedStateFromError(error);
19591 };
19592 }
19593
19594 var inst = fiber.stateNode;
19595 if (inst !== null && typeof inst.componentDidCatch === 'function') {
19596 update.callback = function callback() {
19597 if (typeof getDerivedStateFromError !== 'function') {
19598 // To preserve the preexisting retry behavior of error boundaries,
19599 // we keep track of which ones already failed during this batch.
19600 // This gets reset before we yield back to the browser.
19601 // TODO: Warn in strict mode if getDerivedStateFromError is
19602 // not defined.
19603 markLegacyErrorBoundaryAsFailed$$1(this);
19604 }
19605 var error = errorInfo.value;
19606 var stack = errorInfo.stack;
19607 logError(fiber, errorInfo);
19608 this.componentDidCatch(error, {
19609 componentStack: stack !== null ? stack : ''
19610 });
19611 {
19612 if (typeof getDerivedStateFromError !== 'function') {
19613 // If componentDidCatch is the only error boundary method defined,
19614 // then it needs to call setState to recover from errors.
19615 // If no state update is scheduled then the boundary will swallow the error.
19616 !(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;
19617 }
19618 }
19619 };
19620 }
19621 return update;
19622}
19623
19624function attachPingListener(root, renderExpirationTime, thenable) {
19625 // Attach a listener to the promise to "ping" the root and retry. But
19626 // only if one does not already exist for the current render expiration
19627 // time (which acts like a "thread ID" here).
19628 var pingCache = root.pingCache;
19629 var threadIDs = void 0;
19630 if (pingCache === null) {
19631 pingCache = root.pingCache = new PossiblyWeakMap$1();
19632 threadIDs = new Set();
19633 pingCache.set(thenable, threadIDs);
19634 } else {
19635 threadIDs = pingCache.get(thenable);
19636 if (threadIDs === undefined) {
19637 threadIDs = new Set();
19638 pingCache.set(thenable, threadIDs);
19639 }
19640 }
19641 if (!threadIDs.has(renderExpirationTime)) {
19642 // Memoize using the thread ID to prevent redundant listeners.
19643 threadIDs.add(renderExpirationTime);
19644 var ping = pingSuspendedRoot$$1.bind(null, root, thenable, renderExpirationTime);
19645 if (enableSchedulerTracing) {
19646 ping = unstable_wrap(ping);
19647 }
19648 thenable.then(ping, ping);
19649 }
19650}
19651
19652function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
19653 // The source fiber did not complete.
19654 sourceFiber.effectTag |= Incomplete;
19655 // Its effect list is no longer valid.
19656 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
19657
19658 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
19659 // This is a thenable.
19660 var thenable = value;
19661
19662 // Find the earliest timeout threshold of all the placeholders in the
19663 // ancestor path. We could avoid this traversal by storing the thresholds on
19664 // the stack, but we choose not to because we only hit this path if we're
19665 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
19666 // the non-IO- bound case.
19667 var _workInProgress = returnFiber;
19668 var earliestTimeoutMs = -1;
19669 var startTimeMs = -1;
19670 do {
19671 if (_workInProgress.tag === SuspenseComponent) {
19672 var current$$1 = _workInProgress.alternate;
19673 if (current$$1 !== null) {
19674 var currentState = current$$1.memoizedState;
19675 if (currentState !== null) {
19676 // Reached a boundary that already timed out. Do not search
19677 // any further.
19678 var timedOutAt = currentState.timedOutAt;
19679 startTimeMs = expirationTimeToMs(timedOutAt);
19680 // Do not search any further.
19681 break;
19682 }
19683 }
19684 var defaultSuspenseTimeout = 150;
19685 if (earliestTimeoutMs === -1 || defaultSuspenseTimeout < earliestTimeoutMs) {
19686 earliestTimeoutMs = defaultSuspenseTimeout;
19687 }
19688 }
19689 // If there is a DehydratedSuspenseComponent we don't have to do anything because
19690 // if something suspends inside it, we will simply leave that as dehydrated. It
19691 // will never timeout.
19692 _workInProgress = _workInProgress.return;
19693 } while (_workInProgress !== null);
19694
19695 // Schedule the nearest Suspense to re-render the timed out view.
19696 _workInProgress = returnFiber;
19697 do {
19698 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
19699 // Found the nearest boundary.
19700
19701 // Stash the promise on the boundary fiber. If the boundary times out, we'll
19702 var thenables = _workInProgress.updateQueue;
19703 if (thenables === null) {
19704 var updateQueue = new Set();
19705 updateQueue.add(thenable);
19706 _workInProgress.updateQueue = updateQueue;
19707 } else {
19708 thenables.add(thenable);
19709 }
19710
19711 // If the boundary is outside of concurrent mode, we should *not*
19712 // suspend the commit. Pretend as if the suspended component rendered
19713 // null and keep rendering. In the commit phase, we'll schedule a
19714 // subsequent synchronous update to re-render the Suspense.
19715 //
19716 // Note: It doesn't matter whether the component that suspended was
19717 // inside a concurrent mode tree. If the Suspense is outside of it, we
19718 // should *not* suspend the commit.
19719 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
19720 _workInProgress.effectTag |= DidCapture;
19721
19722 // We're going to commit this fiber even though it didn't complete.
19723 // But we shouldn't call any lifecycle methods or callbacks. Remove
19724 // all lifecycle effect tags.
19725 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
19726
19727 if (sourceFiber.tag === ClassComponent) {
19728 var currentSourceFiber = sourceFiber.alternate;
19729 if (currentSourceFiber === null) {
19730 // This is a new mount. Change the tag so it's not mistaken for a
19731 // completed class component. For example, we should not call
19732 // componentWillUnmount if it is deleted.
19733 sourceFiber.tag = IncompleteClassComponent;
19734 } else {
19735 // When we try rendering again, we should not reuse the current fiber,
19736 // since it's known to be in an inconsistent state. Use a force updte to
19737 // prevent a bail out.
19738 var update = createUpdate(Sync);
19739 update.tag = ForceUpdate;
19740 enqueueUpdate(sourceFiber, update);
19741 }
19742 }
19743
19744 // The source fiber did not complete. Mark it with Sync priority to
19745 // indicate that it still has pending work.
19746 sourceFiber.expirationTime = Sync;
19747
19748 // Exit without suspending.
19749 return;
19750 }
19751
19752 // Confirmed that the boundary is in a concurrent mode tree. Continue
19753 // with the normal suspend path.
19754
19755 attachPingListener(root, renderExpirationTime, thenable);
19756
19757 var absoluteTimeoutMs = void 0;
19758 if (earliestTimeoutMs === -1) {
19759 // If no explicit threshold is given, default to an arbitrarily large
19760 // value. The actual size doesn't matter because the threshold for the
19761 // whole tree will be clamped to the expiration time.
19762 absoluteTimeoutMs = maxSigned31BitInt;
19763 } else {
19764 if (startTimeMs === -1) {
19765 // This suspend happened outside of any already timed-out
19766 // placeholders. We don't know exactly when the update was
19767 // scheduled, but we can infer an approximate start time based on
19768 // the expiration time and the priority.
19769 startTimeMs = inferStartTimeFromExpirationTime$$1(root, renderExpirationTime);
19770 }
19771 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
19772 }
19773
19774 // Mark the earliest timeout in the suspended fiber's ancestor path.
19775 // After completing the root, we'll take the largest of all the
19776 // suspended fiber's timeouts and use it to compute a timeout for the
19777 // whole tree.
19778 renderDidSuspend$$1(root, absoluteTimeoutMs, renderExpirationTime);
19779
19780 _workInProgress.effectTag |= ShouldCapture;
19781 _workInProgress.expirationTime = renderExpirationTime;
19782 return;
19783 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
19784 attachPingListener(root, renderExpirationTime, thenable);
19785
19786 // Since we already have a current fiber, we can eagerly add a retry listener.
19787 var retryCache = _workInProgress.memoizedState;
19788 if (retryCache === null) {
19789 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet$1();
19790 var _current = _workInProgress.alternate;
19791 (function () {
19792 if (!_current) {
19793 {
19794 throw ReactError('A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.');
19795 }
19796 }
19797 })();
19798 _current.memoizedState = retryCache;
19799 }
19800 // Memoize using the boundary fiber to prevent redundant listeners.
19801 if (!retryCache.has(thenable)) {
19802 retryCache.add(thenable);
19803 var retry = resolveRetryThenable$$1.bind(null, _workInProgress, thenable);
19804 if (enableSchedulerTracing) {
19805 retry = unstable_wrap(retry);
19806 }
19807 thenable.then(retry, retry);
19808 }
19809 _workInProgress.effectTag |= ShouldCapture;
19810 _workInProgress.expirationTime = renderExpirationTime;
19811 return;
19812 }
19813 // This boundary already captured during this render. Continue to the next
19814 // boundary.
19815 _workInProgress = _workInProgress.return;
19816 } while (_workInProgress !== null);
19817 // No boundary was found. Fallthrough to error mode.
19818 // TODO: Use invariant so the message is stripped in prod?
19819 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));
19820 }
19821
19822 // We didn't find a boundary that could handle this type of exception. Start
19823 // over and traverse parent path again, this time treating the exception
19824 // as an error.
19825 renderDidError$$1();
19826 value = createCapturedValue(value, sourceFiber);
19827 var workInProgress = returnFiber;
19828 do {
19829 switch (workInProgress.tag) {
19830 case HostRoot:
19831 {
19832 var _errorInfo = value;
19833 workInProgress.effectTag |= ShouldCapture;
19834 workInProgress.expirationTime = renderExpirationTime;
19835 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
19836 enqueueCapturedUpdate(workInProgress, _update);
19837 return;
19838 }
19839 case ClassComponent:
19840 // Capture and retry
19841 var errorInfo = value;
19842 var ctor = workInProgress.type;
19843 var instance = workInProgress.stateNode;
19844 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$$1(instance))) {
19845 workInProgress.effectTag |= ShouldCapture;
19846 workInProgress.expirationTime = renderExpirationTime;
19847 // Schedule the error boundary to re-render using updated state
19848 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
19849 enqueueCapturedUpdate(workInProgress, _update2);
19850 return;
19851 }
19852 break;
19853 default:
19854 break;
19855 }
19856 workInProgress = workInProgress.return;
19857 } while (workInProgress !== null);
19858}
19859
19860function unwindWork(workInProgress, renderExpirationTime) {
19861 switch (workInProgress.tag) {
19862 case ClassComponent:
19863 {
19864 var Component = workInProgress.type;
19865 if (isContextProvider(Component)) {
19866 popContext(workInProgress);
19867 }
19868 var effectTag = workInProgress.effectTag;
19869 if (effectTag & ShouldCapture) {
19870 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
19871 return workInProgress;
19872 }
19873 return null;
19874 }
19875 case HostRoot:
19876 {
19877 popHostContainer(workInProgress);
19878 popTopLevelContextObject(workInProgress);
19879 var _effectTag = workInProgress.effectTag;
19880 (function () {
19881 if (!((_effectTag & DidCapture) === NoEffect)) {
19882 {
19883 throw ReactError('The root failed to unmount after an error. This is likely a bug in React. Please file an issue.');
19884 }
19885 }
19886 })();
19887 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
19888 return workInProgress;
19889 }
19890 case HostComponent:
19891 {
19892 // TODO: popHydrationState
19893 popHostContext(workInProgress);
19894 return null;
19895 }
19896 case SuspenseComponent:
19897 {
19898 var _effectTag2 = workInProgress.effectTag;
19899 if (_effectTag2 & ShouldCapture) {
19900 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
19901 // Captured a suspense effect. Re-render the boundary.
19902 return workInProgress;
19903 }
19904 return null;
19905 }
19906 case DehydratedSuspenseComponent:
19907 {
19908 if (enableSuspenseServerRenderer) {
19909 // TODO: popHydrationState
19910 var _effectTag3 = workInProgress.effectTag;
19911 if (_effectTag3 & ShouldCapture) {
19912 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
19913 // Captured a suspense effect. Re-render the boundary.
19914 return workInProgress;
19915 }
19916 }
19917 return null;
19918 }
19919 case HostPortal:
19920 popHostContainer(workInProgress);
19921 return null;
19922 case ContextProvider:
19923 popProvider(workInProgress);
19924 return null;
19925 case EventComponent:
19926 case EventTarget:
19927 if (enableEventAPI) {
19928 popHostContext(workInProgress);
19929 }
19930 return null;
19931 default:
19932 return null;
19933 }
19934}
19935
19936function unwindInterruptedWork(interruptedWork) {
19937 switch (interruptedWork.tag) {
19938 case ClassComponent:
19939 {
19940 var childContextTypes = interruptedWork.type.childContextTypes;
19941 if (childContextTypes !== null && childContextTypes !== undefined) {
19942 popContext(interruptedWork);
19943 }
19944 break;
19945 }
19946 case HostRoot:
19947 {
19948 popHostContainer(interruptedWork);
19949 popTopLevelContextObject(interruptedWork);
19950 break;
19951 }
19952 case HostComponent:
19953 {
19954 popHostContext(interruptedWork);
19955 break;
19956 }
19957 case HostPortal:
19958 popHostContainer(interruptedWork);
19959 break;
19960 case ContextProvider:
19961 popProvider(interruptedWork);
19962 break;
19963 default:
19964 break;
19965 }
19966}
19967
19968// Intentionally not named imports because Rollup would use dynamic dispatch for
19969// CommonJS interop named imports.
19970// Intentionally not named imports because Rollup would use dynamic dispatch for
19971// CommonJS interop named imports.
19972var scheduleCallback$1 = unstable_scheduleCallback;
19973var cancelCallback$1 = unstable_cancelCallback;
19974var shouldYield$2 = unstable_shouldYield;
19975var now$2 = unstable_now;
19976var getCurrentPriorityLevel$1 = unstable_getCurrentPriorityLevel;
19977var NormalPriority$1 = unstable_NormalPriority;
19978var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
19979var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
19980var ReactShouldWarnActingUpdates = ReactSharedInternals.ReactShouldWarnActingUpdates;
19981
19982
19983var didWarnAboutStateTransition = void 0;
19984var didWarnSetStateChildContext = void 0;
19985var warnAboutUpdateOnUnmounted = void 0;
19986var warnAboutInvalidUpdates = void 0;
19987
19988if (enableSchedulerTracing) {
19989 // Provide explicit error message when production+profiling bundle of e.g. react-dom
19990 // is used with production (non-profiling) bundle of scheduler/tracing
19991 (function () {
19992 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
19993 {
19994 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');
19995 }
19996 }
19997 })();
19998}
19999
20000{
20001 didWarnAboutStateTransition = false;
20002 didWarnSetStateChildContext = false;
20003 var didWarnStateUpdateForUnmountedComponent = {};
20004
20005 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
20006 // We show the whole stack but dedupe on the top component's name because
20007 // the problematic code almost always lies inside that component.
20008 var componentName = getComponentName(fiber.type) || 'ReactComponent';
20009 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
20010 return;
20011 }
20012 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));
20013 didWarnStateUpdateForUnmountedComponent[componentName] = true;
20014 };
20015
20016 warnAboutInvalidUpdates = function (instance) {
20017 switch (phase) {
20018 case 'getChildContext':
20019 if (didWarnSetStateChildContext) {
20020 return;
20021 }
20022 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
20023 didWarnSetStateChildContext = true;
20024 break;
20025 case 'render':
20026 if (didWarnAboutStateTransition) {
20027 return;
20028 }
20029 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.');
20030 didWarnAboutStateTransition = true;
20031 break;
20032 }
20033 };
20034}
20035
20036// Used to ensure computeUniqueAsyncExpiration is monotonically decreasing.
20037var lastUniqueAsyncExpiration = Sync - 1;
20038
20039// Represents the expiration time that incoming updates should use. (If this
20040// is NoWork, use the default strategy: async updates in async mode, sync
20041// updates in sync mode.)
20042var expirationContext = NoWork;
20043
20044var isWorking = false;
20045
20046// The next work in progress fiber that we're currently working on.
20047var nextUnitOfWork = null;
20048var nextRoot = null;
20049// The time at which we're currently rendering work.
20050var nextRenderExpirationTime = NoWork;
20051var nextLatestAbsoluteTimeoutMs = -1;
20052var nextRenderDidError = false;
20053
20054// The next fiber with an effect that we're currently committing.
20055var nextEffect = null;
20056
20057var isCommitting$1 = false;
20058var rootWithPendingPassiveEffects = null;
20059var passiveEffectCallbackHandle = null;
20060var passiveEffectCallback = null;
20061
20062var legacyErrorBoundariesThatAlreadyFailed = null;
20063
20064// Used for performance tracking.
20065var interruptedBy = null;
20066
20067var stashedWorkInProgressProperties = void 0;
20068var replayUnitOfWork = void 0;
20069var mayReplayFailedUnitOfWork = void 0;
20070var isReplayingFailedUnitOfWork = void 0;
20071var originalReplayError = void 0;
20072var rethrowOriginalError = void 0;
20073if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20074 stashedWorkInProgressProperties = null;
20075 mayReplayFailedUnitOfWork = true;
20076 isReplayingFailedUnitOfWork = false;
20077 originalReplayError = null;
20078 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
20079 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
20080 // Don't replay promises. Treat everything else like an error.
20081 // TODO: Need to figure out a different strategy if/when we add
20082 // support for catching other types.
20083 return;
20084 }
20085
20086 // Restore the original state of the work-in-progress
20087 if (stashedWorkInProgressProperties === null) {
20088 // This should never happen. Don't throw because this code is DEV-only.
20089 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
20090 return;
20091 }
20092 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
20093
20094 switch (failedUnitOfWork.tag) {
20095 case HostRoot:
20096 popHostContainer(failedUnitOfWork);
20097 popTopLevelContextObject(failedUnitOfWork);
20098 break;
20099 case HostComponent:
20100 popHostContext(failedUnitOfWork);
20101 break;
20102 case ClassComponent:
20103 {
20104 var Component = failedUnitOfWork.type;
20105 if (isContextProvider(Component)) {
20106 popContext(failedUnitOfWork);
20107 }
20108 break;
20109 }
20110 case HostPortal:
20111 popHostContainer(failedUnitOfWork);
20112 break;
20113 case ContextProvider:
20114 popProvider(failedUnitOfWork);
20115 break;
20116 }
20117 // Replay the begin phase.
20118 isReplayingFailedUnitOfWork = true;
20119 originalReplayError = thrownValue;
20120 invokeGuardedCallback(null, workLoop, null, isYieldy);
20121 isReplayingFailedUnitOfWork = false;
20122 originalReplayError = null;
20123 if (hasCaughtError()) {
20124 var replayError = clearCaughtError();
20125 if (replayError != null && thrownValue != null) {
20126 try {
20127 // Reading the expando property is intentionally
20128 // inside `try` because it might be a getter or Proxy.
20129 if (replayError._suppressLogging) {
20130 // Also suppress logging for the original error.
20131 thrownValue._suppressLogging = true;
20132 }
20133 } catch (inner) {
20134 // Ignore.
20135 }
20136 }
20137 } else {
20138 // If the begin phase did not fail the second time, set this pointer
20139 // back to the original value.
20140 nextUnitOfWork = failedUnitOfWork;
20141 }
20142 };
20143 rethrowOriginalError = function () {
20144 throw originalReplayError;
20145 };
20146}
20147
20148function resetStack() {
20149 if (nextUnitOfWork !== null) {
20150 var interruptedWork = nextUnitOfWork.return;
20151 while (interruptedWork !== null) {
20152 unwindInterruptedWork(interruptedWork);
20153 interruptedWork = interruptedWork.return;
20154 }
20155 }
20156
20157 {
20158 ReactStrictModeWarnings.discardPendingWarnings();
20159 checkThatStackIsEmpty();
20160 }
20161
20162 nextRoot = null;
20163 nextRenderExpirationTime = NoWork;
20164 nextLatestAbsoluteTimeoutMs = -1;
20165 nextRenderDidError = false;
20166 nextUnitOfWork = null;
20167}
20168
20169function commitAllHostEffects() {
20170 while (nextEffect !== null) {
20171 {
20172 setCurrentFiber(nextEffect);
20173 }
20174 recordEffect();
20175
20176 var effectTag = nextEffect.effectTag;
20177
20178 if (effectTag & ContentReset) {
20179 commitResetTextContent(nextEffect);
20180 }
20181
20182 if (effectTag & Ref) {
20183 var current$$1 = nextEffect.alternate;
20184 if (current$$1 !== null) {
20185 commitDetachRef(current$$1);
20186 }
20187 }
20188
20189 // The following switch statement is only concerned about placement,
20190 // updates, and deletions. To avoid needing to add a case for every
20191 // possible bitmap value, we remove the secondary effects from the
20192 // effect tag and switch on that value.
20193 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
20194 switch (primaryEffectTag) {
20195 case Placement:
20196 {
20197 commitPlacement(nextEffect);
20198 // Clear the "placement" from effect tag so that we know that this is inserted, before
20199 // any life-cycles like componentDidMount gets called.
20200 // TODO: findDOMNode doesn't rely on this any more but isMounted
20201 // does and isMounted is deprecated anyway so we should be able
20202 // to kill this.
20203 nextEffect.effectTag &= ~Placement;
20204 break;
20205 }
20206 case PlacementAndUpdate:
20207 {
20208 // Placement
20209 commitPlacement(nextEffect);
20210 // Clear the "placement" from effect tag so that we know that this is inserted, before
20211 // any life-cycles like componentDidMount gets called.
20212 nextEffect.effectTag &= ~Placement;
20213
20214 // Update
20215 var _current = nextEffect.alternate;
20216 commitWork(_current, nextEffect);
20217 break;
20218 }
20219 case Update:
20220 {
20221 var _current2 = nextEffect.alternate;
20222 commitWork(_current2, nextEffect);
20223 break;
20224 }
20225 case Deletion:
20226 {
20227 commitDeletion(nextEffect);
20228 break;
20229 }
20230 }
20231 nextEffect = nextEffect.nextEffect;
20232 }
20233
20234 {
20235 resetCurrentFiber();
20236 }
20237}
20238
20239function commitBeforeMutationLifecycles() {
20240 while (nextEffect !== null) {
20241 {
20242 setCurrentFiber(nextEffect);
20243 }
20244
20245 var effectTag = nextEffect.effectTag;
20246 if (effectTag & Snapshot) {
20247 recordEffect();
20248 var current$$1 = nextEffect.alternate;
20249 commitBeforeMutationLifeCycles(current$$1, nextEffect);
20250 }
20251
20252 nextEffect = nextEffect.nextEffect;
20253 }
20254
20255 {
20256 resetCurrentFiber();
20257 }
20258}
20259
20260function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
20261 {
20262 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
20263 ReactStrictModeWarnings.flushLegacyContextWarning();
20264
20265 if (warnAboutDeprecatedLifecycles) {
20266 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
20267 }
20268 }
20269 while (nextEffect !== null) {
20270 {
20271 setCurrentFiber(nextEffect);
20272 }
20273 var effectTag = nextEffect.effectTag;
20274
20275 if (effectTag & (Update | Callback)) {
20276 recordEffect();
20277 var current$$1 = nextEffect.alternate;
20278 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
20279 }
20280
20281 if (effectTag & Ref) {
20282 recordEffect();
20283 commitAttachRef(nextEffect);
20284 }
20285
20286 if (effectTag & Passive) {
20287 rootWithPendingPassiveEffects = finishedRoot;
20288 }
20289
20290 nextEffect = nextEffect.nextEffect;
20291 }
20292 {
20293 resetCurrentFiber();
20294 }
20295}
20296
20297function commitPassiveEffects(root, firstEffect) {
20298 rootWithPendingPassiveEffects = null;
20299 passiveEffectCallbackHandle = null;
20300 passiveEffectCallback = null;
20301
20302 // Set this to true to prevent re-entrancy
20303 var previousIsRendering = isRendering;
20304 isRendering = true;
20305
20306 var effect = firstEffect;
20307 do {
20308 {
20309 setCurrentFiber(effect);
20310 }
20311
20312 if (effect.effectTag & Passive) {
20313 var didError = false;
20314 var error = void 0;
20315 {
20316 isInPassiveEffectDEV = true;
20317 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
20318 isInPassiveEffectDEV = false;
20319 if (hasCaughtError()) {
20320 didError = true;
20321 error = clearCaughtError();
20322 }
20323 }
20324 if (didError) {
20325 captureCommitPhaseError$1(effect, error);
20326 }
20327 }
20328 effect = effect.nextEffect;
20329 } while (effect !== null);
20330 {
20331 resetCurrentFiber();
20332 }
20333
20334 isRendering = previousIsRendering;
20335
20336 // Check if work was scheduled by one of the effects
20337 var rootExpirationTime = root.expirationTime;
20338 if (rootExpirationTime !== NoWork) {
20339 requestWork(root, rootExpirationTime);
20340 }
20341 // Flush any sync work that was scheduled by effects
20342 if (!isBatchingUpdates && !isRendering) {
20343 performSyncWork();
20344 }
20345
20346 {
20347 if (rootWithPendingPassiveEffects === root) {
20348 nestedPassiveEffectCountDEV++;
20349 } else {
20350 nestedPassiveEffectCountDEV = 0;
20351 }
20352 }
20353}
20354
20355function isAlreadyFailedLegacyErrorBoundary$1(instance) {
20356 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
20357}
20358
20359function markLegacyErrorBoundaryAsFailed$1(instance) {
20360 if (legacyErrorBoundariesThatAlreadyFailed === null) {
20361 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
20362 } else {
20363 legacyErrorBoundariesThatAlreadyFailed.add(instance);
20364 }
20365}
20366
20367function flushPassiveEffects$1() {
20368 var didFlushEffects = passiveEffectCallback !== null;
20369 if (passiveEffectCallbackHandle !== null) {
20370 cancelCallback$1(passiveEffectCallbackHandle);
20371 }
20372 if (passiveEffectCallback !== null) {
20373 // We call the scheduled callback instead of commitPassiveEffects directly
20374 // to ensure tracing works correctly.
20375 passiveEffectCallback();
20376 }
20377 return didFlushEffects;
20378}
20379
20380function commitRoot(root, finishedWork) {
20381 isWorking = true;
20382 isCommitting$1 = true;
20383 startCommitTimer();
20384
20385 (function () {
20386 if (!(root.current !== finishedWork)) {
20387 {
20388 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.');
20389 }
20390 }
20391 })();
20392 var committedExpirationTime = root.pendingCommitExpirationTime;
20393 (function () {
20394 if (!(committedExpirationTime !== NoWork)) {
20395 {
20396 throw ReactError('Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.');
20397 }
20398 }
20399 })();
20400 root.pendingCommitExpirationTime = NoWork;
20401
20402 // Update the pending priority levels to account for the work that we are
20403 // about to commit. This needs to happen before calling the lifecycles, since
20404 // they may schedule additional updates.
20405 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
20406 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
20407 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
20408 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
20409
20410 var prevInteractions = null;
20411 if (enableSchedulerTracing) {
20412 // Restore any pending interactions at this point,
20413 // So that cascading work triggered during the render phase will be accounted for.
20414 prevInteractions = __interactionsRef.current;
20415 __interactionsRef.current = root.memoizedInteractions;
20416 }
20417
20418 // Reset this to null before calling lifecycles
20419 ReactCurrentOwner$2.current = null;
20420
20421 var firstEffect = void 0;
20422 if (finishedWork.effectTag > PerformedWork) {
20423 // A fiber's effect list consists only of its children, not itself. So if
20424 // the root has an effect, we need to add it to the end of the list. The
20425 // resulting list is the set that would belong to the root's parent, if
20426 // it had one; that is, all the effects in the tree including the root.
20427 if (finishedWork.lastEffect !== null) {
20428 finishedWork.lastEffect.nextEffect = finishedWork;
20429 firstEffect = finishedWork.firstEffect;
20430 } else {
20431 firstEffect = finishedWork;
20432 }
20433 } else {
20434 // There is no effect on the root.
20435 firstEffect = finishedWork.firstEffect;
20436 }
20437
20438 prepareForCommit(root.containerInfo);
20439
20440 // Invoke instances of getSnapshotBeforeUpdate before mutation.
20441 nextEffect = firstEffect;
20442 startCommitSnapshotEffectsTimer();
20443 while (nextEffect !== null) {
20444 var didError = false;
20445 var error = void 0;
20446 {
20447 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
20448 if (hasCaughtError()) {
20449 didError = true;
20450 error = clearCaughtError();
20451 }
20452 }
20453 if (didError) {
20454 (function () {
20455 if (!(nextEffect !== null)) {
20456 {
20457 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20458 }
20459 }
20460 })();
20461 captureCommitPhaseError$1(nextEffect, error);
20462 // Clean-up
20463 if (nextEffect !== null) {
20464 nextEffect = nextEffect.nextEffect;
20465 }
20466 }
20467 }
20468 stopCommitSnapshotEffectsTimer();
20469
20470 if (enableProfilerTimer) {
20471 // Mark the current commit time to be shared by all Profilers in this batch.
20472 // This enables them to be grouped later.
20473 recordCommitTime();
20474 }
20475
20476 // Commit all the side-effects within a tree. We'll do this in two passes.
20477 // The first pass performs all the host insertions, updates, deletions and
20478 // ref unmounts.
20479 nextEffect = firstEffect;
20480 startCommitHostEffectsTimer();
20481 while (nextEffect !== null) {
20482 var _didError = false;
20483 var _error = void 0;
20484 {
20485 invokeGuardedCallback(null, commitAllHostEffects, null);
20486 if (hasCaughtError()) {
20487 _didError = true;
20488 _error = clearCaughtError();
20489 }
20490 }
20491 if (_didError) {
20492 (function () {
20493 if (!(nextEffect !== null)) {
20494 {
20495 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20496 }
20497 }
20498 })();
20499 captureCommitPhaseError$1(nextEffect, _error);
20500 // Clean-up
20501 if (nextEffect !== null) {
20502 nextEffect = nextEffect.nextEffect;
20503 }
20504 }
20505 }
20506 stopCommitHostEffectsTimer();
20507
20508 resetAfterCommit(root.containerInfo);
20509
20510 // The work-in-progress tree is now the current tree. This must come after
20511 // the first pass of the commit phase, so that the previous tree is still
20512 // current during componentWillUnmount, but before the second pass, so that
20513 // the finished work is current during componentDidMount/Update.
20514 root.current = finishedWork;
20515
20516 // In the second pass we'll perform all life-cycles and ref callbacks.
20517 // Life-cycles happen as a separate pass so that all placements, updates,
20518 // and deletions in the entire tree have already been invoked.
20519 // This pass also triggers any renderer-specific initial effects.
20520 nextEffect = firstEffect;
20521 startCommitLifeCyclesTimer();
20522 while (nextEffect !== null) {
20523 var _didError2 = false;
20524 var _error2 = void 0;
20525 {
20526 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
20527 if (hasCaughtError()) {
20528 _didError2 = true;
20529 _error2 = clearCaughtError();
20530 }
20531 }
20532 if (_didError2) {
20533 (function () {
20534 if (!(nextEffect !== null)) {
20535 {
20536 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
20537 }
20538 }
20539 })();
20540 captureCommitPhaseError$1(nextEffect, _error2);
20541 if (nextEffect !== null) {
20542 nextEffect = nextEffect.nextEffect;
20543 }
20544 }
20545 }
20546
20547 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
20548 // This commit included a passive effect. These do not need to fire until
20549 // after the next paint. Schedule an callback to fire them in an async
20550 // event. To ensure serial execution, the callback will be flushed early if
20551 // we enter rootWithPendingPassiveEffects commit phase before then.
20552 var callback = commitPassiveEffects.bind(null, root, firstEffect);
20553 if (enableSchedulerTracing) {
20554 // TODO: Avoid this extra callback by mutating the tracing ref directly,
20555 // like we do at the beginning of commitRoot. I've opted not to do that
20556 // here because that code is still in flux.
20557 callback = unstable_wrap(callback);
20558 }
20559 passiveEffectCallbackHandle = scheduleCallback$1(NormalPriority$1, callback);
20560 passiveEffectCallback = callback;
20561 }
20562
20563 isCommitting$1 = false;
20564 isWorking = false;
20565 stopCommitLifeCyclesTimer();
20566 stopCommitTimer();
20567 onCommitRoot(finishedWork.stateNode);
20568 if (true && ReactFiberInstrumentation_1.debugTool) {
20569 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
20570 }
20571
20572 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
20573 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
20574 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
20575 if (earliestRemainingTimeAfterCommit === NoWork) {
20576 // If there's no remaining work, we can clear the set of already failed
20577 // error boundaries.
20578 legacyErrorBoundariesThatAlreadyFailed = null;
20579 }
20580 onCommit(root, earliestRemainingTimeAfterCommit);
20581
20582 if (enableSchedulerTracing) {
20583 __interactionsRef.current = prevInteractions;
20584
20585 var subscriber = void 0;
20586
20587 try {
20588 subscriber = __subscriberRef.current;
20589 if (subscriber !== null && root.memoizedInteractions.size > 0) {
20590 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
20591 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
20592 }
20593 } catch (error) {
20594 // It's not safe for commitRoot() to throw.
20595 // Store the error for now and we'll re-throw in finishRendering().
20596 if (!hasUnhandledError) {
20597 hasUnhandledError = true;
20598 unhandledError = error;
20599 }
20600 } finally {
20601 // Clear completed interactions from the pending Map.
20602 // Unless the render was suspended or cascading work was scheduled,
20603 // In which case– leave pending interactions until the subsequent render.
20604 var pendingInteractionMap = root.pendingInteractionMap;
20605 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
20606 // Only decrement the pending interaction count if we're done.
20607 // If there's still work at the current priority,
20608 // That indicates that we are waiting for suspense data.
20609 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
20610 pendingInteractionMap.delete(scheduledExpirationTime);
20611
20612 scheduledInteractions.forEach(function (interaction) {
20613 interaction.__count--;
20614
20615 if (subscriber !== null && interaction.__count === 0) {
20616 try {
20617 subscriber.onInteractionScheduledWorkCompleted(interaction);
20618 } catch (error) {
20619 // It's not safe for commitRoot() to throw.
20620 // Store the error for now and we'll re-throw in finishRendering().
20621 if (!hasUnhandledError) {
20622 hasUnhandledError = true;
20623 unhandledError = error;
20624 }
20625 }
20626 }
20627 });
20628 }
20629 });
20630 }
20631 }
20632}
20633
20634function resetChildExpirationTime(workInProgress, renderTime) {
20635 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
20636 // The children of this component are hidden. Don't bubble their
20637 // expiration times.
20638 return;
20639 }
20640
20641 var newChildExpirationTime = NoWork;
20642
20643 // Bubble up the earliest expiration time.
20644 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
20645 // We're in profiling mode.
20646 // Let's use this same traversal to update the render durations.
20647 var actualDuration = workInProgress.actualDuration;
20648 var treeBaseDuration = workInProgress.selfBaseDuration;
20649
20650 // When a fiber is cloned, its actualDuration is reset to 0.
20651 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
20652 // When work is done, it should bubble to the parent's actualDuration.
20653 // If the fiber has not been cloned though, (meaning no work was done),
20654 // Then this value will reflect the amount of time spent working on a previous render.
20655 // In that case it should not bubble.
20656 // We determine whether it was cloned by comparing the child pointer.
20657 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
20658
20659 var child = workInProgress.child;
20660 while (child !== null) {
20661 var childUpdateExpirationTime = child.expirationTime;
20662 var childChildExpirationTime = child.childExpirationTime;
20663 if (childUpdateExpirationTime > newChildExpirationTime) {
20664 newChildExpirationTime = childUpdateExpirationTime;
20665 }
20666 if (childChildExpirationTime > newChildExpirationTime) {
20667 newChildExpirationTime = childChildExpirationTime;
20668 }
20669 if (shouldBubbleActualDurations) {
20670 actualDuration += child.actualDuration;
20671 }
20672 treeBaseDuration += child.treeBaseDuration;
20673 child = child.sibling;
20674 }
20675 workInProgress.actualDuration = actualDuration;
20676 workInProgress.treeBaseDuration = treeBaseDuration;
20677 } else {
20678 var _child = workInProgress.child;
20679 while (_child !== null) {
20680 var _childUpdateExpirationTime = _child.expirationTime;
20681 var _childChildExpirationTime = _child.childExpirationTime;
20682 if (_childUpdateExpirationTime > newChildExpirationTime) {
20683 newChildExpirationTime = _childUpdateExpirationTime;
20684 }
20685 if (_childChildExpirationTime > newChildExpirationTime) {
20686 newChildExpirationTime = _childChildExpirationTime;
20687 }
20688 _child = _child.sibling;
20689 }
20690 }
20691
20692 workInProgress.childExpirationTime = newChildExpirationTime;
20693}
20694
20695function completeUnitOfWork(workInProgress) {
20696 // Attempt to complete the current unit of work, then move to the
20697 // next sibling. If there are no more siblings, return to the
20698 // parent fiber.
20699 while (true) {
20700 // The current, flushed, state of this fiber is the alternate.
20701 // Ideally nothing should rely on this, but relying on it here
20702 // means that we don't need an additional field on the work in
20703 // progress.
20704 var current$$1 = workInProgress.alternate;
20705 {
20706 setCurrentFiber(workInProgress);
20707 }
20708
20709 var returnFiber = workInProgress.return;
20710 var siblingFiber = workInProgress.sibling;
20711
20712 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
20713 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20714 // Don't replay if it fails during completion phase.
20715 mayReplayFailedUnitOfWork = false;
20716 }
20717 // This fiber completed.
20718 // Remember we're completing this unit so we can find a boundary if it fails.
20719 nextUnitOfWork = workInProgress;
20720 if (enableProfilerTimer) {
20721 if (workInProgress.mode & ProfileMode) {
20722 startProfilerTimer(workInProgress);
20723 }
20724 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
20725 if (workInProgress.mode & ProfileMode) {
20726 // Update render duration assuming we didn't error.
20727 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
20728 }
20729 } else {
20730 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
20731 }
20732 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20733 // We're out of completion phase so replaying is fine now.
20734 mayReplayFailedUnitOfWork = true;
20735 }
20736 stopWorkTimer(workInProgress);
20737 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
20738 {
20739 resetCurrentFiber();
20740 }
20741
20742 if (nextUnitOfWork !== null) {
20743 // Completing this fiber spawned new work. Work on that next.
20744 return nextUnitOfWork;
20745 }
20746
20747 if (returnFiber !== null &&
20748 // Do not append effects to parents if a sibling failed to complete
20749 (returnFiber.effectTag & Incomplete) === NoEffect) {
20750 // Append all the effects of the subtree and this fiber onto the effect
20751 // list of the parent. The completion order of the children affects the
20752 // side-effect order.
20753 if (returnFiber.firstEffect === null) {
20754 returnFiber.firstEffect = workInProgress.firstEffect;
20755 }
20756 if (workInProgress.lastEffect !== null) {
20757 if (returnFiber.lastEffect !== null) {
20758 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
20759 }
20760 returnFiber.lastEffect = workInProgress.lastEffect;
20761 }
20762
20763 // If this fiber had side-effects, we append it AFTER the children's
20764 // side-effects. We can perform certain side-effects earlier if
20765 // needed, by doing multiple passes over the effect list. We don't want
20766 // to schedule our own side-effect on our own list because if end up
20767 // reusing children we'll schedule this effect onto itself since we're
20768 // at the end.
20769 var effectTag = workInProgress.effectTag;
20770 // Skip both NoWork and PerformedWork tags when creating the effect list.
20771 // PerformedWork effect is read by React DevTools but shouldn't be committed.
20772 if (effectTag > PerformedWork) {
20773 if (returnFiber.lastEffect !== null) {
20774 returnFiber.lastEffect.nextEffect = workInProgress;
20775 } else {
20776 returnFiber.firstEffect = workInProgress;
20777 }
20778 returnFiber.lastEffect = workInProgress;
20779 }
20780 }
20781
20782 if (true && ReactFiberInstrumentation_1.debugTool) {
20783 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20784 }
20785
20786 if (siblingFiber !== null) {
20787 // If there is more work to do in this returnFiber, do that next.
20788 return siblingFiber;
20789 } else if (returnFiber !== null) {
20790 // If there's no more work in this returnFiber. Complete the returnFiber.
20791 workInProgress = returnFiber;
20792 continue;
20793 } else {
20794 // We've reached the root.
20795 return null;
20796 }
20797 } else {
20798 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
20799 // Record the render duration for the fiber that errored.
20800 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
20801
20802 // Include the time spent working on failed children before continuing.
20803 var actualDuration = workInProgress.actualDuration;
20804 var child = workInProgress.child;
20805 while (child !== null) {
20806 actualDuration += child.actualDuration;
20807 child = child.sibling;
20808 }
20809 workInProgress.actualDuration = actualDuration;
20810 }
20811
20812 // This fiber did not complete because something threw. Pop values off
20813 // the stack without entering the complete phase. If this is a boundary,
20814 // capture values if possible.
20815 var next = unwindWork(workInProgress, nextRenderExpirationTime);
20816 // Because this fiber did not complete, don't reset its expiration time.
20817 if (workInProgress.effectTag & DidCapture) {
20818 // Restarting an error boundary
20819 stopFailedWorkTimer(workInProgress);
20820 } else {
20821 stopWorkTimer(workInProgress);
20822 }
20823
20824 {
20825 resetCurrentFiber();
20826 }
20827
20828 if (next !== null) {
20829 stopWorkTimer(workInProgress);
20830 if (true && ReactFiberInstrumentation_1.debugTool) {
20831 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20832 }
20833
20834 // If completing this work spawned new work, do that next. We'll come
20835 // back here again.
20836 // Since we're restarting, remove anything that is not a host effect
20837 // from the effect tag.
20838 next.effectTag &= HostEffectMask;
20839 return next;
20840 }
20841
20842 if (returnFiber !== null) {
20843 // Mark the parent fiber as incomplete and clear its effect list.
20844 returnFiber.firstEffect = returnFiber.lastEffect = null;
20845 returnFiber.effectTag |= Incomplete;
20846 }
20847
20848 if (true && ReactFiberInstrumentation_1.debugTool) {
20849 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
20850 }
20851
20852 if (siblingFiber !== null) {
20853 // If there is more work to do in this returnFiber, do that next.
20854 return siblingFiber;
20855 } else if (returnFiber !== null) {
20856 // If there's no more work in this returnFiber. Complete the returnFiber.
20857 workInProgress = returnFiber;
20858 continue;
20859 } else {
20860 return null;
20861 }
20862 }
20863 }
20864
20865 // Without this explicit null return Flow complains of invalid return type
20866 // TODO Remove the above while(true) loop
20867 // eslint-disable-next-line no-unreachable
20868 return null;
20869}
20870
20871function performUnitOfWork(workInProgress) {
20872 // The current, flushed, state of this fiber is the alternate.
20873 // Ideally nothing should rely on this, but relying on it here
20874 // means that we don't need an additional field on the work in
20875 // progress.
20876 var current$$1 = workInProgress.alternate;
20877
20878 // See if beginning this work spawns more work.
20879 startWorkTimer(workInProgress);
20880 {
20881 setCurrentFiber(workInProgress);
20882 }
20883
20884 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
20885 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
20886 }
20887
20888 var next = void 0;
20889 if (enableProfilerTimer) {
20890 if (workInProgress.mode & ProfileMode) {
20891 startProfilerTimer(workInProgress);
20892 }
20893
20894 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
20895 workInProgress.memoizedProps = workInProgress.pendingProps;
20896
20897 if (workInProgress.mode & ProfileMode) {
20898 // Record the render duration assuming we didn't bailout (or error).
20899 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
20900 }
20901 } else {
20902 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
20903 workInProgress.memoizedProps = workInProgress.pendingProps;
20904 }
20905
20906 {
20907 resetCurrentFiber();
20908 if (isReplayingFailedUnitOfWork) {
20909 // Currently replaying a failed unit of work. This should be unreachable,
20910 // because the render phase is meant to be idempotent, and it should
20911 // have thrown again. Since it didn't, rethrow the original error, so
20912 // React's internal stack is not misaligned.
20913 rethrowOriginalError();
20914 }
20915 }
20916 if (true && ReactFiberInstrumentation_1.debugTool) {
20917 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
20918 }
20919
20920 if (next === null) {
20921 // If this doesn't spawn new work, complete the current work.
20922 next = completeUnitOfWork(workInProgress);
20923 }
20924
20925 ReactCurrentOwner$2.current = null;
20926
20927 return next;
20928}
20929
20930function workLoop(isYieldy) {
20931 if (!isYieldy) {
20932 // Flush work without yielding
20933 while (nextUnitOfWork !== null) {
20934 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
20935 }
20936 } else {
20937 // Flush asynchronous work until there's a higher priority event
20938 while (nextUnitOfWork !== null && !shouldYield$2()) {
20939 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
20940 }
20941 }
20942}
20943
20944function renderRoot(root, isYieldy) {
20945 (function () {
20946 if (!!isWorking) {
20947 {
20948 throw ReactError('renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
20949 }
20950 }
20951 })();
20952
20953 flushPassiveEffects$1();
20954
20955 isWorking = true;
20956 var previousDispatcher = ReactCurrentDispatcher.current;
20957 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
20958
20959 var expirationTime = root.nextExpirationTimeToWorkOn;
20960
20961 // Check if we're starting from a fresh stack, or if we're resuming from
20962 // previously yielded work.
20963 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
20964 // Reset the stack and start working from the root.
20965 resetStack();
20966 nextRoot = root;
20967 nextRenderExpirationTime = expirationTime;
20968 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
20969 root.pendingCommitExpirationTime = NoWork;
20970
20971 if (enableSchedulerTracing) {
20972 // Determine which interactions this batch of work currently includes,
20973 // So that we can accurately attribute time spent working on it,
20974 var interactions = new Set();
20975 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
20976 if (scheduledExpirationTime >= expirationTime) {
20977 scheduledInteractions.forEach(function (interaction) {
20978 return interactions.add(interaction);
20979 });
20980 }
20981 });
20982
20983 // Store the current set of interactions on the FiberRoot for a few reasons:
20984 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
20985 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
20986 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
20987 root.memoizedInteractions = interactions;
20988
20989 if (interactions.size > 0) {
20990 var subscriber = __subscriberRef.current;
20991 if (subscriber !== null) {
20992 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
20993 try {
20994 subscriber.onWorkStarted(interactions, threadID);
20995 } catch (error) {
20996 // Work thrown by an interaction tracing subscriber should be rethrown,
20997 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
20998 // Store the error for now and we'll re-throw in finishRendering().
20999 if (!hasUnhandledError) {
21000 hasUnhandledError = true;
21001 unhandledError = error;
21002 }
21003 }
21004 }
21005 }
21006 }
21007 }
21008
21009 var prevInteractions = null;
21010 if (enableSchedulerTracing) {
21011 // We're about to start new traced work.
21012 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
21013 prevInteractions = __interactionsRef.current;
21014 __interactionsRef.current = root.memoizedInteractions;
21015 }
21016
21017 var didFatal = false;
21018
21019 startWorkLoopTimer(nextUnitOfWork);
21020
21021 do {
21022 try {
21023 workLoop(isYieldy);
21024 } catch (thrownValue) {
21025 resetContextDependences();
21026 resetHooks();
21027
21028 // Reset in case completion throws.
21029 // This is only used in DEV and when replaying is on.
21030 var mayReplay = void 0;
21031 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
21032 mayReplay = mayReplayFailedUnitOfWork;
21033 mayReplayFailedUnitOfWork = true;
21034 }
21035
21036 if (nextUnitOfWork === null) {
21037 // This is a fatal error.
21038 didFatal = true;
21039 onUncaughtError$1(thrownValue);
21040 } else {
21041 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
21042 // Record the time spent rendering before an error was thrown.
21043 // This avoids inaccurate Profiler durations in the case of a suspended render.
21044 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
21045 }
21046
21047 {
21048 // Reset global debug state
21049 // We assume this is defined in DEV
21050 resetCurrentlyProcessingQueue();
21051 }
21052
21053 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
21054 if (mayReplay) {
21055 var failedUnitOfWork = nextUnitOfWork;
21056 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
21057 }
21058 }
21059
21060 // TODO: we already know this isn't true in some cases.
21061 // At least this shows a nicer error message until we figure out the cause.
21062 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
21063 (function () {
21064 if (!(nextUnitOfWork !== null)) {
21065 {
21066 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.');
21067 }
21068 }
21069 })();
21070
21071 var sourceFiber = nextUnitOfWork;
21072 var returnFiber = sourceFiber.return;
21073 if (returnFiber === null) {
21074 // This is the root. The root could capture its own errors. However,
21075 // we don't know if it errors before or after we pushed the host
21076 // context. This information is needed to avoid a stack mismatch.
21077 // Because we're not sure, treat this as a fatal error. We could track
21078 // which phase it fails in, but doesn't seem worth it. At least
21079 // for now.
21080 didFatal = true;
21081 onUncaughtError$1(thrownValue);
21082 } else {
21083 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
21084 nextUnitOfWork = completeUnitOfWork(sourceFiber);
21085 continue;
21086 }
21087 }
21088 }
21089 break;
21090 } while (true);
21091
21092 if (enableSchedulerTracing) {
21093 // Traced work is done for now; restore the previous interactions.
21094 __interactionsRef.current = prevInteractions;
21095 }
21096
21097 // We're done performing work. Time to clean up.
21098 isWorking = false;
21099 ReactCurrentDispatcher.current = previousDispatcher;
21100 resetContextDependences();
21101 resetHooks();
21102
21103 // Yield back to main thread.
21104 if (didFatal) {
21105 var _didCompleteRoot = false;
21106 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
21107 interruptedBy = null;
21108 // There was a fatal error.
21109 {
21110 resetStackAfterFatalErrorInDev();
21111 }
21112 // `nextRoot` points to the in-progress root. A non-null value indicates
21113 // that we're in the middle of an async render. Set it to null to indicate
21114 // there's no more work to be done in the current batch.
21115 nextRoot = null;
21116 onFatal(root);
21117 return;
21118 }
21119
21120 if (nextUnitOfWork !== null) {
21121 // There's still remaining async work in this tree, but we ran out of time
21122 // in the current frame. Yield back to the renderer. Unless we're
21123 // interrupted by a higher priority update, we'll continue later from where
21124 // we left off.
21125 var _didCompleteRoot2 = false;
21126 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
21127 interruptedBy = null;
21128 onYield(root);
21129 return;
21130 }
21131
21132 // We completed the whole tree.
21133 var didCompleteRoot = true;
21134 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
21135 var rootWorkInProgress = root.current.alternate;
21136 (function () {
21137 if (!(rootWorkInProgress !== null)) {
21138 {
21139 throw ReactError('Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.');
21140 }
21141 }
21142 })();
21143
21144 // `nextRoot` points to the in-progress root. A non-null value indicates
21145 // that we're in the middle of an async render. Set it to null to indicate
21146 // there's no more work to be done in the current batch.
21147 nextRoot = null;
21148 interruptedBy = null;
21149
21150 if (nextRenderDidError) {
21151 // There was an error
21152 if (hasLowerPriorityWork(root, expirationTime)) {
21153 // There's lower priority work. If so, it may have the effect of fixing
21154 // the exception that was just thrown. Exit without committing. This is
21155 // similar to a suspend, but without a timeout because we're not waiting
21156 // for a promise to resolve. React will restart at the lower
21157 // priority level.
21158 markSuspendedPriorityLevel(root, expirationTime);
21159 var suspendedExpirationTime = expirationTime;
21160 var rootExpirationTime = root.expirationTime;
21161 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
21162 );
21163 return;
21164 } else if (
21165 // There's no lower priority work, but we're rendering asynchronously.
21166 // Synchronously attempt to render the same level one more time. This is
21167 // similar to a suspend, but without a timeout because we're not waiting
21168 // for a promise to resolve.
21169 !root.didError && isYieldy) {
21170 root.didError = true;
21171 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
21172 var _rootExpirationTime = root.expirationTime = Sync;
21173 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
21174 );
21175 return;
21176 }
21177 }
21178
21179 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
21180 // The tree was suspended.
21181 var _suspendedExpirationTime2 = expirationTime;
21182 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
21183
21184 // Find the earliest uncommitted expiration time in the tree, including
21185 // work that is suspended. The timeout threshold cannot be longer than
21186 // the overall expiration.
21187 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
21188 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
21189 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
21190 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
21191 }
21192
21193 // Subtract the current time from the absolute timeout to get the number
21194 // of milliseconds until the timeout. In other words, convert an absolute
21195 // timestamp to a relative time. This is the value that is passed
21196 // to `setTimeout`.
21197 var currentTimeMs = expirationTimeToMs(requestCurrentTime$1());
21198 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
21199 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
21200
21201 // TODO: Account for the Just Noticeable Difference
21202
21203 var _rootExpirationTime2 = root.expirationTime;
21204 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
21205 return;
21206 }
21207
21208 // Ready to commit.
21209 onComplete(root, rootWorkInProgress, expirationTime);
21210}
21211
21212function captureCommitPhaseError$1(sourceFiber, value) {
21213 var expirationTime = Sync;
21214 var fiber = sourceFiber.return;
21215 while (fiber !== null) {
21216 switch (fiber.tag) {
21217 case ClassComponent:
21218 var ctor = fiber.type;
21219 var instance = fiber.stateNode;
21220 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$1(instance)) {
21221 var errorInfo = createCapturedValue(value, sourceFiber);
21222 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
21223 enqueueUpdate(fiber, update);
21224 scheduleWork$1(fiber, expirationTime);
21225 return;
21226 }
21227 break;
21228 case HostRoot:
21229 {
21230 var _errorInfo = createCapturedValue(value, sourceFiber);
21231 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
21232 enqueueUpdate(fiber, _update);
21233 scheduleWork$1(fiber, expirationTime);
21234 return;
21235 }
21236 }
21237 fiber = fiber.return;
21238 }
21239
21240 if (sourceFiber.tag === HostRoot) {
21241 // Error was thrown at the root. There is no parent, so the root
21242 // itself should capture it.
21243 var rootFiber = sourceFiber;
21244 var _errorInfo2 = createCapturedValue(value, rootFiber);
21245 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
21246 enqueueUpdate(rootFiber, _update2);
21247 scheduleWork$1(rootFiber, expirationTime);
21248 }
21249}
21250
21251function computeThreadID(expirationTime, interactionThreadID) {
21252 // Interaction threads are unique per root and expiration time.
21253 return expirationTime * 1000 + interactionThreadID;
21254}
21255
21256// Creates a unique async expiration time.
21257function computeUniqueAsyncExpiration$1() {
21258 var currentTime = requestCurrentTime$1();
21259 var result = computeAsyncExpiration(currentTime);
21260 if (result >= lastUniqueAsyncExpiration) {
21261 // Since we assume the current time monotonically increases, we only hit
21262 // this branch when computeUniqueAsyncExpiration is fired multiple times
21263 // within a 200ms window (or whatever the async bucket size is).
21264 result = lastUniqueAsyncExpiration - 1;
21265 }
21266 lastUniqueAsyncExpiration = result;
21267 return lastUniqueAsyncExpiration;
21268}
21269
21270function computeExpirationForFiber$1(currentTime, fiber) {
21271 var expirationTime = void 0;
21272 if (expirationContext !== NoWork) {
21273 // An explicit expiration context was set;
21274 expirationTime = expirationContext;
21275 } else if (isWorking) {
21276 if (isCommitting$1) {
21277 // Updates that occur during the commit phase should have sync priority
21278 // by default.
21279 expirationTime = Sync;
21280 } else {
21281 // Updates during the render phase should expire at the same time as
21282 // the work that is being rendered.
21283 expirationTime = nextRenderExpirationTime;
21284 }
21285 } else {
21286 // No explicit expiration context was set, and we're not currently
21287 // performing work. Calculate a new expiration time.
21288 if (fiber.mode & ConcurrentMode) {
21289 if (isBatchingInteractiveUpdates) {
21290 // This is an interactive update
21291 expirationTime = computeInteractiveExpiration(currentTime);
21292 } else {
21293 // This is an async update
21294 expirationTime = computeAsyncExpiration(currentTime);
21295 }
21296 // If we're in the middle of rendering a tree, do not update at the same
21297 // expiration time that is already rendering.
21298 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
21299 expirationTime -= 1;
21300 }
21301 } else {
21302 // This is a sync update
21303 expirationTime = Sync;
21304 }
21305 }
21306 if (isBatchingInteractiveUpdates) {
21307 // This is an interactive update. Keep track of the lowest pending
21308 // interactive expiration time. This allows us to synchronously flush
21309 // all interactive updates when needed.
21310 if (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime) {
21311 lowestPriorityPendingInteractiveExpirationTime = expirationTime;
21312 }
21313 }
21314 return expirationTime;
21315}
21316
21317function renderDidSuspend$1(root, absoluteTimeoutMs, suspendedTime) {
21318 // Schedule the timeout.
21319 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
21320 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
21321 }
21322}
21323
21324function renderDidError$1() {
21325 nextRenderDidError = true;
21326}
21327
21328function inferStartTimeFromExpirationTime$1(root, expirationTime) {
21329 // We don't know exactly when the update was scheduled, but we can infer an
21330 // approximate start time from the expiration time. First, find the earliest
21331 // uncommitted expiration time in the tree, including work that is suspended.
21332 // Then subtract the offset used to compute an async update's expiration time.
21333 // This will cause high priority (interactive) work to expire earlier than
21334 // necessary, but we can account for this by adjusting for the Just
21335 // Noticeable Difference.
21336 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
21337 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
21338 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
21339}
21340
21341function pingSuspendedRoot$1(root, thenable, pingTime) {
21342 // A promise that previously suspended React from committing has resolved.
21343 // If React is still suspended, try again at the previous level (pingTime).
21344
21345 var pingCache = root.pingCache;
21346 if (pingCache !== null) {
21347 // The thenable resolved, so we no longer need to memoize, because it will
21348 // never be thrown again.
21349 pingCache.delete(thenable);
21350 }
21351
21352 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
21353 // Received a ping at the same priority level at which we're currently
21354 // rendering. Restart from the root.
21355 nextRoot = null;
21356 } else {
21357 // Confirm that the root is still suspended at this level. Otherwise exit.
21358 if (isPriorityLevelSuspended(root, pingTime)) {
21359 // Ping at the original level
21360 markPingedPriorityLevel(root, pingTime);
21361 var rootExpirationTime = root.expirationTime;
21362 if (rootExpirationTime !== NoWork) {
21363 requestWork(root, rootExpirationTime);
21364 }
21365 }
21366 }
21367}
21368
21369function retryTimedOutBoundary$1(boundaryFiber) {
21370 var currentTime = requestCurrentTime$1();
21371 var retryTime = computeExpirationForFiber$1(currentTime, boundaryFiber);
21372 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
21373 if (root !== null) {
21374 markPendingPriorityLevel(root, retryTime);
21375 var rootExpirationTime = root.expirationTime;
21376 if (rootExpirationTime !== NoWork) {
21377 requestWork(root, rootExpirationTime);
21378 }
21379 }
21380}
21381
21382function resolveRetryThenable$1(boundaryFiber, thenable) {
21383 // The boundary fiber (a Suspense component) previously timed out and was
21384 // rendered in its fallback state. One of the promises that suspended it has
21385 // resolved, which means at least part of the tree was likely unblocked. Try
21386 var retryCache = void 0;
21387 if (enableSuspenseServerRenderer) {
21388 switch (boundaryFiber.tag) {
21389 case SuspenseComponent:
21390 retryCache = boundaryFiber.stateNode;
21391 break;
21392 case DehydratedSuspenseComponent:
21393 retryCache = boundaryFiber.memoizedState;
21394 break;
21395 default:
21396 (function () {
21397 {
21398 {
21399 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
21400 }
21401 }
21402 })();
21403 }
21404 } else {
21405 retryCache = boundaryFiber.stateNode;
21406 }
21407 if (retryCache !== null) {
21408 // The thenable resolved, so we no longer need to memoize, because it will
21409 // never be thrown again.
21410 retryCache.delete(thenable);
21411 }
21412
21413 retryTimedOutBoundary$1(boundaryFiber);
21414}
21415
21416function scheduleWorkToRoot(fiber, expirationTime) {
21417 recordScheduleUpdate();
21418
21419 {
21420 if (fiber.tag === ClassComponent) {
21421 var instance = fiber.stateNode;
21422 warnAboutInvalidUpdates(instance);
21423 }
21424 }
21425
21426 // Update the source fiber's expiration time
21427 if (fiber.expirationTime < expirationTime) {
21428 fiber.expirationTime = expirationTime;
21429 }
21430 var alternate = fiber.alternate;
21431 if (alternate !== null && alternate.expirationTime < expirationTime) {
21432 alternate.expirationTime = expirationTime;
21433 }
21434 // Walk the parent path to the root and update the child expiration time.
21435 var node = fiber.return;
21436 var root = null;
21437 if (node === null && fiber.tag === HostRoot) {
21438 root = fiber.stateNode;
21439 } else {
21440 while (node !== null) {
21441 alternate = node.alternate;
21442 if (node.childExpirationTime < expirationTime) {
21443 node.childExpirationTime = expirationTime;
21444 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
21445 alternate.childExpirationTime = expirationTime;
21446 }
21447 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
21448 alternate.childExpirationTime = expirationTime;
21449 }
21450 if (node.return === null && node.tag === HostRoot) {
21451 root = node.stateNode;
21452 break;
21453 }
21454 node = node.return;
21455 }
21456 }
21457
21458 if (enableSchedulerTracing) {
21459 if (root !== null) {
21460 var interactions = __interactionsRef.current;
21461 if (interactions.size > 0) {
21462 var pendingInteractionMap = root.pendingInteractionMap;
21463 var pendingInteractions = pendingInteractionMap.get(expirationTime);
21464 if (pendingInteractions != null) {
21465 interactions.forEach(function (interaction) {
21466 if (!pendingInteractions.has(interaction)) {
21467 // Update the pending async work count for previously unscheduled interaction.
21468 interaction.__count++;
21469 }
21470
21471 pendingInteractions.add(interaction);
21472 });
21473 } else {
21474 pendingInteractionMap.set(expirationTime, new Set(interactions));
21475
21476 // Update the pending async work count for the current interactions.
21477 interactions.forEach(function (interaction) {
21478 interaction.__count++;
21479 });
21480 }
21481
21482 var subscriber = __subscriberRef.current;
21483 if (subscriber !== null) {
21484 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
21485 subscriber.onWorkScheduled(interactions, threadID);
21486 }
21487 }
21488 }
21489 }
21490 return root;
21491}
21492
21493// in a test-like environment, we want to warn if dispatchAction() is
21494// called outside of a TestUtils.act(...)/batchedUpdates/render call.
21495// so we have a a step counter for when we descend/ascend from
21496// act() calls, and test on it for when to warn
21497// It's a tuple with a single value. Look for shared/createAct to
21498// see how we change the value inside act() calls
21499
21500function warnIfNotCurrentlyActingUpdatesInDev$1(fiber) {
21501 {
21502 if (isBatchingUpdates === false && isRendering === false && ReactShouldWarnActingUpdates.current === false) {
21503 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));
21504 }
21505 }
21506}
21507
21508function scheduleWork$1(fiber, expirationTime) {
21509 var root = scheduleWorkToRoot(fiber, expirationTime);
21510 if (root === null) {
21511 {
21512 switch (fiber.tag) {
21513 case ClassComponent:
21514 warnAboutUpdateOnUnmounted(fiber, true);
21515 break;
21516 case FunctionComponent:
21517 case ForwardRef:
21518 case MemoComponent:
21519 case SimpleMemoComponent:
21520 warnAboutUpdateOnUnmounted(fiber, false);
21521 break;
21522 }
21523 }
21524 return;
21525 }
21526
21527 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
21528 // This is an interruption. (Used for performance tracking.)
21529 interruptedBy = fiber;
21530 resetStack();
21531 }
21532 markPendingPriorityLevel(root, expirationTime);
21533 if (
21534 // If we're in the render phase, we don't need to schedule this root
21535 // for an update, because we'll do it before we exit...
21536 !isWorking || isCommitting$1 ||
21537 // ...unless this is a different root than the one we're rendering.
21538 nextRoot !== root) {
21539 var rootExpirationTime = root.expirationTime;
21540 requestWork(root, rootExpirationTime);
21541 }
21542 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
21543 // Reset this back to zero so subsequent updates don't throw.
21544 nestedUpdateCount = 0;
21545 (function () {
21546 {
21547 {
21548 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.');
21549 }
21550 }
21551 })();
21552 }
21553 {
21554 if (isInPassiveEffectDEV && nestedPassiveEffectCountDEV > NESTED_PASSIVE_UPDATE_LIMIT) {
21555 nestedPassiveEffectCountDEV = 0;
21556 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.');
21557 }
21558 }
21559}
21560
21561function syncUpdates$1(fn, a, b, c, d) {
21562 var previousExpirationContext = expirationContext;
21563 expirationContext = Sync;
21564 try {
21565 return fn(a, b, c, d);
21566 } finally {
21567 expirationContext = previousExpirationContext;
21568 }
21569}
21570
21571// TODO: Everything below this is written as if it has been lifted to the
21572// renderers. I'll do this in a follow-up.
21573
21574// Linked-list of roots
21575var firstScheduledRoot = null;
21576var lastScheduledRoot = null;
21577
21578var callbackExpirationTime = NoWork;
21579var callbackID = void 0;
21580var isRendering = false;
21581var nextFlushedRoot = null;
21582var nextFlushedExpirationTime = NoWork;
21583var lowestPriorityPendingInteractiveExpirationTime = NoWork;
21584var hasUnhandledError = false;
21585var unhandledError = null;
21586
21587var isBatchingUpdates = false;
21588var isUnbatchingUpdates = false;
21589var isBatchingInteractiveUpdates = false;
21590
21591var completedBatches = null;
21592
21593var originalStartTimeMs = now$2();
21594var currentRendererTime = msToExpirationTime(originalStartTimeMs);
21595var currentSchedulerTime = currentRendererTime;
21596
21597// Use these to prevent an infinite loop of nested updates
21598var NESTED_UPDATE_LIMIT = 50;
21599var nestedUpdateCount = 0;
21600var lastCommittedRootDuringThisBatch = null;
21601
21602// Similar, but for useEffect infinite loops. These are DEV-only.
21603var NESTED_PASSIVE_UPDATE_LIMIT = 50;
21604var nestedPassiveEffectCountDEV = void 0;
21605var isInPassiveEffectDEV = void 0;
21606{
21607 nestedPassiveEffectCountDEV = 0;
21608 isInPassiveEffectDEV = false;
21609}
21610
21611function recomputeCurrentRendererTime() {
21612 var currentTimeMs = now$2() - originalStartTimeMs;
21613 currentRendererTime = msToExpirationTime(currentTimeMs);
21614}
21615
21616function scheduleCallbackWithExpirationTime(root, expirationTime) {
21617 if (callbackExpirationTime !== NoWork) {
21618 // A callback is already scheduled. Check its expiration time (timeout).
21619 if (expirationTime < callbackExpirationTime) {
21620 // Existing callback has sufficient timeout. Exit.
21621 return;
21622 } else {
21623 if (callbackID !== null) {
21624 // Existing callback has insufficient timeout. Cancel and schedule a
21625 // new one.
21626 cancelCallback$1(callbackID);
21627 }
21628 }
21629 // The request callback timer is already running. Don't start a new one.
21630 } else {
21631 startRequestCallbackTimer();
21632 }
21633
21634 callbackExpirationTime = expirationTime;
21635 var currentMs = now$2() - originalStartTimeMs;
21636 var expirationTimeMs = expirationTimeToMs(expirationTime);
21637 var timeout = expirationTimeMs - currentMs;
21638 var priorityLevel = getCurrentPriorityLevel$1();
21639 callbackID = scheduleCallback$1(priorityLevel, performAsyncWork, { timeout: timeout });
21640}
21641
21642// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
21643// onYield is called upon exiting. We use these in lieu of returning a tuple.
21644// I've also chosen not to inline them into renderRoot because these will
21645// eventually be lifted into the renderer.
21646function onFatal(root) {
21647 root.finishedWork = null;
21648}
21649
21650function onComplete(root, finishedWork, expirationTime) {
21651 root.pendingCommitExpirationTime = expirationTime;
21652 root.finishedWork = finishedWork;
21653}
21654
21655function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
21656 root.expirationTime = rootExpirationTime;
21657 if (msUntilTimeout === 0 && (disableYielding || !shouldYield$2())) {
21658 // Don't wait an additional tick. Commit the tree immediately.
21659 root.pendingCommitExpirationTime = suspendedExpirationTime;
21660 root.finishedWork = finishedWork;
21661 } else if (msUntilTimeout > 0) {
21662 // Wait `msUntilTimeout` milliseconds before committing.
21663 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
21664 }
21665}
21666
21667function onYield(root) {
21668 root.finishedWork = null;
21669}
21670
21671function onTimeout(root, finishedWork, suspendedExpirationTime) {
21672 // The root timed out. Commit it.
21673 root.pendingCommitExpirationTime = suspendedExpirationTime;
21674 root.finishedWork = finishedWork;
21675 // Read the current time before entering the commit phase. We can be
21676 // certain this won't cause tearing related to batching of event updates
21677 // because we're at the top of a timer event.
21678 recomputeCurrentRendererTime();
21679 currentSchedulerTime = currentRendererTime;
21680 flushRoot$1(root, suspendedExpirationTime);
21681}
21682
21683function onCommit(root, expirationTime) {
21684 root.expirationTime = expirationTime;
21685 root.finishedWork = null;
21686}
21687
21688function requestCurrentTime$1() {
21689 // requestCurrentTime is called by the scheduler to compute an expiration
21690 // time.
21691 //
21692 // Expiration times are computed by adding to the current time (the start
21693 // time). However, if two updates are scheduled within the same event, we
21694 // should treat their start times as simultaneous, even if the actual clock
21695 // time has advanced between the first and second call.
21696
21697 // In other words, because expiration times determine how updates are batched,
21698 // we want all updates of like priority that occur within the same event to
21699 // receive the same expiration time. Otherwise we get tearing.
21700 //
21701 // We keep track of two separate times: the current "renderer" time and the
21702 // current "scheduler" time. The renderer time can be updated whenever; it
21703 // only exists to minimize the calls performance.now.
21704 //
21705 // But the scheduler time can only be updated if there's no pending work, or
21706 // if we know for certain that we're not in the middle of an event.
21707
21708 if (isRendering) {
21709 // We're already rendering. Return the most recently read time.
21710 return currentSchedulerTime;
21711 }
21712 // Check if there's pending work.
21713 findHighestPriorityRoot();
21714 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
21715 // If there's no pending work, or if the pending work is offscreen, we can
21716 // read the current time without risk of tearing.
21717 recomputeCurrentRendererTime();
21718 currentSchedulerTime = currentRendererTime;
21719 return currentSchedulerTime;
21720 }
21721 // There's already pending work. We might be in the middle of a browser
21722 // event. If we were to read the current time, it could cause multiple updates
21723 // within the same event to receive different expiration times, leading to
21724 // tearing. Return the last read time. During the next idle callback, the
21725 // time will be updated.
21726 return currentSchedulerTime;
21727}
21728
21729// requestWork is called by the scheduler whenever a root receives an update.
21730// It's up to the renderer to call renderRoot at some point in the future.
21731function requestWork(root, expirationTime) {
21732 addRootToSchedule(root, expirationTime);
21733 if (isRendering) {
21734 // Prevent reentrancy. Remaining work will be scheduled at the end of
21735 // the currently rendering batch.
21736 return;
21737 }
21738
21739 if (isBatchingUpdates) {
21740 // Flush work at the end of the batch.
21741 if (isUnbatchingUpdates) {
21742 // ...unless we're inside unbatchedUpdates, in which case we should
21743 // flush it now.
21744 nextFlushedRoot = root;
21745 nextFlushedExpirationTime = Sync;
21746 performWorkOnRoot(root, Sync, false);
21747 }
21748 return;
21749 }
21750
21751 // TODO: Get rid of Sync and use current time?
21752 if (expirationTime === Sync) {
21753 performSyncWork();
21754 } else {
21755 scheduleCallbackWithExpirationTime(root, expirationTime);
21756 }
21757}
21758
21759function addRootToSchedule(root, expirationTime) {
21760 // Add the root to the schedule.
21761 // Check if this root is already part of the schedule.
21762 if (root.nextScheduledRoot === null) {
21763 // This root is not already scheduled. Add it.
21764 root.expirationTime = expirationTime;
21765 if (lastScheduledRoot === null) {
21766 firstScheduledRoot = lastScheduledRoot = root;
21767 root.nextScheduledRoot = root;
21768 } else {
21769 lastScheduledRoot.nextScheduledRoot = root;
21770 lastScheduledRoot = root;
21771 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
21772 }
21773 } else {
21774 // This root is already scheduled, but its priority may have increased.
21775 var remainingExpirationTime = root.expirationTime;
21776 if (expirationTime > remainingExpirationTime) {
21777 // Update the priority.
21778 root.expirationTime = expirationTime;
21779 }
21780 }
21781}
21782
21783function findHighestPriorityRoot() {
21784 var highestPriorityWork = NoWork;
21785 var highestPriorityRoot = null;
21786 if (lastScheduledRoot !== null) {
21787 var previousScheduledRoot = lastScheduledRoot;
21788 var root = firstScheduledRoot;
21789 while (root !== null) {
21790 var remainingExpirationTime = root.expirationTime;
21791 if (remainingExpirationTime === NoWork) {
21792 // This root no longer has work. Remove it from the scheduler.
21793
21794 // TODO: This check is redudant, but Flow is confused by the branch
21795 // below where we set lastScheduledRoot to null, even though we break
21796 // from the loop right after.
21797 (function () {
21798 if (!(previousScheduledRoot !== null && lastScheduledRoot !== null)) {
21799 {
21800 throw ReactError('Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.');
21801 }
21802 }
21803 })();
21804 if (root === root.nextScheduledRoot) {
21805 // This is the only root in the list.
21806 root.nextScheduledRoot = null;
21807 firstScheduledRoot = lastScheduledRoot = null;
21808 break;
21809 } else if (root === firstScheduledRoot) {
21810 // This is the first root in the list.
21811 var next = root.nextScheduledRoot;
21812 firstScheduledRoot = next;
21813 lastScheduledRoot.nextScheduledRoot = next;
21814 root.nextScheduledRoot = null;
21815 } else if (root === lastScheduledRoot) {
21816 // This is the last root in the list.
21817 lastScheduledRoot = previousScheduledRoot;
21818 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
21819 root.nextScheduledRoot = null;
21820 break;
21821 } else {
21822 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
21823 root.nextScheduledRoot = null;
21824 }
21825 root = previousScheduledRoot.nextScheduledRoot;
21826 } else {
21827 if (remainingExpirationTime > highestPriorityWork) {
21828 // Update the priority, if it's higher
21829 highestPriorityWork = remainingExpirationTime;
21830 highestPriorityRoot = root;
21831 }
21832 if (root === lastScheduledRoot) {
21833 break;
21834 }
21835 if (highestPriorityWork === Sync) {
21836 // Sync is highest priority by definition so
21837 // we can stop searching.
21838 break;
21839 }
21840 previousScheduledRoot = root;
21841 root = root.nextScheduledRoot;
21842 }
21843 }
21844 }
21845
21846 nextFlushedRoot = highestPriorityRoot;
21847 nextFlushedExpirationTime = highestPriorityWork;
21848}
21849
21850function performAsyncWork(didTimeout) {
21851 if (didTimeout) {
21852 // The callback timed out. That means at least one update has expired.
21853 // Iterate through the root schedule. If they contain expired work, set
21854 // the next render expiration time to the current time. This has the effect
21855 // of flushing all expired work in a single batch, instead of flushing each
21856 // level one at a time.
21857 if (firstScheduledRoot !== null) {
21858 recomputeCurrentRendererTime();
21859 var root = firstScheduledRoot;
21860 do {
21861 didExpireAtExpirationTime(root, currentRendererTime);
21862 // The root schedule is circular, so this is never null.
21863 root = root.nextScheduledRoot;
21864 } while (root !== firstScheduledRoot);
21865 }
21866 }
21867
21868 // Keep working on roots until there's no more work, or until there's a higher
21869 // priority event.
21870 findHighestPriorityRoot();
21871
21872 if (disableYielding) {
21873 // Just do it all
21874 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork) {
21875 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
21876 findHighestPriorityRoot();
21877 }
21878 } else {
21879 recomputeCurrentRendererTime();
21880 currentSchedulerTime = currentRendererTime;
21881
21882 if (enableUserTimingAPI) {
21883 var didExpire = nextFlushedExpirationTime > currentRendererTime;
21884 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
21885 stopRequestCallbackTimer(didExpire, timeout);
21886 }
21887
21888 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && !(shouldYield$2() && currentRendererTime > nextFlushedExpirationTime)) {
21889 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
21890 findHighestPriorityRoot();
21891 recomputeCurrentRendererTime();
21892 currentSchedulerTime = currentRendererTime;
21893 }
21894 }
21895
21896 // We're done flushing work. Either we ran out of time in this callback,
21897 // or there's no more work left with sufficient priority.
21898
21899 // If we're inside a callback, set this to false since we just completed it.
21900 callbackExpirationTime = NoWork;
21901 callbackID = null;
21902
21903 // If there's work left over, schedule a new callback.
21904 if (nextFlushedExpirationTime !== NoWork) {
21905 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
21906 }
21907
21908 // Clean-up.
21909 finishRendering();
21910}
21911
21912function performSyncWork() {
21913 performWork(Sync);
21914}
21915
21916function performWork(minExpirationTime) {
21917 // Keep working on roots until there's no more work, or until there's a higher
21918 // priority event.
21919 findHighestPriorityRoot();
21920
21921 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
21922 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
21923 findHighestPriorityRoot();
21924 }
21925
21926 // We're done flushing work. Either we ran out of time in this callback,
21927 // or there's no more work left with sufficient priority.
21928
21929 // If there's work left over, schedule a new callback.
21930 if (nextFlushedExpirationTime !== NoWork) {
21931 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
21932 }
21933
21934 // Clean-up.
21935 finishRendering();
21936}
21937
21938function flushRoot$1(root, expirationTime) {
21939 (function () {
21940 if (!!isRendering) {
21941 {
21942 throw ReactError('work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.');
21943 }
21944 }
21945 })();
21946 // Perform work on root as if the given expiration time is the current time.
21947 // This has the effect of synchronously flushing all work up to and
21948 // including the given time.
21949 nextFlushedRoot = root;
21950 nextFlushedExpirationTime = expirationTime;
21951 performWorkOnRoot(root, expirationTime, false);
21952 // Flush any sync work that was scheduled by lifecycles
21953 performSyncWork();
21954}
21955
21956function finishRendering() {
21957 nestedUpdateCount = 0;
21958 lastCommittedRootDuringThisBatch = null;
21959
21960 {
21961 if (rootWithPendingPassiveEffects === null) {
21962 nestedPassiveEffectCountDEV = 0;
21963 }
21964 }
21965
21966 if (completedBatches !== null) {
21967 var batches = completedBatches;
21968 completedBatches = null;
21969 for (var i = 0; i < batches.length; i++) {
21970 var batch = batches[i];
21971 try {
21972 batch._onComplete();
21973 } catch (error) {
21974 if (!hasUnhandledError) {
21975 hasUnhandledError = true;
21976 unhandledError = error;
21977 }
21978 }
21979 }
21980 }
21981
21982 if (hasUnhandledError) {
21983 var error = unhandledError;
21984 unhandledError = null;
21985 hasUnhandledError = false;
21986 throw error;
21987 }
21988}
21989
21990function performWorkOnRoot(root, expirationTime, isYieldy) {
21991 (function () {
21992 if (!!isRendering) {
21993 {
21994 throw ReactError('performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
21995 }
21996 }
21997 })();
21998
21999 isRendering = true;
22000
22001 // Check if this is async work or sync/expired work.
22002 if (!isYieldy) {
22003 // Flush work without yielding.
22004 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
22005 // may want to perform some work without yielding, but also without
22006 // requiring the root to complete (by triggering placeholders).
22007
22008 var finishedWork = root.finishedWork;
22009 if (finishedWork !== null) {
22010 // This root is already complete. We can commit it.
22011 completeRoot(root, finishedWork, expirationTime);
22012 } else {
22013 root.finishedWork = null;
22014 // If this root previously suspended, clear its existing timeout, since
22015 // we're about to try rendering again.
22016 var timeoutHandle = root.timeoutHandle;
22017 if (timeoutHandle !== noTimeout) {
22018 root.timeoutHandle = noTimeout;
22019 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22020 cancelTimeout(timeoutHandle);
22021 }
22022 renderRoot(root, isYieldy);
22023 finishedWork = root.finishedWork;
22024 if (finishedWork !== null) {
22025 // We've completed the root. Commit it.
22026 completeRoot(root, finishedWork, expirationTime);
22027 }
22028 }
22029 } else {
22030 // Flush async work.
22031 var _finishedWork = root.finishedWork;
22032 if (_finishedWork !== null) {
22033 // This root is already complete. We can commit it.
22034 completeRoot(root, _finishedWork, expirationTime);
22035 } else {
22036 root.finishedWork = null;
22037 // If this root previously suspended, clear its existing timeout, since
22038 // we're about to try rendering again.
22039 var _timeoutHandle = root.timeoutHandle;
22040 if (_timeoutHandle !== noTimeout) {
22041 root.timeoutHandle = noTimeout;
22042 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22043 cancelTimeout(_timeoutHandle);
22044 }
22045 renderRoot(root, isYieldy);
22046 _finishedWork = root.finishedWork;
22047 if (_finishedWork !== null) {
22048 // We've completed the root. Check the if we should yield one more time
22049 // before committing.
22050 if (!shouldYield$2()) {
22051 // Still time left. Commit the root.
22052 completeRoot(root, _finishedWork, expirationTime);
22053 } else {
22054 // There's no time left. Mark this root as complete. We'll come
22055 // back and commit it later.
22056 root.finishedWork = _finishedWork;
22057 }
22058 }
22059 }
22060 }
22061
22062 isRendering = false;
22063}
22064
22065function completeRoot(root, finishedWork, expirationTime) {
22066 // Check if there's a batch that matches this expiration time.
22067 var firstBatch = root.firstBatch;
22068 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
22069 if (completedBatches === null) {
22070 completedBatches = [firstBatch];
22071 } else {
22072 completedBatches.push(firstBatch);
22073 }
22074 if (firstBatch._defer) {
22075 // This root is blocked from committing by a batch. Unschedule it until
22076 // we receive another update.
22077 root.finishedWork = finishedWork;
22078 root.expirationTime = NoWork;
22079 return;
22080 }
22081 }
22082
22083 // Commit the root.
22084 root.finishedWork = null;
22085
22086 // Check if this is a nested update (a sync update scheduled during the
22087 // commit phase).
22088 if (root === lastCommittedRootDuringThisBatch) {
22089 // If the next root is the same as the previous root, this is a nested
22090 // update. To prevent an infinite loop, increment the nested update count.
22091 nestedUpdateCount++;
22092 } else {
22093 // Reset whenever we switch roots.
22094 lastCommittedRootDuringThisBatch = root;
22095 nestedUpdateCount = 0;
22096 }
22097 commitRoot(root, finishedWork);
22098}
22099
22100function onUncaughtError$1(error) {
22101 (function () {
22102 if (!(nextFlushedRoot !== null)) {
22103 {
22104 throw ReactError('Should be working on a root. This error is likely caused by a bug in React. Please file an issue.');
22105 }
22106 }
22107 })();
22108 // Unschedule this root so we don't work on it again until there's
22109 // another update.
22110 nextFlushedRoot.expirationTime = NoWork;
22111 if (!hasUnhandledError) {
22112 hasUnhandledError = true;
22113 unhandledError = error;
22114 }
22115}
22116
22117// TODO: Batching should be implemented at the renderer level, not inside
22118// the reconciler.
22119function batchedUpdates$2(fn, a) {
22120 var previousIsBatchingUpdates = isBatchingUpdates;
22121 isBatchingUpdates = true;
22122 try {
22123 return fn(a);
22124 } finally {
22125 isBatchingUpdates = previousIsBatchingUpdates;
22126 if (!isBatchingUpdates && !isRendering) {
22127 performSyncWork();
22128 }
22129 }
22130}
22131
22132// TODO: Batching should be implemented at the renderer level, not inside
22133// the reconciler.
22134function unbatchedUpdates$1(fn, a) {
22135 if (isBatchingUpdates && !isUnbatchingUpdates) {
22136 isUnbatchingUpdates = true;
22137 try {
22138 return fn(a);
22139 } finally {
22140 isUnbatchingUpdates = false;
22141 }
22142 }
22143 return fn(a);
22144}
22145
22146// TODO: Batching should be implemented at the renderer level, not within
22147// the reconciler.
22148function flushSync$1(fn, a) {
22149 (function () {
22150 if (!!isRendering) {
22151 {
22152 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
22153 }
22154 }
22155 })();
22156 var previousIsBatchingUpdates = isBatchingUpdates;
22157 isBatchingUpdates = true;
22158 try {
22159 return syncUpdates$1(fn, a);
22160 } finally {
22161 isBatchingUpdates = previousIsBatchingUpdates;
22162 performSyncWork();
22163 }
22164}
22165
22166function interactiveUpdates$2(fn, a, b, c) {
22167 if (isBatchingInteractiveUpdates) {
22168 return fn(a, b, c);
22169 }
22170 // If there are any pending interactive updates, synchronously flush them.
22171 // This needs to happen before we read any handlers, because the effect of
22172 // the previous event may influence which handlers are called during
22173 // this event.
22174 if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
22175 // Synchronously flush pending interactive updates.
22176 performWork(lowestPriorityPendingInteractiveExpirationTime);
22177 lowestPriorityPendingInteractiveExpirationTime = NoWork;
22178 }
22179 var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates;
22180 var previousIsBatchingUpdates = isBatchingUpdates;
22181 isBatchingInteractiveUpdates = true;
22182 isBatchingUpdates = true;
22183 try {
22184 return fn(a, b, c);
22185 } finally {
22186 isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates;
22187 isBatchingUpdates = previousIsBatchingUpdates;
22188 if (!isBatchingUpdates && !isRendering) {
22189 performSyncWork();
22190 }
22191 }
22192}
22193
22194function flushInteractiveUpdates$2() {
22195 if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) {
22196 // Synchronously flush pending interactive updates.
22197 performWork(lowestPriorityPendingInteractiveExpirationTime);
22198 lowestPriorityPendingInteractiveExpirationTime = NoWork;
22199 }
22200}
22201
22202function flushControlled$1(fn) {
22203 var previousIsBatchingUpdates = isBatchingUpdates;
22204 isBatchingUpdates = true;
22205 try {
22206 syncUpdates$1(fn);
22207 } finally {
22208 isBatchingUpdates = previousIsBatchingUpdates;
22209 if (!isBatchingUpdates && !isRendering) {
22210 performSyncWork();
22211 }
22212 }
22213}
22214
22215// TODO: Ahaha Andrew is bad at spellling
22216// DEV stuff
22217var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher;
22218var ReactCurrentOwner$4 = ReactSharedInternals.ReactCurrentOwner;
22219var ReactShouldWarnActingUpdates$1 = ReactSharedInternals.ReactShouldWarnActingUpdates;
22220
22221var NotWorking = 0;
22222var BatchedPhase = 1;
22223var LegacyUnbatchedPhase = 2;
22224var FlushSyncPhase = 3;
22225var RenderPhase = 4;
22226var CommitPhase = 5;
22227
22228var RootIncomplete = 0;
22229var RootErrored = 1;
22230var RootSuspended = 2;
22231var RootCompleted = 3;
22232
22233// The phase of work we're currently in
22234var workPhase = NotWorking;
22235// The root we're working on
22236var workInProgressRoot = null;
22237// The fiber we're working on
22238var workInProgress = null;
22239// The expiration time we're rendering
22240var renderExpirationTime$1 = NoWork;
22241// Whether to root completed, errored, suspended, etc.
22242var workInProgressRootExitStatus = RootIncomplete;
22243var workInProgressRootAbsoluteTimeoutMs = -1;
22244
22245var nextEffect$1 = null;
22246var hasUncaughtError = false;
22247var firstUncaughtError = null;
22248var legacyErrorBoundariesThatAlreadyFailed$1 = null;
22249
22250var rootDoesHavePassiveEffects = false;
22251var rootWithPendingPassiveEffects$1 = null;
22252var pendingPassiveEffectsExpirationTime = NoWork;
22253
22254var rootsWithPendingDiscreteUpdates = null;
22255
22256// Use these to prevent an infinite loop of nested updates
22257var NESTED_UPDATE_LIMIT$1 = 50;
22258var nestedUpdateCount$1 = 0;
22259var rootWithNestedUpdates = null;
22260
22261var NESTED_PASSIVE_UPDATE_LIMIT$1 = 50;
22262var nestedPassiveUpdateCount = 0;
22263
22264var interruptedBy$1 = null;
22265
22266// Expiration times are computed by adding to the current time (the start
22267// time). However, if two updates are scheduled within the same event, we
22268// should treat their start times as simultaneous, even if the actual clock
22269// time has advanced between the first and second call.
22270
22271// In other words, because expiration times determine how updates are batched,
22272// we want all updates of like priority that occur within the same event to
22273// receive the same expiration time. Otherwise we get tearing.
22274var currentEventTime = NoWork;
22275
22276function requestCurrentTime$2() {
22277 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22278 // We're inside React, so it's fine to read the actual time.
22279 return msToExpirationTime(now$1());
22280 }
22281 // We're not inside React, so we may be in the middle of a browser event.
22282 if (currentEventTime !== NoWork) {
22283 // Use the same start time for all updates until we enter React again.
22284 return currentEventTime;
22285 }
22286 // This is the first update since React yielded. Compute a new start time.
22287 currentEventTime = msToExpirationTime(now$1());
22288 return currentEventTime;
22289}
22290
22291function computeExpirationForFiber$2(currentTime, fiber) {
22292 if ((fiber.mode & ConcurrentMode) === NoContext) {
22293 return Sync;
22294 }
22295
22296 if (workPhase === RenderPhase) {
22297 // Use whatever time we're already rendering
22298 return renderExpirationTime$1;
22299 }
22300
22301 // Compute an expiration time based on the Scheduler priority.
22302 var expirationTime = void 0;
22303 var priorityLevel = getCurrentPriorityLevel();
22304 switch (priorityLevel) {
22305 case ImmediatePriority:
22306 expirationTime = Sync;
22307 break;
22308 case UserBlockingPriority:
22309 // TODO: Rename this to computeUserBlockingExpiration
22310 expirationTime = computeInteractiveExpiration(currentTime);
22311 break;
22312 case NormalPriority:
22313 case LowPriority:
22314 // TODO: Handle LowPriority
22315 // TODO: Rename this to... something better.
22316 expirationTime = computeAsyncExpiration(currentTime);
22317 break;
22318 case IdlePriority:
22319 expirationTime = Never;
22320 break;
22321 default:
22322 (function () {
22323 {
22324 {
22325 throw ReactError('Expected a valid priority level');
22326 }
22327 }
22328 })();
22329 }
22330
22331 // If we're in the middle of rendering a tree, do not update at the same
22332 // expiration time that is already rendering.
22333 if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {
22334 // This is a trick to move this update into a separate batch
22335 expirationTime -= 1;
22336 }
22337
22338 return expirationTime;
22339}
22340
22341var lastUniqueAsyncExpiration$1 = NoWork;
22342function computeUniqueAsyncExpiration$2() {
22343 var currentTime = requestCurrentTime$2();
22344 var result = computeAsyncExpiration(currentTime);
22345 if (result <= lastUniqueAsyncExpiration$1) {
22346 // Since we assume the current time monotonically increases, we only hit
22347 // this branch when computeUniqueAsyncExpiration is fired multiple times
22348 // within a 200ms window (or whatever the async bucket size is).
22349 result -= 1;
22350 }
22351 lastUniqueAsyncExpiration$1 = result;
22352 return result;
22353}
22354
22355function scheduleUpdateOnFiber(fiber, expirationTime) {
22356 checkForNestedUpdates();
22357 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
22358
22359 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
22360 if (root === null) {
22361 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
22362 return;
22363 }
22364
22365 root.pingTime = NoWork;
22366
22367 checkForInterruption(fiber, expirationTime);
22368 recordScheduleUpdate();
22369
22370 if (expirationTime === Sync) {
22371 if (workPhase === LegacyUnbatchedPhase) {
22372 // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
22373 // root inside of batchedUpdates should be synchronous, but layout updates
22374 // should be deferred until the end of the batch.
22375 var callback = renderRoot$1(root, Sync, true);
22376 while (callback !== null) {
22377 callback = callback(true);
22378 }
22379 } else {
22380 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
22381 if (workPhase === NotWorking) {
22382 // Flush the synchronous work now, wnless we're already working or inside
22383 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
22384 // scheduleCallbackForFiber to preserve the ability to schedule a callback
22385 // without immediately flushing it. We only do this for user-initated
22386 // updates, to preserve historical behavior of sync mode.
22387 flushImmediateQueue();
22388 }
22389 }
22390 } else {
22391 // TODO: computeExpirationForFiber also reads the priority. Pass the
22392 // priority as an argument to that function and this one.
22393 var priorityLevel = getCurrentPriorityLevel();
22394 if (priorityLevel === UserBlockingPriority) {
22395 // This is the result of a discrete event. Track the lowest priority
22396 // discrete update per root so we can flush them early, if needed.
22397 if (rootsWithPendingDiscreteUpdates === null) {
22398 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
22399 } else {
22400 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
22401 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
22402 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
22403 }
22404 }
22405 }
22406 scheduleCallbackForRoot(root, priorityLevel, expirationTime);
22407 }
22408}
22409var scheduleWork$2 = scheduleUpdateOnFiber;
22410
22411// This is split into a separate function so we can mark a fiber with pending
22412// work without treating it as a typical update that originates from an event;
22413// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
22414// on a fiber.
22415function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
22416 // Update the source fiber's expiration time
22417 if (fiber.expirationTime < expirationTime) {
22418 fiber.expirationTime = expirationTime;
22419 }
22420 var alternate = fiber.alternate;
22421 if (alternate !== null && alternate.expirationTime < expirationTime) {
22422 alternate.expirationTime = expirationTime;
22423 }
22424 // Walk the parent path to the root and update the child expiration time.
22425 var node = fiber.return;
22426 var root = null;
22427 if (node === null && fiber.tag === HostRoot) {
22428 root = fiber.stateNode;
22429 } else {
22430 while (node !== null) {
22431 alternate = node.alternate;
22432 if (node.childExpirationTime < expirationTime) {
22433 node.childExpirationTime = expirationTime;
22434 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
22435 alternate.childExpirationTime = expirationTime;
22436 }
22437 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
22438 alternate.childExpirationTime = expirationTime;
22439 }
22440 if (node.return === null && node.tag === HostRoot) {
22441 root = node.stateNode;
22442 break;
22443 }
22444 node = node.return;
22445 }
22446 }
22447
22448 if (root !== null) {
22449 // Update the first and last pending expiration times in this root
22450 var firstPendingTime = root.firstPendingTime;
22451 if (expirationTime > firstPendingTime) {
22452 root.firstPendingTime = expirationTime;
22453 }
22454 var lastPendingTime = root.lastPendingTime;
22455 if (lastPendingTime === NoWork || expirationTime < lastPendingTime) {
22456 root.lastPendingTime = expirationTime;
22457 }
22458 }
22459
22460 return root;
22461}
22462
22463// Use this function, along with runRootCallback, to ensure that only a single
22464// callback per root is scheduled. It's still possible to call renderRoot
22465// directly, but scheduling via this function helps avoid excessive callbacks.
22466// It works by storing the callback node and expiration time on the root. When a
22467// new callback comes in, it compares the expiration time to determine if it
22468// should cancel the previous one. It also relies on commitRoot scheduling a
22469// callback to render the next level, because that means we don't need a
22470// separate callback per expiration time.
22471function scheduleCallbackForRoot(root, priorityLevel, expirationTime) {
22472 var existingCallbackExpirationTime = root.callbackExpirationTime;
22473 if (existingCallbackExpirationTime < expirationTime) {
22474 // New callback has higher priority than the existing one.
22475 var existingCallbackNode = root.callbackNode;
22476 if (existingCallbackNode !== null) {
22477 cancelCallback(existingCallbackNode);
22478 }
22479 root.callbackExpirationTime = expirationTime;
22480 var options = expirationTime === Sync ? null : { timeout: expirationTimeToMs(expirationTime) };
22481 root.callbackNode = scheduleCallback(priorityLevel, runRootCallback.bind(null, root, renderRoot$1.bind(null, root, expirationTime)), options);
22482 if (enableUserTimingAPI && expirationTime !== Sync && workPhase !== RenderPhase && workPhase !== CommitPhase) {
22483 // Scheduled an async callback, and we're not already working. Add an
22484 // entry to the flamegraph that shows we're waiting for a callback
22485 // to fire.
22486 startRequestCallbackTimer();
22487 }
22488 }
22489
22490 var timeoutHandle = root.timeoutHandle;
22491 if (timeoutHandle !== noTimeout) {
22492 // The root previous suspended and scheduled a timeout to commit a fallback
22493 // state. Now that we have additional work, cancel the timeout.
22494 root.timeoutHandle = noTimeout;
22495 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
22496 cancelTimeout(timeoutHandle);
22497 }
22498
22499 // Add the current set of interactions to the pending set associated with
22500 // this root.
22501 schedulePendingInteraction(root, expirationTime);
22502}
22503
22504function runRootCallback(root, callback, isSync) {
22505 var prevCallbackNode = root.callbackNode;
22506 var continuation = null;
22507 try {
22508 continuation = callback(isSync);
22509 if (continuation !== null) {
22510 return runRootCallback.bind(null, root, continuation);
22511 } else {
22512 return null;
22513 }
22514 } finally {
22515 // If the callback exits without returning a continuation, remove the
22516 // corresponding callback node from the root. Unless the callback node
22517 // has changed, which implies that it was already cancelled by a high
22518 // priority update.
22519 if (continuation === null && prevCallbackNode === root.callbackNode) {
22520 root.callbackNode = null;
22521 root.callbackExpirationTime = NoWork;
22522 }
22523 }
22524}
22525
22526function flushRoot$2(root, expirationTime) {
22527 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22528 (function () {
22529 {
22530 {
22531 throw ReactError('work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.');
22532 }
22533 }
22534 })();
22535 }
22536 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22537 flushImmediateQueue();
22538}
22539
22540function flushInteractiveUpdates$3() {
22541 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22542 // Can't synchronously flush interactive updates if React is already
22543 // working. This is currently a no-op.
22544 // TODO: Should we fire a warning? This happens if you synchronously invoke
22545 // an input event inside an effect, like with `element.click()`.
22546 return;
22547 }
22548 flushPendingDiscreteUpdates();
22549}
22550
22551function resolveLocksOnRoot(root, expirationTime) {
22552 var firstBatch = root.firstBatch;
22553 if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
22554 root.finishedWork = root.current.alternate;
22555 root.pendingCommitExpirationTime = expirationTime;
22556 scheduleCallback(NormalPriority, function () {
22557 firstBatch._onComplete();
22558 return null;
22559 });
22560 return true;
22561 } else {
22562 return false;
22563 }
22564}
22565
22566
22567
22568function interactiveUpdates$3(fn, a, b, c) {
22569 if (workPhase === NotWorking) {
22570 // TODO: Remove this call. Instead of doing this automatically, the caller
22571 // should explicitly call flushInteractiveUpdates.
22572 flushPendingDiscreteUpdates();
22573 }
22574 return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c));
22575}
22576
22577
22578
22579function flushPendingDiscreteUpdates() {
22580 if (rootsWithPendingDiscreteUpdates !== null) {
22581 // For each root with pending discrete updates, schedule a callback to
22582 // immediately flush them.
22583 var roots = rootsWithPendingDiscreteUpdates;
22584 rootsWithPendingDiscreteUpdates = null;
22585 roots.forEach(function (expirationTime, root) {
22586 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22587 });
22588 // Now flush the immediate queue.
22589 flushImmediateQueue();
22590 }
22591}
22592
22593function batchedUpdates$3(fn, a) {
22594 if (workPhase !== NotWorking) {
22595 // We're already working, or inside a batch, so batchedUpdates is a no-op.
22596 return fn(a);
22597 }
22598 workPhase = BatchedPhase;
22599 try {
22600 return fn(a);
22601 } finally {
22602 workPhase = NotWorking;
22603 // Flush the immediate callbacks that were scheduled during this batch
22604 flushImmediateQueue();
22605 }
22606}
22607
22608function unbatchedUpdates$2(fn, a) {
22609 if (workPhase !== BatchedPhase && workPhase !== FlushSyncPhase) {
22610 // We're not inside batchedUpdates or flushSync, so unbatchedUpdates is
22611 // a no-op.
22612 return fn(a);
22613 }
22614 var prevWorkPhase = workPhase;
22615 workPhase = LegacyUnbatchedPhase;
22616 try {
22617 return fn(a);
22618 } finally {
22619 workPhase = prevWorkPhase;
22620 }
22621}
22622
22623function flushSync$2(fn, a) {
22624 if (workPhase === RenderPhase || workPhase === CommitPhase) {
22625 (function () {
22626 {
22627 {
22628 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
22629 }
22630 }
22631 })();
22632 }
22633 var prevWorkPhase = workPhase;
22634 workPhase = FlushSyncPhase;
22635 try {
22636 return runWithPriority(ImmediatePriority, fn.bind(null, a));
22637 } finally {
22638 workPhase = prevWorkPhase;
22639 // Flush the immediate callbacks that were scheduled during this batch.
22640 // Note that this will happen even if batchedUpdates is higher up
22641 // the stack.
22642 flushImmediateQueue();
22643 }
22644}
22645
22646function flushControlled$2(fn) {
22647 var prevWorkPhase = workPhase;
22648 workPhase = BatchedPhase;
22649 try {
22650 runWithPriority(ImmediatePriority, fn);
22651 } finally {
22652 workPhase = prevWorkPhase;
22653 if (workPhase === NotWorking) {
22654 // Flush the immediate callbacks that were scheduled during this batch
22655 flushImmediateQueue();
22656 }
22657 }
22658}
22659
22660function prepareFreshStack(root, expirationTime) {
22661 root.pendingCommitExpirationTime = NoWork;
22662
22663 if (workInProgress !== null) {
22664 var interruptedWork = workInProgress.return;
22665 while (interruptedWork !== null) {
22666 unwindInterruptedWork(interruptedWork);
22667 interruptedWork = interruptedWork.return;
22668 }
22669 }
22670 workInProgressRoot = root;
22671 workInProgress = createWorkInProgress(root.current, null, expirationTime);
22672 renderExpirationTime$1 = expirationTime;
22673 workInProgressRootExitStatus = RootIncomplete;
22674 workInProgressRootAbsoluteTimeoutMs = -1;
22675
22676 {
22677 ReactStrictModeWarnings.discardPendingWarnings();
22678 }
22679}
22680
22681function renderRoot$1(root, expirationTime, isSync) {
22682 (function () {
22683 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
22684 {
22685 throw ReactError('Should not already be working.');
22686 }
22687 }
22688 })();
22689
22690 if (enableUserTimingAPI && expirationTime !== Sync) {
22691 var didExpire = isSync;
22692 var timeoutMs = expirationTimeToMs(expirationTime);
22693 stopRequestCallbackTimer(didExpire, timeoutMs);
22694 }
22695
22696 if (root.firstPendingTime < expirationTime) {
22697 // If there's no work left at this expiration time, exit immediately. This
22698 // happens when multiple callbacks are scheduled for a single root, but an
22699 // earlier callback flushes the work of a later one.
22700 return null;
22701 }
22702
22703 if (root.pendingCommitExpirationTime === expirationTime) {
22704 // There's already a pending commit at this expiration time.
22705 root.pendingCommitExpirationTime = NoWork;
22706 return commitRoot$1.bind(null, root, expirationTime);
22707 }
22708
22709 flushPassiveEffects$2();
22710
22711 // If the root or expiration time have changed, throw out the existing stack
22712 // and prepare a fresh one. Otherwise we'll continue where we left off.
22713 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
22714 prepareFreshStack(root, expirationTime);
22715 startWorkOnPendingInteraction(root, expirationTime);
22716 }
22717
22718 // If we have a work-in-progress fiber, it means there's still work to do
22719 // in this root.
22720 if (workInProgress !== null) {
22721 var prevWorkPhase = workPhase;
22722 workPhase = RenderPhase;
22723 var prevDispatcher = ReactCurrentDispatcher$2.current;
22724 if (prevDispatcher === null) {
22725 // The React isomorphic package does not include a default dispatcher.
22726 // Instead the first renderer will lazily attach one, in order to give
22727 // nicer error messages.
22728 prevDispatcher = ContextOnlyDispatcher;
22729 }
22730 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
22731 var prevInteractions = null;
22732 if (enableSchedulerTracing) {
22733 prevInteractions = __interactionsRef.current;
22734 __interactionsRef.current = root.memoizedInteractions;
22735 }
22736
22737 startWorkLoopTimer(workInProgress);
22738 do {
22739 try {
22740 if (isSync) {
22741 if (expirationTime !== Sync) {
22742 // An async update expired. There may be other expired updates on
22743 // this root. We should render all the expired work in a
22744 // single batch.
22745 var currentTime = requestCurrentTime$2();
22746 if (currentTime < expirationTime) {
22747 // Restart at the current time.
22748 workPhase = prevWorkPhase;
22749 ReactCurrentDispatcher$2.current = prevDispatcher;
22750 return renderRoot$1.bind(null, root, currentTime);
22751 }
22752 }
22753 workLoopSync();
22754 } else {
22755 // Since we know we're in a React event, we can clear the current
22756 // event time. The next update will compute a new event time.
22757 currentEventTime = NoWork;
22758 workLoop$1();
22759 }
22760 break;
22761 } catch (thrownValue) {
22762 // Reset module-level state that was set during the render phase.
22763 resetContextDependences();
22764 resetHooks();
22765
22766 var sourceFiber = workInProgress;
22767 if (sourceFiber === null || sourceFiber.return === null) {
22768 // Expected to be working on a non-root fiber. This is a fatal error
22769 // because there's no ancestor that can handle it; the root is
22770 // supposed to capture all errors that weren't caught by an error
22771 // boundary.
22772 prepareFreshStack(root, expirationTime);
22773 workPhase = prevWorkPhase;
22774 throw thrownValue;
22775 }
22776
22777 if (enableProfilerTimer && sourceFiber.mode & ProfileMode) {
22778 // Record the time spent rendering before an error was thrown. This
22779 // avoids inaccurate Profiler durations in the case of a
22780 // suspended render.
22781 stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true);
22782 }
22783
22784 var returnFiber = sourceFiber.return;
22785 throwException(root, returnFiber, sourceFiber, thrownValue, renderExpirationTime$1);
22786 workInProgress = completeUnitOfWork$1(sourceFiber);
22787 }
22788 } while (true);
22789
22790 workPhase = prevWorkPhase;
22791 resetContextDependences();
22792 ReactCurrentDispatcher$2.current = prevDispatcher;
22793 if (enableSchedulerTracing) {
22794 __interactionsRef.current = prevInteractions;
22795 }
22796
22797 if (workInProgress !== null) {
22798 // There's still work left over. Return a continuation.
22799 stopInterruptedWorkLoopTimer();
22800 if (expirationTime !== Sync) {
22801 startRequestCallbackTimer();
22802 }
22803 return renderRoot$1.bind(null, root, expirationTime);
22804 }
22805 }
22806
22807 // We now have a consistent tree. The next step is either to commit it, or, if
22808 // something suspended, wait to commit it after a timeout.
22809 stopFinishedWorkLoopTimer();
22810
22811 var isLocked = resolveLocksOnRoot(root, expirationTime);
22812 if (isLocked) {
22813 // This root has a lock that prevents it from committing. Exit. If we begin
22814 // work on the root again, without any intervening updates, it will finish
22815 // without doing additional work.
22816 return null;
22817 }
22818
22819 // Set this to null to indicate there's no in-progress render.
22820 workInProgressRoot = null;
22821
22822 switch (workInProgressRootExitStatus) {
22823 case RootIncomplete:
22824 {
22825 (function () {
22826 {
22827 {
22828 throw ReactError('Should have a work-in-progress.');
22829 }
22830 }
22831 })();
22832 }
22833 // Flow knows about invariant, so it compains if I add a break statement,
22834 // but eslint doesn't know about invariant, so it complains if I do.
22835 // eslint-disable-next-line no-fallthrough
22836 case RootErrored:
22837 {
22838 // An error was thrown. First check if there is lower priority work
22839 // scheduled on this root.
22840 var lastPendingTime = root.lastPendingTime;
22841 if (root.lastPendingTime < expirationTime) {
22842 // There's lower priority work. Before raising the error, try rendering
22843 // at the lower priority to see if it fixes it. Use a continuation to
22844 // maintain the existing priority and position in the queue.
22845 return renderRoot$1.bind(null, root, lastPendingTime);
22846 }
22847 if (!isSync) {
22848 // If we're rendering asynchronously, it's possible the error was
22849 // caused by tearing due to a mutation during an event. Try rendering
22850 // one more time without yiedling to events.
22851 prepareFreshStack(root, expirationTime);
22852 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
22853 return null;
22854 }
22855 // If we're already rendering synchronously, commit the root in its
22856 // errored state.
22857 return commitRoot$1.bind(null, root, expirationTime);
22858 }
22859 case RootSuspended:
22860 {
22861 var _lastPendingTime = root.lastPendingTime;
22862 if (root.lastPendingTime < expirationTime) {
22863 // There's lower priority work. It might be unsuspended. Try rendering
22864 // at that level.
22865 return renderRoot$1.bind(null, root, _lastPendingTime);
22866 }
22867 if (!isSync) {
22868 var msUntilTimeout = computeMsUntilTimeout(root, workInProgressRootAbsoluteTimeoutMs);
22869 if (msUntilTimeout > 0) {
22870 // The render is suspended, it hasn't timed out, and there's no lower
22871 // priority work to do. Instead of committing the fallback
22872 // immediately, wait for more data to arrive.
22873 root.timeoutHandle = scheduleTimeout(commitRoot$1.bind(null, root, expirationTime), msUntilTimeout);
22874 return null;
22875 }
22876 }
22877 // The work expired. Commit immediately.
22878 return commitRoot$1.bind(null, root, expirationTime);
22879 }
22880 case RootCompleted:
22881 {
22882 // The work completed. Ready to commit.
22883 return commitRoot$1.bind(null, root, expirationTime);
22884 }
22885 default:
22886 {
22887 (function () {
22888 {
22889 {
22890 throw ReactError('Unknown root exit status.');
22891 }
22892 }
22893 })();
22894 }
22895 }
22896}
22897
22898function renderDidSuspend$2(root, absoluteTimeoutMs,
22899// TODO: Don't need this argument anymore
22900suspendedTime) {
22901 if (absoluteTimeoutMs >= 0 && workInProgressRootAbsoluteTimeoutMs < absoluteTimeoutMs) {
22902 workInProgressRootAbsoluteTimeoutMs = absoluteTimeoutMs;
22903 if (workInProgressRootExitStatus === RootIncomplete) {
22904 workInProgressRootExitStatus = RootSuspended;
22905 }
22906 }
22907}
22908
22909function renderDidError$2() {
22910 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
22911 workInProgressRootExitStatus = RootErrored;
22912 }
22913}
22914
22915function workLoopSync() {
22916 // Already timed out, so perform work without checking if we need to yield.
22917 while (workInProgress !== null) {
22918 workInProgress = performUnitOfWork$1(workInProgress);
22919 }
22920}
22921
22922function workLoop$1() {
22923 // Perform work until Scheduler asks us to yield
22924 while (workInProgress !== null && !shouldYield$1()) {
22925 workInProgress = performUnitOfWork$1(workInProgress);
22926 }
22927}
22928
22929function performUnitOfWork$1(unitOfWork) {
22930 // The current, flushed, state of this fiber is the alternate. Ideally
22931 // nothing should rely on this, but relying on it here means that we don't
22932 // need an additional field on the work in progress.
22933 var current$$1 = unitOfWork.alternate;
22934
22935 startWorkTimer(unitOfWork);
22936 setCurrentFiber(unitOfWork);
22937
22938 var next = void 0;
22939 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) {
22940 startProfilerTimer(unitOfWork);
22941 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
22942 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22943 } else {
22944 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
22945 }
22946
22947 resetCurrentFiber();
22948 unitOfWork.memoizedProps = unitOfWork.pendingProps;
22949 if (next === null) {
22950 // If this doesn't spawn new work, complete the current work.
22951 next = completeUnitOfWork$1(unitOfWork);
22952 }
22953
22954 ReactCurrentOwner$4.current = null;
22955 return next;
22956}
22957
22958function completeUnitOfWork$1(unitOfWork) {
22959 // Attempt to complete the current unit of work, then move to the next
22960 // sibling. If there are no more siblings, return to the parent fiber.
22961 workInProgress = unitOfWork;
22962 do {
22963 // The current, flushed, state of this fiber is the alternate. Ideally
22964 // nothing should rely on this, but relying on it here means that we don't
22965 // need an additional field on the work in progress.
22966 var current$$1 = workInProgress.alternate;
22967 var returnFiber = workInProgress.return;
22968
22969 // Check if the work completed or if something threw.
22970 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
22971 setCurrentFiber(workInProgress);
22972 var next = void 0;
22973 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoContext) {
22974 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
22975 } else {
22976 startProfilerTimer(workInProgress);
22977 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
22978 // Update render duration assuming we didn't error.
22979 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
22980 }
22981 stopWorkTimer(workInProgress);
22982 resetCurrentFiber();
22983 resetChildExpirationTime$1(workInProgress);
22984
22985 if (next !== null) {
22986 // Completing this fiber spawned new work. Work on that next.
22987 return next;
22988 }
22989
22990 if (returnFiber !== null &&
22991 // Do not append effects to parents if a sibling failed to complete
22992 (returnFiber.effectTag & Incomplete) === NoEffect) {
22993 // Append all the effects of the subtree and this fiber onto the effect
22994 // list of the parent. The completion order of the children affects the
22995 // side-effect order.
22996 if (returnFiber.firstEffect === null) {
22997 returnFiber.firstEffect = workInProgress.firstEffect;
22998 }
22999 if (workInProgress.lastEffect !== null) {
23000 if (returnFiber.lastEffect !== null) {
23001 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
23002 }
23003 returnFiber.lastEffect = workInProgress.lastEffect;
23004 }
23005
23006 // If this fiber had side-effects, we append it AFTER the children's
23007 // side-effects. We can perform certain side-effects earlier if needed,
23008 // by doing multiple passes over the effect list. We don't want to
23009 // schedule our own side-effect on our own list because if end up
23010 // reusing children we'll schedule this effect onto itself since we're
23011 // at the end.
23012 var effectTag = workInProgress.effectTag;
23013
23014 // Skip both NoWork and PerformedWork tags when creating the effect
23015 // list. PerformedWork effect is read by React DevTools but shouldn't be
23016 // committed.
23017 if (effectTag > PerformedWork) {
23018 if (returnFiber.lastEffect !== null) {
23019 returnFiber.lastEffect.nextEffect = workInProgress;
23020 } else {
23021 returnFiber.firstEffect = workInProgress;
23022 }
23023 returnFiber.lastEffect = workInProgress;
23024 }
23025 }
23026 } else {
23027 // This fiber did not complete because something threw. Pop values off
23028 // the stack without entering the complete phase. If this is a boundary,
23029 // capture values if possible.
23030 var _next = unwindWork(workInProgress, renderExpirationTime$1);
23031
23032 // Because this fiber did not complete, don't reset its expiration time.
23033
23034 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoContext) {
23035 // Record the render duration for the fiber that errored.
23036 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
23037
23038 // Include the time spent working on failed children before continuing.
23039 var actualDuration = workInProgress.actualDuration;
23040 var child = workInProgress.child;
23041 while (child !== null) {
23042 actualDuration += child.actualDuration;
23043 child = child.sibling;
23044 }
23045 workInProgress.actualDuration = actualDuration;
23046 }
23047
23048 if (_next !== null) {
23049 // If completing this work spawned new work, do that next. We'll come
23050 // back here again.
23051 // Since we're restarting, remove anything that is not a host effect
23052 // from the effect tag.
23053 // TODO: The name stopFailedWorkTimer is misleading because Suspense
23054 // also captures and restarts.
23055 stopFailedWorkTimer(workInProgress);
23056 _next.effectTag &= HostEffectMask;
23057 return _next;
23058 }
23059 stopWorkTimer(workInProgress);
23060
23061 if (returnFiber !== null) {
23062 // Mark the parent fiber as incomplete and clear its effect list.
23063 returnFiber.firstEffect = returnFiber.lastEffect = null;
23064 returnFiber.effectTag |= Incomplete;
23065 }
23066 }
23067
23068 var siblingFiber = workInProgress.sibling;
23069 if (siblingFiber !== null) {
23070 // If there is more work to do in this returnFiber, do that next.
23071 return siblingFiber;
23072 }
23073 // Otherwise, return to the parent
23074 workInProgress = returnFiber;
23075 } while (workInProgress !== null);
23076
23077 // We've reached the root.
23078 if (workInProgressRootExitStatus === RootIncomplete) {
23079 workInProgressRootExitStatus = RootCompleted;
23080 }
23081 return null;
23082}
23083
23084function resetChildExpirationTime$1(completedWork) {
23085 if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {
23086 // The children of this component are hidden. Don't bubble their
23087 // expiration times.
23088 return;
23089 }
23090
23091 var newChildExpirationTime = NoWork;
23092
23093 // Bubble up the earliest expiration time.
23094 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) {
23095 // In profiling mode, resetChildExpirationTime is also used to reset
23096 // profiler durations.
23097 var actualDuration = completedWork.actualDuration;
23098 var treeBaseDuration = completedWork.selfBaseDuration;
23099
23100 // When a fiber is cloned, its actualDuration is reset to 0. This value will
23101 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
23102 // When work is done, it should bubble to the parent's actualDuration. If
23103 // the fiber has not been cloned though, (meaning no work was done), then
23104 // this value will reflect the amount of time spent working on a previous
23105 // render. In that case it should not bubble. We determine whether it was
23106 // cloned by comparing the child pointer.
23107 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
23108
23109 var child = completedWork.child;
23110 while (child !== null) {
23111 var childUpdateExpirationTime = child.expirationTime;
23112 var childChildExpirationTime = child.childExpirationTime;
23113 if (childUpdateExpirationTime > newChildExpirationTime) {
23114 newChildExpirationTime = childUpdateExpirationTime;
23115 }
23116 if (childChildExpirationTime > newChildExpirationTime) {
23117 newChildExpirationTime = childChildExpirationTime;
23118 }
23119 if (shouldBubbleActualDurations) {
23120 actualDuration += child.actualDuration;
23121 }
23122 treeBaseDuration += child.treeBaseDuration;
23123 child = child.sibling;
23124 }
23125 completedWork.actualDuration = actualDuration;
23126 completedWork.treeBaseDuration = treeBaseDuration;
23127 } else {
23128 var _child = completedWork.child;
23129 while (_child !== null) {
23130 var _childUpdateExpirationTime = _child.expirationTime;
23131 var _childChildExpirationTime = _child.childExpirationTime;
23132 if (_childUpdateExpirationTime > newChildExpirationTime) {
23133 newChildExpirationTime = _childUpdateExpirationTime;
23134 }
23135 if (_childChildExpirationTime > newChildExpirationTime) {
23136 newChildExpirationTime = _childChildExpirationTime;
23137 }
23138 _child = _child.sibling;
23139 }
23140 }
23141
23142 completedWork.childExpirationTime = newChildExpirationTime;
23143}
23144
23145function commitRoot$1(root, expirationTime) {
23146 runWithPriority(ImmediatePriority, commitRootImpl.bind(null, root, expirationTime));
23147 // If there are passive effects, schedule a callback to flush them. This goes
23148 // outside commitRootImpl so that it inherits the priority of the render.
23149 if (rootWithPendingPassiveEffects$1 !== null) {
23150 var priorityLevel = getCurrentPriorityLevel();
23151 scheduleCallback(priorityLevel, function () {
23152 flushPassiveEffects$2();
23153 return null;
23154 });
23155 }
23156 return null;
23157}
23158
23159function commitRootImpl(root, expirationTime) {
23160 flushPassiveEffects$2();
23161 flushRenderPhaseStrictModeWarningsInDEV();
23162
23163 (function () {
23164 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
23165 {
23166 throw ReactError('Should not already be working.');
23167 }
23168 }
23169 })();
23170 var finishedWork = root.current.alternate;
23171 (function () {
23172 if (!(finishedWork !== null)) {
23173 {
23174 throw ReactError('Should have a work-in-progress root.');
23175 }
23176 }
23177 })();
23178
23179 // commitRoot never returns a continuation; it always finishes synchronously.
23180 // So we can clear these now to allow a new callback to be scheduled.
23181 root.callbackNode = null;
23182 root.callbackExpirationTime = NoWork;
23183
23184 startCommitTimer();
23185
23186 // Update the first and last pending times on this root. The new first
23187 // pending time is whatever is left on the root fiber.
23188 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
23189 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
23190 var firstPendingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
23191 root.firstPendingTime = firstPendingTimeBeforeCommit;
23192 if (firstPendingTimeBeforeCommit < root.lastPendingTime) {
23193 // This usually means we've finished all the work, but it can also happen
23194 // when something gets downprioritized during render, like a hidden tree.
23195 root.lastPendingTime = firstPendingTimeBeforeCommit;
23196 }
23197
23198 if (root === workInProgressRoot) {
23199 // We can reset these now that they are finished.
23200 workInProgressRoot = null;
23201 workInProgress = null;
23202 renderExpirationTime$1 = NoWork;
23203 } else {}
23204 // This indicates that the last root we worked on is not the same one that
23205 // we're committing now. This most commonly happens when a suspended root
23206 // times out.
23207
23208
23209 // Get the list of effects.
23210 var firstEffect = void 0;
23211 if (finishedWork.effectTag > PerformedWork) {
23212 // A fiber's effect list consists only of its children, not itself. So if
23213 // the root has an effect, we need to add it to the end of the list. The
23214 // resulting list is the set that would belong to the root's parent, if it
23215 // had one; that is, all the effects in the tree including the root.
23216 if (finishedWork.lastEffect !== null) {
23217 finishedWork.lastEffect.nextEffect = finishedWork;
23218 firstEffect = finishedWork.firstEffect;
23219 } else {
23220 firstEffect = finishedWork;
23221 }
23222 } else {
23223 // There is no effect on the root.
23224 firstEffect = finishedWork.firstEffect;
23225 }
23226
23227 if (firstEffect !== null) {
23228 var prevWorkPhase = workPhase;
23229 workPhase = CommitPhase;
23230 var prevInteractions = null;
23231 if (enableSchedulerTracing) {
23232 prevInteractions = __interactionsRef.current;
23233 __interactionsRef.current = root.memoizedInteractions;
23234 }
23235
23236 // Reset this to null before calling lifecycles
23237 ReactCurrentOwner$4.current = null;
23238
23239 // The commit phase is broken into several sub-phases. We do a separate pass
23240 // of the effect list for each phase: all mutation effects come before all
23241 // layout effects, and so on.
23242
23243 // The first phase a "before mutation" phase. We use this phase to read the
23244 // state of the host tree right before we mutate it. This is where
23245 // getSnapshotBeforeUpdate is called.
23246 startCommitSnapshotEffectsTimer();
23247 prepareForCommit(root.containerInfo);
23248 nextEffect$1 = firstEffect;
23249 do {
23250 {
23251 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
23252 if (hasCaughtError()) {
23253 (function () {
23254 if (!(nextEffect$1 !== null)) {
23255 {
23256 throw ReactError('Should be working on an effect.');
23257 }
23258 }
23259 })();
23260 var error = clearCaughtError();
23261 captureCommitPhaseError$2(nextEffect$1, error);
23262 nextEffect$1 = nextEffect$1.nextEffect;
23263 }
23264 }
23265 } while (nextEffect$1 !== null);
23266 stopCommitSnapshotEffectsTimer();
23267
23268 if (enableProfilerTimer) {
23269 // Mark the current commit time to be shared by all Profilers in this
23270 // batch. This enables them to be grouped later.
23271 recordCommitTime();
23272 }
23273
23274 // The next phase is the mutation phase, where we mutate the host tree.
23275 startCommitHostEffectsTimer();
23276 nextEffect$1 = firstEffect;
23277 do {
23278 {
23279 invokeGuardedCallback(null, commitMutationEffects, null);
23280 if (hasCaughtError()) {
23281 (function () {
23282 if (!(nextEffect$1 !== null)) {
23283 {
23284 throw ReactError('Should be working on an effect.');
23285 }
23286 }
23287 })();
23288 var _error = clearCaughtError();
23289 captureCommitPhaseError$2(nextEffect$1, _error);
23290 nextEffect$1 = nextEffect$1.nextEffect;
23291 }
23292 }
23293 } while (nextEffect$1 !== null);
23294 stopCommitHostEffectsTimer();
23295 resetAfterCommit(root.containerInfo);
23296
23297 // The work-in-progress tree is now the current tree. This must come after
23298 // the mutation phase, so that the previous tree is still current during
23299 // componentWillUnmount, but before the layout phase, so that the finished
23300 // work is current during componentDidMount/Update.
23301 root.current = finishedWork;
23302
23303 // The next phase is the layout phase, where we call effects that read
23304 // the host tree after it's been mutated. The idiomatic use case for this is
23305 // layout, but class component lifecycles also fire here for legacy reasons.
23306 startCommitLifeCyclesTimer();
23307 nextEffect$1 = firstEffect;
23308 do {
23309 {
23310 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
23311 if (hasCaughtError()) {
23312 (function () {
23313 if (!(nextEffect$1 !== null)) {
23314 {
23315 throw ReactError('Should be working on an effect.');
23316 }
23317 }
23318 })();
23319 var _error2 = clearCaughtError();
23320 captureCommitPhaseError$2(nextEffect$1, _error2);
23321 nextEffect$1 = nextEffect$1.nextEffect;
23322 }
23323 }
23324 } while (nextEffect$1 !== null);
23325 stopCommitLifeCyclesTimer();
23326
23327 nextEffect$1 = null;
23328
23329 if (enableSchedulerTracing) {
23330 __interactionsRef.current = prevInteractions;
23331 }
23332 workPhase = prevWorkPhase;
23333 } else {
23334 // No effects.
23335 root.current = finishedWork;
23336 // Measure these anyway so the flamegraph explicitly shows that there were
23337 // no effects.
23338 // TODO: Maybe there's a better way to report this.
23339 startCommitSnapshotEffectsTimer();
23340 stopCommitSnapshotEffectsTimer();
23341 if (enableProfilerTimer) {
23342 recordCommitTime();
23343 }
23344 startCommitHostEffectsTimer();
23345 stopCommitHostEffectsTimer();
23346 startCommitLifeCyclesTimer();
23347 stopCommitLifeCyclesTimer();
23348 }
23349
23350 stopCommitTimer();
23351
23352 if (rootDoesHavePassiveEffects) {
23353 // This commit has passive effects. Stash a reference to them. But don't
23354 // schedule a callback until after flushing layout work.
23355 rootDoesHavePassiveEffects = false;
23356 rootWithPendingPassiveEffects$1 = root;
23357 pendingPassiveEffectsExpirationTime = expirationTime;
23358 } else {
23359 if (enableSchedulerTracing) {
23360 // If there are no passive effects, then we can complete the pending
23361 // interactions. Otherwise, we'll wait until after the passive effects
23362 // are flushed.
23363 finishPendingInteractions(root, expirationTime);
23364 }
23365 }
23366
23367 // Check if there's remaining work on this root
23368 var remainingExpirationTime = root.firstPendingTime;
23369 if (remainingExpirationTime !== NoWork) {
23370 var currentTime = requestCurrentTime$2();
23371 var priorityLevel = inferPriorityFromExpirationTime(currentTime, remainingExpirationTime);
23372 scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime);
23373 } else {
23374 // If there's no remaining work, we can clear the set of already failed
23375 // error boundaries.
23376 legacyErrorBoundariesThatAlreadyFailed$1 = null;
23377 }
23378
23379 onCommitRoot(finishedWork.stateNode);
23380
23381 if (remainingExpirationTime === Sync) {
23382 // Count the number of times the root synchronously re-renders without
23383 // finishing. If there are too many, it indicates an infinite update loop.
23384 if (root === rootWithNestedUpdates) {
23385 nestedUpdateCount$1++;
23386 } else {
23387 nestedUpdateCount$1 = 0;
23388 rootWithNestedUpdates = root;
23389 }
23390 } else {
23391 nestedUpdateCount$1 = 0;
23392 }
23393
23394 if (hasUncaughtError) {
23395 hasUncaughtError = false;
23396 var _error3 = firstUncaughtError;
23397 firstUncaughtError = null;
23398 throw _error3;
23399 }
23400
23401 if (workPhase === LegacyUnbatchedPhase) {
23402 // This is a legacy edge case. We just committed the initial mount of
23403 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
23404 // synchronously, but layout updates should be deferred until the end
23405 // of the batch.
23406 return null;
23407 }
23408
23409 // If layout work was scheduled, flush it now.
23410 flushImmediateQueue();
23411 return null;
23412}
23413
23414function commitBeforeMutationEffects() {
23415 while (nextEffect$1 !== null) {
23416 if ((nextEffect$1.effectTag & Snapshot) !== NoEffect) {
23417 setCurrentFiber(nextEffect$1);
23418 recordEffect();
23419
23420 var current$$1 = nextEffect$1.alternate;
23421 commitBeforeMutationLifeCycles(current$$1, nextEffect$1);
23422
23423 resetCurrentFiber();
23424 }
23425 nextEffect$1 = nextEffect$1.nextEffect;
23426 }
23427}
23428
23429function commitMutationEffects() {
23430 // TODO: Should probably move the bulk of this function to commitWork.
23431 while (nextEffect$1 !== null) {
23432 setCurrentFiber(nextEffect$1);
23433
23434 var effectTag = nextEffect$1.effectTag;
23435
23436 if (effectTag & ContentReset) {
23437 commitResetTextContent(nextEffect$1);
23438 }
23439
23440 if (effectTag & Ref) {
23441 var current$$1 = nextEffect$1.alternate;
23442 if (current$$1 !== null) {
23443 commitDetachRef(current$$1);
23444 }
23445 }
23446
23447 // The following switch statement is only concerned about placement,
23448 // updates, and deletions. To avoid needing to add a case for every possible
23449 // bitmap value, we remove the secondary effects from the effect tag and
23450 // switch on that value.
23451 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
23452 switch (primaryEffectTag) {
23453 case Placement:
23454 {
23455 commitPlacement(nextEffect$1);
23456 // Clear the "placement" from effect tag so that we know that this is
23457 // inserted, before any life-cycles like componentDidMount gets called.
23458 // TODO: findDOMNode doesn't rely on this any more but isMounted does
23459 // and isMounted is deprecated anyway so we should be able to kill this.
23460 nextEffect$1.effectTag &= ~Placement;
23461 break;
23462 }
23463 case PlacementAndUpdate:
23464 {
23465 // Placement
23466 commitPlacement(nextEffect$1);
23467 // Clear the "placement" from effect tag so that we know that this is
23468 // inserted, before any life-cycles like componentDidMount gets called.
23469 nextEffect$1.effectTag &= ~Placement;
23470
23471 // Update
23472 var _current = nextEffect$1.alternate;
23473 commitWork(_current, nextEffect$1);
23474 break;
23475 }
23476 case Update:
23477 {
23478 var _current2 = nextEffect$1.alternate;
23479 commitWork(_current2, nextEffect$1);
23480 break;
23481 }
23482 case Deletion:
23483 {
23484 commitDeletion(nextEffect$1);
23485 break;
23486 }
23487 }
23488
23489 // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
23490 recordEffect();
23491
23492 resetCurrentFiber();
23493 nextEffect$1 = nextEffect$1.nextEffect;
23494 }
23495}
23496
23497function commitLayoutEffects(root, committedExpirationTime) {
23498 // TODO: Should probably move the bulk of this function to commitWork.
23499 while (nextEffect$1 !== null) {
23500 setCurrentFiber(nextEffect$1);
23501
23502 var effectTag = nextEffect$1.effectTag;
23503
23504 if (effectTag & (Update | Callback)) {
23505 recordEffect();
23506 var current$$1 = nextEffect$1.alternate;
23507 commitLifeCycles(root, current$$1, nextEffect$1, committedExpirationTime);
23508 }
23509
23510 if (effectTag & Ref) {
23511 recordEffect();
23512 commitAttachRef(nextEffect$1);
23513 }
23514
23515 if (effectTag & Passive) {
23516 rootDoesHavePassiveEffects = true;
23517 }
23518
23519 resetCurrentFiber();
23520 nextEffect$1 = nextEffect$1.nextEffect;
23521 }
23522}
23523
23524function flushPassiveEffects$2() {
23525 if (rootWithPendingPassiveEffects$1 === null) {
23526 return false;
23527 }
23528 var root = rootWithPendingPassiveEffects$1;
23529 var expirationTime = pendingPassiveEffectsExpirationTime;
23530 rootWithPendingPassiveEffects$1 = null;
23531 pendingPassiveEffectsExpirationTime = NoWork;
23532
23533 var prevInteractions = null;
23534 if (enableSchedulerTracing) {
23535 prevInteractions = __interactionsRef.current;
23536 __interactionsRef.current = root.memoizedInteractions;
23537 }
23538
23539 (function () {
23540 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
23541 {
23542 throw ReactError('Cannot flush passive effects while already rendering.');
23543 }
23544 }
23545 })();
23546 var prevWorkPhase = workPhase;
23547 workPhase = CommitPhase;
23548
23549 // Note: This currently assumes there are no passive effects on the root
23550 // fiber, because the root is not part of its own effect list. This could
23551 // change in the future.
23552 var effect = root.current.firstEffect;
23553 while (effect !== null) {
23554 {
23555 setCurrentFiber(effect);
23556 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
23557 if (hasCaughtError()) {
23558 (function () {
23559 if (!(effect !== null)) {
23560 {
23561 throw ReactError('Should be working on an effect.');
23562 }
23563 }
23564 })();
23565 var error = clearCaughtError();
23566 captureCommitPhaseError$2(effect, error);
23567 }
23568 resetCurrentFiber();
23569 }
23570 effect = effect.nextEffect;
23571 }
23572
23573 if (enableSchedulerTracing) {
23574 __interactionsRef.current = prevInteractions;
23575 finishPendingInteractions(root, expirationTime);
23576 }
23577
23578 workPhase = prevWorkPhase;
23579 flushImmediateQueue();
23580
23581 // If additional passive effects were scheduled, increment a counter. If this
23582 // exceeds the limit, we'll fire a warning.
23583 nestedPassiveUpdateCount = rootWithPendingPassiveEffects$1 === null ? 0 : nestedPassiveUpdateCount + 1;
23584
23585 return true;
23586}
23587
23588function isAlreadyFailedLegacyErrorBoundary$2(instance) {
23589 return legacyErrorBoundariesThatAlreadyFailed$1 !== null && legacyErrorBoundariesThatAlreadyFailed$1.has(instance);
23590}
23591
23592function markLegacyErrorBoundaryAsFailed$2(instance) {
23593 if (legacyErrorBoundariesThatAlreadyFailed$1 === null) {
23594 legacyErrorBoundariesThatAlreadyFailed$1 = new Set([instance]);
23595 } else {
23596 legacyErrorBoundariesThatAlreadyFailed$1.add(instance);
23597 }
23598}
23599
23600function prepareToThrowUncaughtError(error) {
23601 if (!hasUncaughtError) {
23602 hasUncaughtError = true;
23603 firstUncaughtError = error;
23604 }
23605}
23606var onUncaughtError$2 = prepareToThrowUncaughtError;
23607
23608function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
23609 var errorInfo = createCapturedValue(error, sourceFiber);
23610 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
23611 enqueueUpdate(rootFiber, update);
23612 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
23613 if (root !== null) {
23614 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
23615 }
23616}
23617
23618function captureCommitPhaseError$2(sourceFiber, error) {
23619 if (sourceFiber.tag === HostRoot) {
23620 // Error was thrown at the root. There is no parent, so the root
23621 // itself should capture it.
23622 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
23623 return;
23624 }
23625
23626 var fiber = sourceFiber.return;
23627 while (fiber !== null) {
23628 if (fiber.tag === HostRoot) {
23629 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
23630 return;
23631 } else if (fiber.tag === ClassComponent) {
23632 var ctor = fiber.type;
23633 var instance = fiber.stateNode;
23634 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$2(instance)) {
23635 var errorInfo = createCapturedValue(error, sourceFiber);
23636 var update = createClassErrorUpdate(fiber, errorInfo,
23637 // TODO: This is always sync
23638 Sync);
23639 enqueueUpdate(fiber, update);
23640 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
23641 if (root !== null) {
23642 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
23643 }
23644 return;
23645 }
23646 }
23647 fiber = fiber.return;
23648 }
23649}
23650
23651function pingSuspendedRoot$2(root, thenable, suspendedTime) {
23652 var pingCache = root.pingCache;
23653 if (pingCache !== null) {
23654 // The thenable resolved, so we no longer need to memoize, because it will
23655 // never be thrown again.
23656 pingCache.delete(thenable);
23657 }
23658
23659 if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {
23660 // Received a ping at the same priority level at which we're currently
23661 // rendering. Restart from the root. Don't need to schedule a ping because
23662 // we're already working on this tree.
23663 prepareFreshStack(root, renderExpirationTime$1);
23664 return;
23665 }
23666
23667 var lastPendingTime = root.lastPendingTime;
23668 if (lastPendingTime < suspendedTime) {
23669 // The root is no longer suspended at this time.
23670 return;
23671 }
23672
23673 var pingTime = root.pingTime;
23674 if (pingTime !== NoWork && pingTime < suspendedTime) {
23675 // There's already a lower priority ping scheduled.
23676 return;
23677 }
23678
23679 // Mark the time at which this ping was scheduled.
23680 root.pingTime = suspendedTime;
23681
23682 var currentTime = requestCurrentTime$2();
23683 var priorityLevel = inferPriorityFromExpirationTime(currentTime, suspendedTime);
23684 scheduleCallbackForRoot(root, priorityLevel, suspendedTime);
23685}
23686
23687function retryTimedOutBoundary$2(boundaryFiber) {
23688 // The boundary fiber (a Suspense component) previously timed out and was
23689 // rendered in its fallback state. One of the promises that suspended it has
23690 // resolved, which means at least part of the tree was likely unblocked. Try
23691 // rendering again, at a new expiration time.
23692 var currentTime = requestCurrentTime$2();
23693 var retryTime = computeExpirationForFiber$2(currentTime, boundaryFiber);
23694 // TODO: Special case idle priority?
23695 var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime);
23696 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
23697 if (root !== null) {
23698 scheduleCallbackForRoot(root, priorityLevel, retryTime);
23699 }
23700}
23701
23702function resolveRetryThenable$2(boundaryFiber, thenable) {
23703 var retryCache = void 0;
23704 if (enableSuspenseServerRenderer) {
23705 switch (boundaryFiber.tag) {
23706 case SuspenseComponent:
23707 retryCache = boundaryFiber.stateNode;
23708 break;
23709 case DehydratedSuspenseComponent:
23710 retryCache = boundaryFiber.memoizedState;
23711 break;
23712 default:
23713 (function () {
23714 {
23715 {
23716 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
23717 }
23718 }
23719 })();
23720 }
23721 } else {
23722 retryCache = boundaryFiber.stateNode;
23723 }
23724
23725 if (retryCache !== null) {
23726 // The thenable resolved, so we no longer need to memoize, because it will
23727 // never be thrown again.
23728 retryCache.delete(thenable);
23729 }
23730
23731 retryTimedOutBoundary$2(boundaryFiber);
23732}
23733
23734function inferStartTimeFromExpirationTime$2(root, expirationTime) {
23735 // We don't know exactly when the update was scheduled, but we can infer an
23736 // approximate start time from the expiration time.
23737 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
23738 // TODO: Track this on the root instead. It's more accurate, doesn't rely on
23739 // assumptions about priority, and isn't coupled to Scheduler details.
23740 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
23741}
23742
23743function computeMsUntilTimeout(root, absoluteTimeoutMs) {
23744 if (disableYielding) {
23745 // Timeout immediately when yielding is disabled.
23746 return 0;
23747 }
23748
23749 // Find the earliest uncommitted expiration time in the tree, including
23750 // work that is suspended. The timeout threshold cannot be longer than
23751 // the overall expiration.
23752 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
23753 if (earliestExpirationTimeMs < absoluteTimeoutMs) {
23754 absoluteTimeoutMs = earliestExpirationTimeMs;
23755 }
23756
23757 // Subtract the current time from the absolute timeout to get the number
23758 // of milliseconds until the timeout. In other words, convert an absolute
23759 // timestamp to a relative time. This is the value that is passed
23760 // to `setTimeout`.
23761 var msUntilTimeout = absoluteTimeoutMs - now$1();
23762 return msUntilTimeout < 0 ? 0 : msUntilTimeout;
23763}
23764
23765function checkForNestedUpdates() {
23766 if (nestedUpdateCount$1 > NESTED_UPDATE_LIMIT$1) {
23767 nestedUpdateCount$1 = 0;
23768 rootWithNestedUpdates = null;
23769 (function () {
23770 {
23771 {
23772 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.');
23773 }
23774 }
23775 })();
23776 }
23777
23778 {
23779 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT$1) {
23780 nestedPassiveUpdateCount = 0;
23781 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.');
23782 }
23783 }
23784}
23785
23786function flushRenderPhaseStrictModeWarningsInDEV() {
23787 {
23788 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
23789 ReactStrictModeWarnings.flushLegacyContextWarning();
23790
23791 if (warnAboutDeprecatedLifecycles) {
23792 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
23793 }
23794 }
23795}
23796
23797function stopFinishedWorkLoopTimer() {
23798 var didCompleteRoot = true;
23799 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
23800 interruptedBy$1 = null;
23801}
23802
23803function stopInterruptedWorkLoopTimer() {
23804 // TODO: Track which fiber caused the interruption.
23805 var didCompleteRoot = false;
23806 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
23807 interruptedBy$1 = null;
23808}
23809
23810function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
23811 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {
23812 interruptedBy$1 = fiberThatReceivedUpdate;
23813 }
23814}
23815
23816var didWarnStateUpdateForUnmountedComponent$1 = null;
23817function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
23818 {
23819 var tag = fiber.tag;
23820 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
23821 // Only warn for user-defined components, not internal ones like Suspense.
23822 return;
23823 }
23824 // We show the whole stack but dedupe on the top component's name because
23825 // the problematic code almost always lies inside that component.
23826 var componentName = getComponentName(fiber.type) || 'ReactComponent';
23827 if (didWarnStateUpdateForUnmountedComponent$1 !== null) {
23828 if (didWarnStateUpdateForUnmountedComponent$1.has(componentName)) {
23829 return;
23830 }
23831 didWarnStateUpdateForUnmountedComponent$1.add(componentName);
23832 } else {
23833 didWarnStateUpdateForUnmountedComponent$1 = new Set([componentName]);
23834 }
23835 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));
23836 }
23837}
23838
23839var beginWork$1 = void 0;
23840if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
23841 var dummyFiber = null;
23842 beginWork$1 = function (current$$1, unitOfWork, expirationTime) {
23843 // If a component throws an error, we replay it again in a synchronously
23844 // dispatched event, so that the debugger will treat it as an uncaught
23845 // error See ReactErrorUtils for more information.
23846
23847 // Before entering the begin phase, copy the work-in-progress onto a dummy
23848 // fiber. If beginWork throws, we'll use this to reset the state.
23849 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
23850 try {
23851 return beginWork(current$$1, unitOfWork, expirationTime);
23852 } catch (originalError) {
23853 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
23854 // Don't replay promises. Treat everything else like an error.
23855 throw originalError;
23856 }
23857
23858 // Keep this code in sync with renderRoot; any changes here must have
23859 // corresponding changes there.
23860 resetContextDependences();
23861 resetHooks();
23862
23863 // Unwind the failed stack frame
23864 unwindInterruptedWork(unitOfWork);
23865
23866 // Restore the original properties of the fiber.
23867 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
23868
23869 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
23870 // Reset the profiler timer.
23871 startProfilerTimer(unitOfWork);
23872 }
23873
23874 // Run beginWork again.
23875 invokeGuardedCallback(null, beginWork, null, current$$1, unitOfWork, expirationTime);
23876
23877 if (hasCaughtError()) {
23878 var replayError = clearCaughtError();
23879 // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
23880 // Rethrow this error instead of the original one.
23881 throw replayError;
23882 } else {
23883 // This branch is reachable if the render phase is impure.
23884 throw originalError;
23885 }
23886 }
23887 };
23888} else {
23889 beginWork$1 = beginWork;
23890}
23891
23892var didWarnAboutUpdateInRender = false;
23893var didWarnAboutUpdateInGetChildContext = false;
23894function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
23895 {
23896 if (fiber.tag === ClassComponent) {
23897 switch (phase) {
23898 case 'getChildContext':
23899 if (didWarnAboutUpdateInGetChildContext) {
23900 return;
23901 }
23902 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
23903 didWarnAboutUpdateInGetChildContext = true;
23904 break;
23905 case 'render':
23906 if (didWarnAboutUpdateInRender) {
23907 return;
23908 }
23909 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.');
23910 didWarnAboutUpdateInRender = true;
23911 break;
23912 }
23913 }
23914 }
23915}
23916
23917function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
23918 {
23919 if (workPhase === NotWorking && ReactShouldWarnActingUpdates$1.current === false) {
23920 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));
23921 }
23922 }
23923}
23924
23925var warnIfNotCurrentlyActingUpdatesInDev$2 = warnIfNotCurrentlyActingUpdatesInDEV;
23926
23927function computeThreadID$1(root, expirationTime) {
23928 // Interaction threads are unique per root and expiration time.
23929 return expirationTime * 1000 + root.interactionThreadID;
23930}
23931
23932function schedulePendingInteraction(root, expirationTime) {
23933 // This is called when work is scheduled on a root. It sets up a pending
23934 // interaction, which is completed once the work commits.
23935 if (!enableSchedulerTracing) {
23936 return;
23937 }
23938
23939 var interactions = __interactionsRef.current;
23940 if (interactions.size > 0) {
23941 var pendingInteractionMap = root.pendingInteractionMap;
23942 var pendingInteractions = pendingInteractionMap.get(expirationTime);
23943 if (pendingInteractions != null) {
23944 interactions.forEach(function (interaction) {
23945 if (!pendingInteractions.has(interaction)) {
23946 // Update the pending async work count for previously unscheduled interaction.
23947 interaction.__count++;
23948 }
23949
23950 pendingInteractions.add(interaction);
23951 });
23952 } else {
23953 pendingInteractionMap.set(expirationTime, new Set(interactions));
23954
23955 // Update the pending async work count for the current interactions.
23956 interactions.forEach(function (interaction) {
23957 interaction.__count++;
23958 });
23959 }
23960
23961 var subscriber = __subscriberRef.current;
23962 if (subscriber !== null) {
23963 var threadID = computeThreadID$1(root, expirationTime);
23964 subscriber.onWorkScheduled(interactions, threadID);
23965 }
23966 }
23967}
23968
23969function startWorkOnPendingInteraction(root, expirationTime) {
23970 // This is called when new work is started on a root.
23971 if (!enableSchedulerTracing) {
23972 return;
23973 }
23974
23975 // Determine which interactions this batch of work currently includes, So that
23976 // we can accurately attribute time spent working on it, And so that cascading
23977 // work triggered during the render phase will be associated with it.
23978 var interactions = new Set();
23979 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
23980 if (scheduledExpirationTime >= expirationTime) {
23981 scheduledInteractions.forEach(function (interaction) {
23982 return interactions.add(interaction);
23983 });
23984 }
23985 });
23986
23987 // Store the current set of interactions on the FiberRoot for a few reasons:
23988 // We can re-use it in hot functions like renderRoot() without having to
23989 // recalculate it. We will also use it in commitWork() to pass to any Profiler
23990 // onRender() hooks. This also provides DevTools with a way to access it when
23991 // the onCommitRoot() hook is called.
23992 root.memoizedInteractions = interactions;
23993
23994 if (interactions.size > 0) {
23995 var subscriber = __subscriberRef.current;
23996 if (subscriber !== null) {
23997 var threadID = computeThreadID$1(root, expirationTime);
23998 try {
23999 subscriber.onWorkStarted(interactions, threadID);
24000 } catch (error) {
24001 // If the subscriber throws, rethrow it in a separate task
24002 scheduleCallback(ImmediatePriority, function () {
24003 throw error;
24004 });
24005 }
24006 }
24007 }
24008}
24009
24010function finishPendingInteractions(root, committedExpirationTime) {
24011 if (!enableSchedulerTracing) {
24012 return;
24013 }
24014
24015 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
24016
24017 var subscriber = void 0;
24018
24019 try {
24020 subscriber = __subscriberRef.current;
24021 if (subscriber !== null && root.memoizedInteractions.size > 0) {
24022 var threadID = computeThreadID$1(root, committedExpirationTime);
24023 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
24024 }
24025 } catch (error) {
24026 // If the subscriber throws, rethrow it in a separate task
24027 scheduleCallback(ImmediatePriority, function () {
24028 throw error;
24029 });
24030 } finally {
24031 // Clear completed interactions from the pending Map.
24032 // Unless the render was suspended or cascading work was scheduled,
24033 // In which case– leave pending interactions until the subsequent render.
24034 var pendingInteractionMap = root.pendingInteractionMap;
24035 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
24036 // Only decrement the pending interaction count if we're done.
24037 // If there's still work at the current priority,
24038 // That indicates that we are waiting for suspense data.
24039 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
24040 pendingInteractionMap.delete(scheduledExpirationTime);
24041
24042 scheduledInteractions.forEach(function (interaction) {
24043 interaction.__count--;
24044
24045 if (subscriber !== null && interaction.__count === 0) {
24046 try {
24047 subscriber.onInteractionScheduledWorkCompleted(interaction);
24048 } catch (error) {
24049 // If the subscriber throws, rethrow it in a separate task
24050 scheduleCallback(ImmediatePriority, function () {
24051 throw error;
24052 });
24053 }
24054 }
24055 });
24056 }
24057 });
24058 }
24059}
24060
24061var requestCurrentTime$$1 = enableNewScheduler ? requestCurrentTime$2 : requestCurrentTime$1;
24062var computeExpirationForFiber$$1 = enableNewScheduler ? computeExpirationForFiber$2 : computeExpirationForFiber$1;
24063var captureCommitPhaseError$$1 = enableNewScheduler ? captureCommitPhaseError$2 : captureCommitPhaseError$1;
24064var onUncaughtError$$1 = enableNewScheduler ? onUncaughtError$2 : onUncaughtError$1;
24065var renderDidSuspend$$1 = enableNewScheduler ? renderDidSuspend$2 : renderDidSuspend$1;
24066var renderDidError$$1 = enableNewScheduler ? renderDidError$2 : renderDidError$1;
24067var pingSuspendedRoot$$1 = enableNewScheduler ? pingSuspendedRoot$2 : pingSuspendedRoot$1;
24068var retryTimedOutBoundary$$1 = enableNewScheduler ? retryTimedOutBoundary$2 : retryTimedOutBoundary$1;
24069var resolveRetryThenable$$1 = enableNewScheduler ? resolveRetryThenable$2 : resolveRetryThenable$1;
24070var markLegacyErrorBoundaryAsFailed$$1 = enableNewScheduler ? markLegacyErrorBoundaryAsFailed$2 : markLegacyErrorBoundaryAsFailed$1;
24071var isAlreadyFailedLegacyErrorBoundary$$1 = enableNewScheduler ? isAlreadyFailedLegacyErrorBoundary$2 : isAlreadyFailedLegacyErrorBoundary$1;
24072var scheduleWork$$1 = enableNewScheduler ? scheduleWork$2 : scheduleWork$1;
24073var flushRoot$$1 = enableNewScheduler ? flushRoot$2 : flushRoot$1;
24074var batchedUpdates$1 = enableNewScheduler ? batchedUpdates$3 : batchedUpdates$2;
24075var unbatchedUpdates$$1 = enableNewScheduler ? unbatchedUpdates$2 : unbatchedUpdates$1;
24076var flushSync$$1 = enableNewScheduler ? flushSync$2 : flushSync$1;
24077var flushControlled$$1 = enableNewScheduler ? flushControlled$2 : flushControlled$1;
24078
24079
24080var interactiveUpdates$1 = enableNewScheduler ? interactiveUpdates$3 : interactiveUpdates$2;
24081var flushInteractiveUpdates$1 = enableNewScheduler ? flushInteractiveUpdates$3 : flushInteractiveUpdates$2;
24082var computeUniqueAsyncExpiration$$1 = enableNewScheduler ? computeUniqueAsyncExpiration$2 : computeUniqueAsyncExpiration$1;
24083var flushPassiveEffects$$1 = enableNewScheduler ? flushPassiveEffects$2 : flushPassiveEffects$1;
24084var warnIfNotCurrentlyActingUpdatesInDev$$1 = enableNewScheduler ? warnIfNotCurrentlyActingUpdatesInDev$2 : warnIfNotCurrentlyActingUpdatesInDev$1;
24085var inferStartTimeFromExpirationTime$$1 = enableNewScheduler ? inferStartTimeFromExpirationTime$2 : inferStartTimeFromExpirationTime$1;
24086
24087// 0 is PROD, 1 is DEV.
24088// Might add PROFILE later.
24089
24090
24091var didWarnAboutNestedUpdates = void 0;
24092var didWarnAboutFindNodeInStrictMode = void 0;
24093
24094{
24095 didWarnAboutNestedUpdates = false;
24096 didWarnAboutFindNodeInStrictMode = {};
24097}
24098
24099function getContextForSubtree(parentComponent) {
24100 if (!parentComponent) {
24101 return emptyContextObject;
24102 }
24103
24104 var fiber = get(parentComponent);
24105 var parentContext = findCurrentUnmaskedContext(fiber);
24106
24107 if (fiber.tag === ClassComponent) {
24108 var Component = fiber.type;
24109 if (isContextProvider(Component)) {
24110 return processChildContext(fiber, Component, parentContext);
24111 }
24112 }
24113
24114 return parentContext;
24115}
24116
24117function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
24118 {
24119 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
24120 didWarnAboutNestedUpdates = true;
24121 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');
24122 }
24123 }
24124
24125 var update = createUpdate(expirationTime);
24126 // Caution: React DevTools currently depends on this property
24127 // being called "element".
24128 update.payload = { element: element };
24129
24130 callback = callback === undefined ? null : callback;
24131 if (callback !== null) {
24132 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
24133 update.callback = callback;
24134 }
24135
24136 flushPassiveEffects$$1();
24137 enqueueUpdate(current$$1, update);
24138 scheduleWork$$1(current$$1, expirationTime);
24139
24140 return expirationTime;
24141}
24142
24143function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
24144 // TODO: If this is a nested container, this won't be the root.
24145 var current$$1 = container.current;
24146
24147 {
24148 if (ReactFiberInstrumentation_1.debugTool) {
24149 if (current$$1.alternate === null) {
24150 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
24151 } else if (element === null) {
24152 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
24153 } else {
24154 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
24155 }
24156 }
24157 }
24158
24159 var context = getContextForSubtree(parentComponent);
24160 if (container.context === null) {
24161 container.context = context;
24162 } else {
24163 container.pendingContext = context;
24164 }
24165
24166 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
24167}
24168
24169function findHostInstance(component) {
24170 var fiber = get(component);
24171 if (fiber === undefined) {
24172 if (typeof component.render === 'function') {
24173 (function () {
24174 {
24175 {
24176 throw ReactError('Unable to find node on an unmounted component.');
24177 }
24178 }
24179 })();
24180 } else {
24181 (function () {
24182 {
24183 {
24184 throw ReactError('Argument appears to not be a ReactComponent. Keys: ' + Object.keys(component));
24185 }
24186 }
24187 })();
24188 }
24189 }
24190 var hostFiber = findCurrentHostFiber(fiber);
24191 if (hostFiber === null) {
24192 return null;
24193 }
24194 return hostFiber.stateNode;
24195}
24196
24197function findHostInstanceWithWarning(component, methodName) {
24198 {
24199 var fiber = get(component);
24200 if (fiber === undefined) {
24201 if (typeof component.render === 'function') {
24202 (function () {
24203 {
24204 {
24205 throw ReactError('Unable to find node on an unmounted component.');
24206 }
24207 }
24208 })();
24209 } else {
24210 (function () {
24211 {
24212 {
24213 throw ReactError('Argument appears to not be a ReactComponent. Keys: ' + Object.keys(component));
24214 }
24215 }
24216 })();
24217 }
24218 }
24219 var hostFiber = findCurrentHostFiber(fiber);
24220 if (hostFiber === null) {
24221 return null;
24222 }
24223 if (hostFiber.mode & StrictMode) {
24224 var componentName = getComponentName(fiber.type) || 'Component';
24225 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
24226 didWarnAboutFindNodeInStrictMode[componentName] = true;
24227 if (fiber.mode & StrictMode) {
24228 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));
24229 } else {
24230 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));
24231 }
24232 }
24233 }
24234 return hostFiber.stateNode;
24235 }
24236 return findHostInstance(component);
24237}
24238
24239function createContainer(containerInfo, isConcurrent, hydrate) {
24240 return createFiberRoot(containerInfo, isConcurrent, hydrate);
24241}
24242
24243function updateContainer(element, container, parentComponent, callback) {
24244 var current$$1 = container.current;
24245 var currentTime = requestCurrentTime$$1();
24246 var expirationTime = computeExpirationForFiber$$1(currentTime, current$$1);
24247 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
24248}
24249
24250function getPublicRootInstance(container) {
24251 var containerFiber = container.current;
24252 if (!containerFiber.child) {
24253 return null;
24254 }
24255 switch (containerFiber.child.tag) {
24256 case HostComponent:
24257 return getPublicInstance(containerFiber.child.stateNode);
24258 default:
24259 return containerFiber.child.stateNode;
24260 }
24261}
24262
24263function findHostInstanceWithNoPortals(fiber) {
24264 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
24265 if (hostFiber === null) {
24266 return null;
24267 }
24268 return hostFiber.stateNode;
24269}
24270
24271var overrideHookState = null;
24272var overrideProps = null;
24273
24274{
24275 var copyWithSetImpl = function (obj, path, idx, value) {
24276 if (idx >= path.length) {
24277 return value;
24278 }
24279 var key = path[idx];
24280 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
24281 // $FlowFixMe number or string is fine here
24282 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
24283 return updated;
24284 };
24285
24286 var copyWithSet = function (obj, path, value) {
24287 return copyWithSetImpl(obj, path, 0, value);
24288 };
24289
24290 // Support DevTools editable values for useState and useReducer.
24291 overrideHookState = function (fiber, id, path, value) {
24292 // For now, the "id" of stateful hooks is just the stateful hook index.
24293 // This may change in the future with e.g. nested hooks.
24294 var currentHook = fiber.memoizedState;
24295 while (currentHook !== null && id > 0) {
24296 currentHook = currentHook.next;
24297 id--;
24298 }
24299 if (currentHook !== null) {
24300 flushPassiveEffects$$1();
24301
24302 var newState = copyWithSet(currentHook.memoizedState, path, value);
24303 currentHook.memoizedState = newState;
24304 currentHook.baseState = newState;
24305
24306 // We aren't actually adding an update to the queue,
24307 // because there is no update we can add for useReducer hooks that won't trigger an error.
24308 // (There's no appropriate action type for DevTools overrides.)
24309 // As a result though, React will see the scheduled update as a noop and bailout.
24310 // Shallow cloning props works as a workaround for now to bypass the bailout check.
24311 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
24312
24313 scheduleWork$$1(fiber, Sync);
24314 }
24315 };
24316
24317 // Support DevTools props for function components, forwardRef, memo, host components, etc.
24318 overrideProps = function (fiber, path, value) {
24319 flushPassiveEffects$$1();
24320 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
24321 if (fiber.alternate) {
24322 fiber.alternate.pendingProps = fiber.pendingProps;
24323 }
24324 scheduleWork$$1(fiber, Sync);
24325 };
24326}
24327
24328function injectIntoDevTools(devToolsConfig) {
24329 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
24330 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
24331
24332
24333 return injectInternals(_assign({}, devToolsConfig, {
24334 overrideHookState: overrideHookState,
24335 overrideProps: overrideProps,
24336 currentDispatcherRef: ReactCurrentDispatcher,
24337 findHostInstanceByFiber: function (fiber) {
24338 var hostFiber = findCurrentHostFiber(fiber);
24339 if (hostFiber === null) {
24340 return null;
24341 }
24342 return hostFiber.stateNode;
24343 },
24344 findFiberByHostInstance: function (instance) {
24345 if (!findFiberByHostInstance) {
24346 // Might not be implemented by the renderer.
24347 return null;
24348 }
24349 return findFiberByHostInstance(instance);
24350 }
24351 }));
24352}
24353
24354// This file intentionally does *not* have the Flow annotation.
24355// Don't add it. See `./inline-typed.js` for an explanation.
24356
24357function createPortal$1(children, containerInfo,
24358// TODO: figure out the API for cross-renderer implementation.
24359implementation) {
24360 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
24361
24362 return {
24363 // This tag allow us to uniquely identify this as a React Portal
24364 $$typeof: REACT_PORTAL_TYPE,
24365 key: key == null ? null : '' + key,
24366 children: children,
24367 containerInfo: containerInfo,
24368 implementation: implementation
24369 };
24370}
24371
24372// TODO: this is special because it gets imported during build.
24373
24374var ReactVersion = '16.9.0-alpha.0';
24375
24376// This file is copy paste from ReactDOM with adjusted paths
24377// and a different host config import (react-reconciler/inline.fire).
24378// TODO: real implementation.
24379// console.log('Hello from Fire entry point.');
24380
24381// TODO: This type is shared between the reconciler and ReactDOM, but will
24382// eventually be lifted out to the renderer.
24383
24384var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
24385
24386var topLevelUpdateWarnings = void 0;
24387var warnOnInvalidCallback = void 0;
24388var didWarnAboutUnstableCreatePortal = false;
24389
24390{
24391 if (typeof Map !== 'function' ||
24392 // $FlowIssue Flow incorrectly thinks Map has no prototype
24393 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' ||
24394 // $FlowIssue Flow incorrectly thinks Set has no prototype
24395 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
24396 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');
24397 }
24398
24399 topLevelUpdateWarnings = function (container) {
24400 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
24401 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
24402 if (hostInstance) {
24403 !(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;
24404 }
24405 }
24406
24407 var isRootRenderedBySomeReact = !!container._reactRootContainer;
24408 var rootEl = getReactRootElementInContainer(container);
24409 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
24410
24411 !(!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;
24412
24413 !(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;
24414 };
24415
24416 warnOnInvalidCallback = function (callback, callerName) {
24417 !(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;
24418 };
24419}
24420
24421setRestoreImplementation(restoreControlledState$1);
24422
24423function ReactBatch(root) {
24424 var expirationTime = computeUniqueAsyncExpiration$$1();
24425 this._expirationTime = expirationTime;
24426 this._root = root;
24427 this._next = null;
24428 this._callbacks = null;
24429 this._didComplete = false;
24430 this._hasChildren = false;
24431 this._children = null;
24432 this._defer = true;
24433}
24434ReactBatch.prototype.render = function (children) {
24435 var _this = this;
24436
24437 (function () {
24438 if (!_this._defer) {
24439 {
24440 throw ReactError('batch.render: Cannot render a batch that already committed.');
24441 }
24442 }
24443 })();
24444 this._hasChildren = true;
24445 this._children = children;
24446 var internalRoot = this._root._internalRoot;
24447 var expirationTime = this._expirationTime;
24448 var work = new ReactWork();
24449 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit);
24450 return work;
24451};
24452ReactBatch.prototype.then = function (onComplete) {
24453 if (this._didComplete) {
24454 onComplete();
24455 return;
24456 }
24457 var callbacks = this._callbacks;
24458 if (callbacks === null) {
24459 callbacks = this._callbacks = [];
24460 }
24461 callbacks.push(onComplete);
24462};
24463ReactBatch.prototype.commit = function () {
24464 var _this2 = this;
24465
24466 var internalRoot = this._root._internalRoot;
24467 var firstBatch = internalRoot.firstBatch;
24468 (function () {
24469 if (!(_this2._defer && firstBatch !== null)) {
24470 {
24471 throw ReactError('batch.commit: Cannot commit a batch multiple times.');
24472 }
24473 }
24474 })();
24475
24476 if (!this._hasChildren) {
24477 // This batch is empty. Return.
24478 this._next = null;
24479 this._defer = false;
24480 return;
24481 }
24482
24483 var expirationTime = this._expirationTime;
24484
24485 // Ensure this is the first batch in the list.
24486 if (firstBatch !== this) {
24487 // This batch is not the earliest batch. We need to move it to the front.
24488 // Update its expiration time to be the expiration time of the earliest
24489 // batch, so that we can flush it without flushing the other batches.
24490 if (this._hasChildren) {
24491 expirationTime = this._expirationTime = firstBatch._expirationTime;
24492 // Rendering this batch again ensures its children will be the final state
24493 // when we flush (updates are processed in insertion order: last
24494 // update wins).
24495 // TODO: This forces a restart. Should we print a warning?
24496 this.render(this._children);
24497 }
24498
24499 // Remove the batch from the list.
24500 var previous = null;
24501 var batch = firstBatch;
24502 while (batch !== this) {
24503 previous = batch;
24504 batch = batch._next;
24505 }
24506 (function () {
24507 if (!(previous !== null)) {
24508 {
24509 throw ReactError('batch.commit: Cannot commit a batch multiple times.');
24510 }
24511 }
24512 })();
24513 previous._next = batch._next;
24514
24515 // Add it to the front.
24516 this._next = firstBatch;
24517 firstBatch = internalRoot.firstBatch = this;
24518 }
24519
24520 // Synchronously flush all the work up to this batch's expiration time.
24521 this._defer = false;
24522 flushRoot$$1(internalRoot, expirationTime);
24523
24524 // Pop the batch from the list.
24525 var next = this._next;
24526 this._next = null;
24527 firstBatch = internalRoot.firstBatch = next;
24528
24529 // Append the next earliest batch's children to the update queue.
24530 if (firstBatch !== null && firstBatch._hasChildren) {
24531 firstBatch.render(firstBatch._children);
24532 }
24533};
24534ReactBatch.prototype._onComplete = function () {
24535 if (this._didComplete) {
24536 return;
24537 }
24538 this._didComplete = true;
24539 var callbacks = this._callbacks;
24540 if (callbacks === null) {
24541 return;
24542 }
24543 // TODO: Error handling.
24544 for (var i = 0; i < callbacks.length; i++) {
24545 var _callback = callbacks[i];
24546 _callback();
24547 }
24548};
24549
24550function ReactWork() {
24551 this._callbacks = null;
24552 this._didCommit = false;
24553 // TODO: Avoid need to bind by replacing callbacks in the update queue with
24554 // list of Work objects.
24555 this._onCommit = this._onCommit.bind(this);
24556}
24557ReactWork.prototype.then = function (onCommit) {
24558 if (this._didCommit) {
24559 onCommit();
24560 return;
24561 }
24562 var callbacks = this._callbacks;
24563 if (callbacks === null) {
24564 callbacks = this._callbacks = [];
24565 }
24566 callbacks.push(onCommit);
24567};
24568ReactWork.prototype._onCommit = function () {
24569 if (this._didCommit) {
24570 return;
24571 }
24572 this._didCommit = true;
24573 var callbacks = this._callbacks;
24574 if (callbacks === null) {
24575 return;
24576 }
24577 // TODO: Error handling.
24578 for (var i = 0; i < callbacks.length; i++) {
24579 var _callback2 = callbacks[i];
24580 (function () {
24581 if (!(typeof _callback2 === 'function')) {
24582 {
24583 throw ReactError('Invalid argument passed as callback. Expected a function. Instead received: ' + _callback2);
24584 }
24585 }
24586 })();
24587 _callback2();
24588 }
24589};
24590
24591function ReactRoot(container, isConcurrent, hydrate) {
24592 var root = createContainer(container, isConcurrent, hydrate);
24593 this._internalRoot = root;
24594}
24595ReactRoot.prototype.render = function (children, callback) {
24596 var root = this._internalRoot;
24597 var work = new ReactWork();
24598 callback = callback === undefined ? null : callback;
24599 {
24600 warnOnInvalidCallback(callback, 'render');
24601 }
24602 if (callback !== null) {
24603 work.then(callback);
24604 }
24605 updateContainer(children, root, null, work._onCommit);
24606 return work;
24607};
24608ReactRoot.prototype.unmount = function (callback) {
24609 var root = this._internalRoot;
24610 var work = new ReactWork();
24611 callback = callback === undefined ? null : callback;
24612 {
24613 warnOnInvalidCallback(callback, 'render');
24614 }
24615 if (callback !== null) {
24616 work.then(callback);
24617 }
24618 updateContainer(null, root, null, work._onCommit);
24619 return work;
24620};
24621ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) {
24622 var root = this._internalRoot;
24623 var work = new ReactWork();
24624 callback = callback === undefined ? null : callback;
24625 {
24626 warnOnInvalidCallback(callback, 'render');
24627 }
24628 if (callback !== null) {
24629 work.then(callback);
24630 }
24631 updateContainer(children, root, parentComponent, work._onCommit);
24632 return work;
24633};
24634ReactRoot.prototype.createBatch = function () {
24635 var batch = new ReactBatch(this);
24636 var expirationTime = batch._expirationTime;
24637
24638 var internalRoot = this._internalRoot;
24639 var firstBatch = internalRoot.firstBatch;
24640 if (firstBatch === null) {
24641 internalRoot.firstBatch = batch;
24642 batch._next = null;
24643 } else {
24644 // Insert sorted by expiration time then insertion order
24645 var insertAfter = null;
24646 var insertBefore = firstBatch;
24647 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
24648 insertAfter = insertBefore;
24649 insertBefore = insertBefore._next;
24650 }
24651 batch._next = insertBefore;
24652 if (insertAfter !== null) {
24653 insertAfter._next = batch;
24654 }
24655 }
24656
24657 return batch;
24658};
24659
24660/**
24661 * True if the supplied DOM node is a valid node element.
24662 *
24663 * @param {?DOMElement} node The candidate DOM node.
24664 * @return {boolean} True if the DOM is a valid DOM node.
24665 * @internal
24666 */
24667function isValidContainer(node) {
24668 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 '));
24669}
24670
24671function getReactRootElementInContainer(container) {
24672 if (!container) {
24673 return null;
24674 }
24675
24676 if (container.nodeType === DOCUMENT_NODE) {
24677 return container.documentElement;
24678 } else {
24679 return container.firstChild;
24680 }
24681}
24682
24683function shouldHydrateDueToLegacyHeuristic(container) {
24684 var rootElement = getReactRootElementInContainer(container);
24685 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
24686}
24687
24688setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1);
24689
24690var warnedAboutHydrateAPI = false;
24691
24692function legacyCreateRootFromDOMContainer(container, forceHydrate) {
24693 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
24694 // First clear any existing content.
24695 if (!shouldHydrate) {
24696 var warned = false;
24697 var rootSibling = void 0;
24698 while (rootSibling = container.lastChild) {
24699 {
24700 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
24701 warned = true;
24702 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.');
24703 }
24704 }
24705 container.removeChild(rootSibling);
24706 }
24707 }
24708 {
24709 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
24710 warnedAboutHydrateAPI = true;
24711 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.');
24712 }
24713 }
24714 // Legacy roots are not async by default.
24715 var isConcurrent = false;
24716 return new ReactRoot(container, isConcurrent, shouldHydrate);
24717}
24718
24719function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
24720 {
24721 topLevelUpdateWarnings(container);
24722 }
24723
24724 // TODO: Without `any` type, Flow says "Property cannot be accessed on any
24725 // member of intersection type." Whyyyyyy.
24726 var root = container._reactRootContainer;
24727 if (!root) {
24728 // Initial mount
24729 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
24730 if (typeof callback === 'function') {
24731 var originalCallback = callback;
24732 callback = function () {
24733 var instance = getPublicRootInstance(root._internalRoot);
24734 originalCallback.call(instance);
24735 };
24736 }
24737 // Initial mount should not be batched.
24738 unbatchedUpdates$$1(function () {
24739 if (parentComponent != null) {
24740 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
24741 } else {
24742 root.render(children, callback);
24743 }
24744 });
24745 } else {
24746 if (typeof callback === 'function') {
24747 var _originalCallback = callback;
24748 callback = function () {
24749 var instance = getPublicRootInstance(root._internalRoot);
24750 _originalCallback.call(instance);
24751 };
24752 }
24753 // Update
24754 if (parentComponent != null) {
24755 root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback);
24756 } else {
24757 root.render(children, callback);
24758 }
24759 }
24760 return getPublicRootInstance(root._internalRoot);
24761}
24762
24763function createPortal$$1(children, container) {
24764 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
24765
24766 (function () {
24767 if (!isValidContainer(container)) {
24768 {
24769 throw ReactError('Target container is not a DOM element.');
24770 }
24771 }
24772 })();
24773 // TODO: pass ReactDOM portal implementation as third argument
24774 return createPortal$1(children, container, null, key);
24775}
24776
24777var ReactDOM = {
24778 createPortal: createPortal$$1,
24779
24780 findDOMNode: function (componentOrElement) {
24781 {
24782 var owner = ReactCurrentOwner.current;
24783 if (owner !== null && owner.stateNode !== null) {
24784 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
24785 !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;
24786 owner.stateNode._warnedAboutRefsInRender = true;
24787 }
24788 }
24789 if (componentOrElement == null) {
24790 return null;
24791 }
24792 if (componentOrElement.nodeType === ELEMENT_NODE) {
24793 return componentOrElement;
24794 }
24795 {
24796 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
24797 }
24798 return findHostInstance(componentOrElement);
24799 },
24800 hydrate: function (element, container, callback) {
24801 (function () {
24802 if (!isValidContainer(container)) {
24803 {
24804 throw ReactError('Target container is not a DOM element.');
24805 }
24806 }
24807 })();
24808 {
24809 !!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;
24810 }
24811 // TODO: throw or warn if we couldn't hydrate?
24812 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
24813 },
24814 render: function (element, container, callback) {
24815 (function () {
24816 if (!isValidContainer(container)) {
24817 {
24818 throw ReactError('Target container is not a DOM element.');
24819 }
24820 }
24821 })();
24822 {
24823 !!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;
24824 }
24825 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
24826 },
24827 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
24828 (function () {
24829 if (!isValidContainer(containerNode)) {
24830 {
24831 throw ReactError('Target container is not a DOM element.');
24832 }
24833 }
24834 })();
24835 (function () {
24836 if (!(parentComponent != null && has(parentComponent))) {
24837 {
24838 throw ReactError('parentComponent must be a valid React Component');
24839 }
24840 }
24841 })();
24842 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
24843 },
24844 unmountComponentAtNode: function (container) {
24845 (function () {
24846 if (!isValidContainer(container)) {
24847 {
24848 throw ReactError('unmountComponentAtNode(...): Target container is not a DOM element.');
24849 }
24850 }
24851 })();
24852
24853 {
24854 !!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;
24855 }
24856
24857 if (container._reactRootContainer) {
24858 {
24859 var rootEl = getReactRootElementInContainer(container);
24860 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
24861 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
24862 }
24863
24864 // Unmount should not be batched.
24865 unbatchedUpdates$$1(function () {
24866 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
24867 container._reactRootContainer = null;
24868 });
24869 });
24870 // If you call unmountComponentAtNode twice in quick succession, you'll
24871 // get `true` twice. That's probably fine?
24872 return true;
24873 } else {
24874 {
24875 var _rootEl = getReactRootElementInContainer(container);
24876 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl));
24877
24878 // Check if the container itself is a React root node.
24879 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
24880
24881 !!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;
24882 }
24883
24884 return false;
24885 }
24886 },
24887
24888
24889 // Temporary alias since we already shipped React 16 RC with it.
24890 // TODO: remove in React 17.
24891 unstable_createPortal: function () {
24892 if (!didWarnAboutUnstableCreatePortal) {
24893 didWarnAboutUnstableCreatePortal = true;
24894 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.');
24895 }
24896 return createPortal$$1.apply(undefined, arguments);
24897 },
24898
24899
24900 unstable_batchedUpdates: batchedUpdates$1,
24901
24902 unstable_interactiveUpdates: interactiveUpdates$1,
24903
24904 flushSync: flushSync$$1,
24905
24906 unstable_createRoot: createRoot,
24907 unstable_flushControlled: flushControlled$$1,
24908
24909 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
24910 // Keep in sync with ReactDOMUnstableNativeDependencies.js
24911 // and ReactTestUtils.js. This is an array for better minification.
24912 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects$$1]
24913 }
24914};
24915
24916function createRoot(container, options) {
24917 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
24918 (function () {
24919 if (!isValidContainer(container)) {
24920 {
24921 throw ReactError(functionName + '(...): Target container is not a DOM element.');
24922 }
24923 }
24924 })();
24925 {
24926 !!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;
24927 container._reactHasBeenPassedToCreateRootDEV = true;
24928 }
24929 var hydrate = options != null && options.hydrate === true;
24930 return new ReactRoot(container, true, hydrate);
24931}
24932
24933if (enableStableConcurrentModeAPIs) {
24934 ReactDOM.createRoot = createRoot;
24935 ReactDOM.unstable_createRoot = undefined;
24936}
24937
24938var foundDevTools = injectIntoDevTools({
24939 findFiberByHostInstance: getClosestInstanceFromNode,
24940 bundleType: 1,
24941 version: ReactVersion,
24942 rendererPackageName: 'react-dom'
24943});
24944
24945{
24946 if (!foundDevTools && canUseDOM && window.top === window.self) {
24947 // If we're in Chrome or Firefox, provide a download link if not installed.
24948 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
24949 var protocol = window.location.protocol;
24950 // Don't warn in exotic cases like chrome-extension://.
24951 if (/^(https?|file):$/.test(protocol)) {
24952 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');
24953 }
24954 }
24955 }
24956}
24957
24958
24959
24960var ReactFire = Object.freeze({
24961 default: ReactDOM
24962});
24963
24964var ReactFire$1 = ( ReactFire && ReactDOM ) || ReactFire;
24965
24966// TODO: decide on the top-level export form.
24967// This is hacky but makes it work with both Rollup and Jest.
24968var unstableFire = ReactFire$1.default || ReactFire$1;
24969
24970return unstableFire;
24971
24972})));