UNPKG

978 kBJavaScriptView Raw
1/** @license React v16.10.2
2 * react-dom.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactDOM = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18// Do not require this module directly! Use normal `invariant` calls 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 normal `invariant` calls with
23// template literal strings. The messages will be converted to ReactError during
24// build, and in production they will be minified.
25function ReactError(error) {
26 error.name = 'Invariant Violation';
27 return error;
28}
29
30/**
31 * Use invariant() to assert state which your program assumes to be true.
32 *
33 * Provide sprintf-style format (only %s is supported) and arguments
34 * to provide information about what broke and what you were
35 * expecting.
36 *
37 * The invariant message will be stripped in production, but the invariant
38 * will remain to ensure logic does not differ in production.
39 */
40
41(function () {
42 if (!React) {
43 {
44 throw ReactError(Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM."));
45 }
46 }
47})();
48
49/**
50 * Injectable ordering of event plugins.
51 */
52var eventPluginOrder = null;
53/**
54 * Injectable mapping from names to event plugin modules.
55 */
56
57var namesToPlugins = {};
58/**
59 * Recomputes the plugin list using the injected plugins and plugin ordering.
60 *
61 * @private
62 */
63
64function recomputePluginOrdering() {
65 if (!eventPluginOrder) {
66 // Wait until an `eventPluginOrder` is injected.
67 return;
68 }
69
70 for (var pluginName in namesToPlugins) {
71 var pluginModule = namesToPlugins[pluginName];
72 var pluginIndex = eventPluginOrder.indexOf(pluginName);
73
74 (function () {
75 if (!(pluginIndex > -1)) {
76 {
77 throw ReactError(Error("EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`."));
78 }
79 }
80 })();
81
82 if (plugins[pluginIndex]) {
83 continue;
84 }
85
86 (function () {
87 if (!pluginModule.extractEvents) {
88 {
89 throw ReactError(Error("EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not."));
90 }
91 }
92 })();
93
94 plugins[pluginIndex] = pluginModule;
95 var publishedEvents = pluginModule.eventTypes;
96
97 for (var eventName in publishedEvents) {
98 (function () {
99 if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
100 {
101 throw ReactError(Error("EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`."));
102 }
103 }
104 })();
105 }
106 }
107}
108/**
109 * Publishes an event so that it can be dispatched by the supplied plugin.
110 *
111 * @param {object} dispatchConfig Dispatch configuration for the event.
112 * @param {object} PluginModule Plugin publishing the event.
113 * @return {boolean} True if the event was successfully published.
114 * @private
115 */
116
117
118function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
119 (function () {
120 if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
121 {
122 throw ReactError(Error("EventPluginHub: More than one plugin attempted to publish the same event name, `" + eventName + "`."));
123 }
124 }
125 })();
126
127 eventNameDispatchConfigs[eventName] = dispatchConfig;
128 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
129
130 if (phasedRegistrationNames) {
131 for (var phaseName in phasedRegistrationNames) {
132 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
133 var phasedRegistrationName = phasedRegistrationNames[phaseName];
134 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
135 }
136 }
137
138 return true;
139 } else if (dispatchConfig.registrationName) {
140 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
141 return true;
142 }
143
144 return false;
145}
146/**
147 * Publishes a registration name that is used to identify dispatched events.
148 *
149 * @param {string} registrationName Registration name to add.
150 * @param {object} PluginModule Plugin publishing the event.
151 * @private
152 */
153
154
155function publishRegistrationName(registrationName, pluginModule, eventName) {
156 (function () {
157 if (!!registrationNameModules[registrationName]) {
158 {
159 throw ReactError(Error("EventPluginHub: More than one plugin attempted to publish the same registration name, `" + registrationName + "`."));
160 }
161 }
162 })();
163
164 registrationNameModules[registrationName] = pluginModule;
165 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
166
167 {
168 var lowerCasedName = registrationName.toLowerCase();
169 possibleRegistrationNames[lowerCasedName] = registrationName;
170
171 if (registrationName === 'onDoubleClick') {
172 possibleRegistrationNames.ondblclick = registrationName;
173 }
174 }
175}
176/**
177 * Registers plugins so that they can extract and dispatch events.
178 *
179 * @see {EventPluginHub}
180 */
181
182/**
183 * Ordered list of injected plugins.
184 */
185
186
187var plugins = [];
188/**
189 * Mapping from event name to dispatch config
190 */
191
192var eventNameDispatchConfigs = {};
193/**
194 * Mapping from registration name to plugin module
195 */
196
197var registrationNameModules = {};
198/**
199 * Mapping from registration name to event name
200 */
201
202var registrationNameDependencies = {};
203/**
204 * Mapping from lowercase registration names to the properly cased version,
205 * used to warn in the case of missing event handlers. Available
206 * only in true.
207 * @type {Object}
208 */
209
210var possibleRegistrationNames = {}; // Trust the developer to only use possibleRegistrationNames in true
211
212/**
213 * Injects an ordering of plugins (by plugin name). This allows the ordering
214 * to be decoupled from injection of the actual plugins so that ordering is
215 * always deterministic regardless of packaging, on-the-fly injection, etc.
216 *
217 * @param {array} InjectedEventPluginOrder
218 * @internal
219 * @see {EventPluginHub.injection.injectEventPluginOrder}
220 */
221
222function injectEventPluginOrder(injectedEventPluginOrder) {
223 (function () {
224 if (!!eventPluginOrder) {
225 {
226 throw ReactError(Error("EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."));
227 }
228 }
229 })(); // Clone the ordering so it cannot be dynamically mutated.
230
231
232 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
233 recomputePluginOrdering();
234}
235/**
236 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
237 * in the ordering injected by `injectEventPluginOrder`.
238 *
239 * Plugins can be injected as part of page initialization or on-the-fly.
240 *
241 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
242 * @internal
243 * @see {EventPluginHub.injection.injectEventPluginsByName}
244 */
245
246function injectEventPluginsByName(injectedNamesToPlugins) {
247 var isOrderingDirty = false;
248
249 for (var pluginName in injectedNamesToPlugins) {
250 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
251 continue;
252 }
253
254 var pluginModule = injectedNamesToPlugins[pluginName];
255
256 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
257 (function () {
258 if (!!namesToPlugins[pluginName]) {
259 {
260 throw ReactError(Error("EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`."));
261 }
262 }
263 })();
264
265 namesToPlugins[pluginName] = pluginModule;
266 isOrderingDirty = true;
267 }
268 }
269
270 if (isOrderingDirty) {
271 recomputePluginOrdering();
272 }
273}
274
275var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
276 var funcArgs = Array.prototype.slice.call(arguments, 3);
277
278 try {
279 func.apply(context, funcArgs);
280 } catch (error) {
281 this.onError(error);
282 }
283};
284
285{
286 // In DEV mode, we swap out invokeGuardedCallback for a special version
287 // that plays more nicely with the browser's DevTools. The idea is to preserve
288 // "Pause on exceptions" behavior. Because React wraps all user-provided
289 // functions in invokeGuardedCallback, and the production version of
290 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
291 // like caught exceptions, and the DevTools won't pause unless the developer
292 // takes the extra step of enabling pause on caught exceptions. This is
293 // unintuitive, though, because even though React has caught the error, from
294 // the developer's perspective, the error is uncaught.
295 //
296 // To preserve the expected "Pause on exceptions" behavior, we don't use a
297 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
298 // DOM node, and call the user-provided callback from inside an event handler
299 // for that fake event. If the callback throws, the error is "captured" using
300 // a global event handler. But because the error happens in a different
301 // event loop context, it does not interrupt the normal program flow.
302 // Effectively, this gives us try-catch behavior without actually using
303 // try-catch. Neat!
304 // Check that the browser supports the APIs we need to implement our special
305 // DEV version of invokeGuardedCallback
306 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
307 var fakeNode = document.createElement('react');
308
309 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
310 // If document doesn't exist we know for sure we will crash in this method
311 // when we call document.createEvent(). However this can cause confusing
312 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
313 // So we preemptively throw with a better message instead.
314 (function () {
315 if (!(typeof document !== 'undefined')) {
316 {
317 throw ReactError(Error("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."));
318 }
319 }
320 })();
321
322 var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
323 // set this to true at the beginning, then set it to false right after
324 // calling the function. If the function errors, `didError` will never be
325 // set to false. This strategy works even if the browser is flaky and
326 // fails to call our global error handler, because it doesn't rely on
327 // the error event at all.
328
329 var didError = true; // Keeps track of the value of window.event so that we can reset it
330 // during the callback to let user code access window.event in the
331 // browsers that support it.
332
333 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
334 // dispatching: https://github.com/facebook/react/issues/13688
335
336 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
337 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
338 // call the user-provided callback.
339
340 var funcArgs = Array.prototype.slice.call(arguments, 3);
341
342 function callCallback() {
343 // We immediately remove the callback from event listeners so that
344 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
345 // nested call would trigger the fake event handlers of any call higher
346 // in the stack.
347 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
348 // window.event assignment in both IE <= 10 as they throw an error
349 // "Member not found" in strict mode, and in Firefox which does not
350 // support window.event.
351
352 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
353 window.event = windowEvent;
354 }
355
356 func.apply(context, funcArgs);
357 didError = false;
358 } // Create a global error event handler. We use this to capture the value
359 // that was thrown. It's possible that this error handler will fire more
360 // than once; for example, if non-React code also calls `dispatchEvent`
361 // and a handler for that event throws. We should be resilient to most of
362 // those cases. Even if our error event handler fires more than once, the
363 // last error event is always used. If the callback actually does error,
364 // we know that the last error event is the correct one, because it's not
365 // possible for anything else to have happened in between our callback
366 // erroring and the code that follows the `dispatchEvent` call below. If
367 // the callback doesn't error, but the error event was fired, we know to
368 // ignore it because `didError` will be false, as described above.
369
370
371 var error; // Use this to track whether the error event is ever called.
372
373 var didSetError = false;
374 var isCrossOriginError = false;
375
376 function handleWindowError(event) {
377 error = event.error;
378 didSetError = true;
379
380 if (error === null && event.colno === 0 && event.lineno === 0) {
381 isCrossOriginError = true;
382 }
383
384 if (event.defaultPrevented) {
385 // Some other error handler has prevented default.
386 // Browsers silence the error report if this happens.
387 // We'll remember this to later decide whether to log it or not.
388 if (error != null && typeof error === 'object') {
389 try {
390 error._suppressLogging = true;
391 } catch (inner) {// Ignore.
392 }
393 }
394 }
395 } // Create a fake event type.
396
397
398 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
399
400 window.addEventListener('error', handleWindowError);
401 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
402 // errors, it will trigger our global error handler.
403
404 evt.initEvent(evtType, false, false);
405 fakeNode.dispatchEvent(evt);
406
407 if (windowEventDescriptor) {
408 Object.defineProperty(window, 'event', windowEventDescriptor);
409 }
410
411 if (didError) {
412 if (!didSetError) {
413 // The callback errored, but the error event never fired.
414 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.');
415 } else if (isCrossOriginError) {
416 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.');
417 }
418
419 this.onError(error);
420 } // Remove our event listeners
421
422
423 window.removeEventListener('error', handleWindowError);
424 };
425
426 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
427 }
428}
429
430var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
431
432var hasError = false;
433var caughtError = null; // Used by event system to capture/rethrow the first error.
434
435var hasRethrowError = false;
436var rethrowError = null;
437var reporter = {
438 onError: function (error) {
439 hasError = true;
440 caughtError = error;
441 }
442};
443/**
444 * Call a function while guarding against errors that happens within it.
445 * Returns an error if it throws, otherwise null.
446 *
447 * In production, this is implemented using a try-catch. The reason we don't
448 * use a try-catch directly is so that we can swap out a different
449 * implementation in DEV mode.
450 *
451 * @param {String} name of the guard to use for logging or debugging
452 * @param {Function} func The function to invoke
453 * @param {*} context The context to use when calling the function
454 * @param {...*} args Arguments for function
455 */
456
457function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
458 hasError = false;
459 caughtError = null;
460 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
461}
462/**
463 * Same as invokeGuardedCallback, but instead of returning an error, it stores
464 * it in a global so it can be rethrown by `rethrowCaughtError` later.
465 * TODO: See if caughtError and rethrowError can be unified.
466 *
467 * @param {String} name of the guard to use for logging or debugging
468 * @param {Function} func The function to invoke
469 * @param {*} context The context to use when calling the function
470 * @param {...*} args Arguments for function
471 */
472
473function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
474 invokeGuardedCallback.apply(this, arguments);
475
476 if (hasError) {
477 var error = clearCaughtError();
478
479 if (!hasRethrowError) {
480 hasRethrowError = true;
481 rethrowError = error;
482 }
483 }
484}
485/**
486 * During execution of guarded functions we will capture the first error which
487 * we will rethrow to be handled by the top level error handler.
488 */
489
490function rethrowCaughtError() {
491 if (hasRethrowError) {
492 var error = rethrowError;
493 hasRethrowError = false;
494 rethrowError = null;
495 throw error;
496 }
497}
498function hasCaughtError() {
499 return hasError;
500}
501function clearCaughtError() {
502 if (hasError) {
503 var error = caughtError;
504 hasError = false;
505 caughtError = null;
506 return error;
507 } else {
508 (function () {
509 {
510 {
511 throw ReactError(Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue."));
512 }
513 }
514 })();
515 }
516}
517
518/**
519 * Similar to invariant but only logs a warning if the condition is not met.
520 * This can be used to log issues in development environments in critical
521 * paths. Removing the logging code for production environments will keep the
522 * same logic and follow the same code paths.
523 */
524var warningWithoutStack = function () {};
525
526{
527 warningWithoutStack = function (condition, format) {
528 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
529 args[_key - 2] = arguments[_key];
530 }
531
532 if (format === undefined) {
533 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
534 }
535
536 if (args.length > 8) {
537 // Check before the condition to catch violations early.
538 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
539 }
540
541 if (condition) {
542 return;
543 }
544
545 if (typeof console !== 'undefined') {
546 var argsWithFormat = args.map(function (item) {
547 return '' + item;
548 });
549 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
550 // breaks IE9: https://github.com/facebook/react/issues/13610
551
552 Function.prototype.apply.call(console.error, console, argsWithFormat);
553 }
554
555 try {
556 // --- Welcome to debugging React ---
557 // This error was thrown as a convenience so that you can use this stack
558 // to find the callsite that caused this warning to fire.
559 var argIndex = 0;
560 var message = 'Warning: ' + format.replace(/%s/g, function () {
561 return args[argIndex++];
562 });
563 throw new Error(message);
564 } catch (x) {}
565 };
566}
567
568var warningWithoutStack$1 = warningWithoutStack;
569
570var getFiberCurrentPropsFromNode = null;
571var getInstanceFromNode = null;
572var getNodeFromInstance = null;
573function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
574 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
575 getInstanceFromNode = getInstanceFromNodeImpl;
576 getNodeFromInstance = getNodeFromInstanceImpl;
577
578 {
579 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
580 }
581}
582var validateEventDispatches;
583
584{
585 validateEventDispatches = function (event) {
586 var dispatchListeners = event._dispatchListeners;
587 var dispatchInstances = event._dispatchInstances;
588 var listenersIsArr = Array.isArray(dispatchListeners);
589 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
590 var instancesIsArr = Array.isArray(dispatchInstances);
591 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
592 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
593 };
594}
595/**
596 * Dispatch the event to the listener.
597 * @param {SyntheticEvent} event SyntheticEvent to handle
598 * @param {function} listener Application-level callback
599 * @param {*} inst Internal component instance
600 */
601
602
603function executeDispatch(event, listener, inst) {
604 var type = event.type || 'unknown-event';
605 event.currentTarget = getNodeFromInstance(inst);
606 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
607 event.currentTarget = null;
608}
609/**
610 * Standard/simple iteration through an event's collected dispatches.
611 */
612
613function executeDispatchesInOrder(event) {
614 var dispatchListeners = event._dispatchListeners;
615 var dispatchInstances = event._dispatchInstances;
616
617 {
618 validateEventDispatches(event);
619 }
620
621 if (Array.isArray(dispatchListeners)) {
622 for (var i = 0; i < dispatchListeners.length; i++) {
623 if (event.isPropagationStopped()) {
624 break;
625 } // Listeners and Instances are two parallel arrays that are always in sync.
626
627
628 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
629 }
630 } else if (dispatchListeners) {
631 executeDispatch(event, dispatchListeners, dispatchInstances);
632 }
633
634 event._dispatchListeners = null;
635 event._dispatchInstances = null;
636}
637/**
638 * @see executeDispatchesInOrderStopAtTrueImpl
639 */
640
641
642
643/**
644 * Execution of a "direct" dispatch - there must be at most one dispatch
645 * accumulated on the event or it is considered an error. It doesn't really make
646 * sense for an event with multiple dispatches (bubbled) to keep track of the
647 * return values at each dispatch execution, but it does tend to make sense when
648 * dealing with "direct" dispatches.
649 *
650 * @return {*} The return value of executing the single dispatch.
651 */
652
653
654/**
655 * @param {SyntheticEvent} event
656 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
657 */
658
659/**
660 * Accumulates items that must not be null or undefined into the first one. This
661 * is used to conserve memory by avoiding array allocations, and thus sacrifices
662 * API cleanness. Since `current` can be null before being passed in and not
663 * null after this function, make sure to assign it back to `current`:
664 *
665 * `a = accumulateInto(a, b);`
666 *
667 * This API should be sparingly used. Try `accumulate` for something cleaner.
668 *
669 * @return {*|array<*>} An accumulation of items.
670 */
671
672function accumulateInto(current, next) {
673 (function () {
674 if (!(next != null)) {
675 {
676 throw ReactError(Error("accumulateInto(...): Accumulated items must not be null or undefined."));
677 }
678 }
679 })();
680
681 if (current == null) {
682 return next;
683 } // Both are not empty. Warning: Never call x.concat(y) when you are not
684 // certain that x is an Array (x could be a string with concat method).
685
686
687 if (Array.isArray(current)) {
688 if (Array.isArray(next)) {
689 current.push.apply(current, next);
690 return current;
691 }
692
693 current.push(next);
694 return current;
695 }
696
697 if (Array.isArray(next)) {
698 // A bit too dangerous to mutate `next`.
699 return [current].concat(next);
700 }
701
702 return [current, next];
703}
704
705/**
706 * @param {array} arr an "accumulation" of items which is either an Array or
707 * a single item. Useful when paired with the `accumulate` module. This is a
708 * simple utility that allows us to reason about a collection of items, but
709 * handling the case when there is exactly one item (and we do not need to
710 * allocate an array).
711 * @param {function} cb Callback invoked with each element or a collection.
712 * @param {?} [scope] Scope used as `this` in a callback.
713 */
714function forEachAccumulated(arr, cb, scope) {
715 if (Array.isArray(arr)) {
716 arr.forEach(cb, scope);
717 } else if (arr) {
718 cb.call(scope, arr);
719 }
720}
721
722/**
723 * Internal queue of events that have accumulated their dispatches and are
724 * waiting to have their dispatches executed.
725 */
726
727var eventQueue = null;
728/**
729 * Dispatches an event and releases it back into the pool, unless persistent.
730 *
731 * @param {?object} event Synthetic event to be dispatched.
732 * @private
733 */
734
735var executeDispatchesAndRelease = function (event) {
736 if (event) {
737 executeDispatchesInOrder(event);
738
739 if (!event.isPersistent()) {
740 event.constructor.release(event);
741 }
742 }
743};
744
745var executeDispatchesAndReleaseTopLevel = function (e) {
746 return executeDispatchesAndRelease(e);
747};
748
749function runEventsInBatch(events) {
750 if (events !== null) {
751 eventQueue = accumulateInto(eventQueue, events);
752 } // Set `eventQueue` to null before processing it so that we can tell if more
753 // events get enqueued while processing.
754
755
756 var processingEventQueue = eventQueue;
757 eventQueue = null;
758
759 if (!processingEventQueue) {
760 return;
761 }
762
763 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
764
765 (function () {
766 if (!!eventQueue) {
767 {
768 throw ReactError(Error("processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."));
769 }
770 }
771 })(); // This would be a good time to rethrow if any of the event handlers threw.
772
773
774 rethrowCaughtError();
775}
776
777function isInteractive(tag) {
778 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
779}
780
781function shouldPreventMouseEvent(name, type, props) {
782 switch (name) {
783 case 'onClick':
784 case 'onClickCapture':
785 case 'onDoubleClick':
786 case 'onDoubleClickCapture':
787 case 'onMouseDown':
788 case 'onMouseDownCapture':
789 case 'onMouseMove':
790 case 'onMouseMoveCapture':
791 case 'onMouseUp':
792 case 'onMouseUpCapture':
793 return !!(props.disabled && isInteractive(type));
794
795 default:
796 return false;
797 }
798}
799/**
800 * This is a unified interface for event plugins to be installed and configured.
801 *
802 * Event plugins can implement the following properties:
803 *
804 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
805 * Required. When a top-level event is fired, this method is expected to
806 * extract synthetic events that will in turn be queued and dispatched.
807 *
808 * `eventTypes` {object}
809 * Optional, plugins that fire events must publish a mapping of registration
810 * names that are used to register listeners. Values of this mapping must
811 * be objects that contain `registrationName` or `phasedRegistrationNames`.
812 *
813 * `executeDispatch` {function(object, function, string)}
814 * Optional, allows plugins to override how an event gets dispatched. By
815 * default, the listener is simply invoked.
816 *
817 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
818 *
819 * @public
820 */
821
822/**
823 * Methods for injecting dependencies.
824 */
825
826
827var injection = {
828 /**
829 * @param {array} InjectedEventPluginOrder
830 * @public
831 */
832 injectEventPluginOrder: injectEventPluginOrder,
833
834 /**
835 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
836 */
837 injectEventPluginsByName: injectEventPluginsByName
838};
839/**
840 * @param {object} inst The instance, which is the source of events.
841 * @param {string} registrationName Name of listener (e.g. `onClick`).
842 * @return {?function} The stored callback.
843 */
844
845function getListener(inst, registrationName) {
846 var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
847 // live here; needs to be moved to a better place soon
848
849 var stateNode = inst.stateNode;
850
851 if (!stateNode) {
852 // Work in progress (ex: onload events in incremental mode).
853 return null;
854 }
855
856 var props = getFiberCurrentPropsFromNode(stateNode);
857
858 if (!props) {
859 // Work in progress.
860 return null;
861 }
862
863 listener = props[registrationName];
864
865 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
866 return null;
867 }
868
869 (function () {
870 if (!(!listener || typeof listener === 'function')) {
871 {
872 throw ReactError(Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type."));
873 }
874 }
875 })();
876
877 return listener;
878}
879/**
880 * Allows registered plugins an opportunity to extract events from top-level
881 * native browser events.
882 *
883 * @return {*} An accumulation of synthetic events.
884 * @internal
885 */
886
887function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
888 var events = null;
889
890 for (var i = 0; i < plugins.length; i++) {
891 // Not every plugin in the ordering may be loaded at runtime.
892 var possiblePlugin = plugins[i];
893
894 if (possiblePlugin) {
895 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
896
897 if (extractedEvents) {
898 events = accumulateInto(events, extractedEvents);
899 }
900 }
901 }
902
903 return events;
904}
905
906function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
907 var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
908 runEventsInBatch(events);
909}
910
911var FunctionComponent = 0;
912var ClassComponent = 1;
913var IndeterminateComponent = 2; // Before we know whether it is function or class
914
915var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
916
917var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
918
919var HostComponent = 5;
920var HostText = 6;
921var Fragment = 7;
922var Mode = 8;
923var ContextConsumer = 9;
924var ContextProvider = 10;
925var ForwardRef = 11;
926var Profiler = 12;
927var SuspenseComponent = 13;
928var MemoComponent = 14;
929var SimpleMemoComponent = 15;
930var LazyComponent = 16;
931var IncompleteClassComponent = 17;
932var DehydratedFragment = 18;
933var SuspenseListComponent = 19;
934var FundamentalComponent = 20;
935var ScopeComponent = 21;
936
937var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
938// Current owner and dispatcher used to share the same ref,
939// but PR #14548 split them out to better support the react-debug-tools package.
940
941if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
942 ReactSharedInternals.ReactCurrentDispatcher = {
943 current: null
944 };
945}
946
947if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
948 ReactSharedInternals.ReactCurrentBatchConfig = {
949 suspense: null
950 };
951}
952
953var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
954var describeComponentFrame = function (name, source, ownerName) {
955 var sourceInfo = '';
956
957 if (source) {
958 var path = source.fileName;
959 var fileName = path.replace(BEFORE_SLASH_RE, '');
960
961 {
962 // In DEV, include code for a common special case:
963 // prefer "folder/index.js" instead of just "index.js".
964 if (/^index\./.test(fileName)) {
965 var match = path.match(BEFORE_SLASH_RE);
966
967 if (match) {
968 var pathBeforeSlash = match[1];
969
970 if (pathBeforeSlash) {
971 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
972 fileName = folderName + '/' + fileName;
973 }
974 }
975 }
976 }
977
978 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
979 } else if (ownerName) {
980 sourceInfo = ' (created by ' + ownerName + ')';
981 }
982
983 return '\n in ' + (name || 'Unknown') + sourceInfo;
984};
985
986// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
987// nor polyfill, then a plain number is used for performance.
988var hasSymbol = typeof Symbol === 'function' && Symbol.for;
989var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
990var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
991var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
992var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
993var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
994var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
995var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
996// (unstable) APIs that have been removed. Can we remove the symbols?
997
998
999var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
1000var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
1001var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
1002var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
1003var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
1004var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
1005var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
1006var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
1007var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
1008var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
1009var FAUX_ITERATOR_SYMBOL = '@@iterator';
1010function getIteratorFn(maybeIterable) {
1011 if (maybeIterable === null || typeof maybeIterable !== 'object') {
1012 return null;
1013 }
1014
1015 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
1016
1017 if (typeof maybeIterator === 'function') {
1018 return maybeIterator;
1019 }
1020
1021 return null;
1022}
1023
1024/**
1025 * Similar to invariant but only logs a warning if the condition is not met.
1026 * This can be used to log issues in development environments in critical
1027 * paths. Removing the logging code for production environments will keep the
1028 * same logic and follow the same code paths.
1029 */
1030
1031var warning = warningWithoutStack$1;
1032
1033{
1034 warning = function (condition, format) {
1035 if (condition) {
1036 return;
1037 }
1038
1039 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1040 var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args
1041
1042 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1043 args[_key - 2] = arguments[_key];
1044 }
1045
1046 warningWithoutStack$1.apply(void 0, [false, format + '%s'].concat(args, [stack]));
1047 };
1048}
1049
1050var warning$1 = warning;
1051
1052var Uninitialized = -1;
1053var Pending = 0;
1054var Resolved = 1;
1055var Rejected = 2;
1056function refineResolvedLazyComponent(lazyComponent) {
1057 return lazyComponent._status === Resolved ? lazyComponent._result : null;
1058}
1059function initializeLazyComponentType(lazyComponent) {
1060 if (lazyComponent._status === Uninitialized) {
1061 lazyComponent._status = Pending;
1062 var ctor = lazyComponent._ctor;
1063 var thenable = ctor();
1064 lazyComponent._result = thenable;
1065 thenable.then(function (moduleObject) {
1066 if (lazyComponent._status === Pending) {
1067 var defaultExport = moduleObject.default;
1068
1069 {
1070 if (defaultExport === undefined) {
1071 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);
1072 }
1073 }
1074
1075 lazyComponent._status = Resolved;
1076 lazyComponent._result = defaultExport;
1077 }
1078 }, function (error) {
1079 if (lazyComponent._status === Pending) {
1080 lazyComponent._status = Rejected;
1081 lazyComponent._result = error;
1082 }
1083 });
1084 }
1085}
1086
1087function getWrappedName(outerType, innerType, wrapperName) {
1088 var functionName = innerType.displayName || innerType.name || '';
1089 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
1090}
1091
1092function getComponentName(type) {
1093 if (type == null) {
1094 // Host root, text node or just invalid type.
1095 return null;
1096 }
1097
1098 {
1099 if (typeof type.tag === 'number') {
1100 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
1101 }
1102 }
1103
1104 if (typeof type === 'function') {
1105 return type.displayName || type.name || null;
1106 }
1107
1108 if (typeof type === 'string') {
1109 return type;
1110 }
1111
1112 switch (type) {
1113 case REACT_FRAGMENT_TYPE:
1114 return 'Fragment';
1115
1116 case REACT_PORTAL_TYPE:
1117 return 'Portal';
1118
1119 case REACT_PROFILER_TYPE:
1120 return "Profiler";
1121
1122 case REACT_STRICT_MODE_TYPE:
1123 return 'StrictMode';
1124
1125 case REACT_SUSPENSE_TYPE:
1126 return 'Suspense';
1127
1128 case REACT_SUSPENSE_LIST_TYPE:
1129 return 'SuspenseList';
1130 }
1131
1132 if (typeof type === 'object') {
1133 switch (type.$$typeof) {
1134 case REACT_CONTEXT_TYPE:
1135 return 'Context.Consumer';
1136
1137 case REACT_PROVIDER_TYPE:
1138 return 'Context.Provider';
1139
1140 case REACT_FORWARD_REF_TYPE:
1141 return getWrappedName(type, type.render, 'ForwardRef');
1142
1143 case REACT_MEMO_TYPE:
1144 return getComponentName(type.type);
1145
1146 case REACT_LAZY_TYPE:
1147 {
1148 var thenable = type;
1149 var resolvedThenable = refineResolvedLazyComponent(thenable);
1150
1151 if (resolvedThenable) {
1152 return getComponentName(resolvedThenable);
1153 }
1154
1155 break;
1156 }
1157 }
1158 }
1159
1160 return null;
1161}
1162
1163var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1164
1165function describeFiber(fiber) {
1166 switch (fiber.tag) {
1167 case HostRoot:
1168 case HostPortal:
1169 case HostText:
1170 case Fragment:
1171 case ContextProvider:
1172 case ContextConsumer:
1173 return '';
1174
1175 default:
1176 var owner = fiber._debugOwner;
1177 var source = fiber._debugSource;
1178 var name = getComponentName(fiber.type);
1179 var ownerName = null;
1180
1181 if (owner) {
1182 ownerName = getComponentName(owner.type);
1183 }
1184
1185 return describeComponentFrame(name, source, ownerName);
1186 }
1187}
1188
1189function getStackByFiberInDevAndProd(workInProgress) {
1190 var info = '';
1191 var node = workInProgress;
1192
1193 do {
1194 info += describeFiber(node);
1195 node = node.return;
1196 } while (node);
1197
1198 return info;
1199}
1200var current = null;
1201var phase = null;
1202function getCurrentFiberOwnerNameInDevOrNull() {
1203 {
1204 if (current === null) {
1205 return null;
1206 }
1207
1208 var owner = current._debugOwner;
1209
1210 if (owner !== null && typeof owner !== 'undefined') {
1211 return getComponentName(owner.type);
1212 }
1213 }
1214
1215 return null;
1216}
1217function getCurrentFiberStackInDev() {
1218 {
1219 if (current === null) {
1220 return '';
1221 } // Safe because if current fiber exists, we are reconciling,
1222 // and it is guaranteed to be the work-in-progress version.
1223
1224
1225 return getStackByFiberInDevAndProd(current);
1226 }
1227
1228 return '';
1229}
1230function resetCurrentFiber() {
1231 {
1232 ReactDebugCurrentFrame.getCurrentStack = null;
1233 current = null;
1234 phase = null;
1235 }
1236}
1237function setCurrentFiber(fiber) {
1238 {
1239 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1240 current = fiber;
1241 phase = null;
1242 }
1243}
1244function setCurrentPhase(lifeCyclePhase) {
1245 {
1246 phase = lifeCyclePhase;
1247 }
1248}
1249
1250var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1251
1252function endsWith(subject, search) {
1253 var length = subject.length;
1254 return subject.substring(length - search.length, length) === search;
1255}
1256
1257var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1258var _assign = ReactInternals.assign;
1259
1260var PLUGIN_EVENT_SYSTEM = 1;
1261var RESPONDER_EVENT_SYSTEM = 1 << 1;
1262var IS_PASSIVE = 1 << 2;
1263var IS_ACTIVE = 1 << 3;
1264var PASSIVE_NOT_SUPPORTED = 1 << 4;
1265var IS_REPLAYED = 1 << 5;
1266
1267var restoreImpl = null;
1268var restoreTarget = null;
1269var restoreQueue = null;
1270
1271function restoreStateOfTarget(target) {
1272 // We perform this translation at the end of the event loop so that we
1273 // always receive the correct fiber here
1274 var internalInstance = getInstanceFromNode(target);
1275
1276 if (!internalInstance) {
1277 // Unmounted
1278 return;
1279 }
1280
1281 (function () {
1282 if (!(typeof restoreImpl === 'function')) {
1283 {
1284 throw ReactError(Error("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."));
1285 }
1286 }
1287 })();
1288
1289 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
1290 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
1291}
1292
1293function setRestoreImplementation(impl) {
1294 restoreImpl = impl;
1295}
1296function enqueueStateRestore(target) {
1297 if (restoreTarget) {
1298 if (restoreQueue) {
1299 restoreQueue.push(target);
1300 } else {
1301 restoreQueue = [target];
1302 }
1303 } else {
1304 restoreTarget = target;
1305 }
1306}
1307function needsStateRestore() {
1308 return restoreTarget !== null || restoreQueue !== null;
1309}
1310function restoreStateIfNeeded() {
1311 if (!restoreTarget) {
1312 return;
1313 }
1314
1315 var target = restoreTarget;
1316 var queuedTargets = restoreQueue;
1317 restoreTarget = null;
1318 restoreQueue = null;
1319 restoreStateOfTarget(target);
1320
1321 if (queuedTargets) {
1322 for (var i = 0; i < queuedTargets.length; i++) {
1323 restoreStateOfTarget(queuedTargets[i]);
1324 }
1325 }
1326}
1327
1328var enableUserTimingAPI = true; // Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
1329
1330var debugRenderPhaseSideEffects = false; // In some cases, StrictMode should also double-render lifecycles.
1331// This can be confusing for tests though,
1332// And it can be bad for performance in production.
1333// This feature flag can be used to control the behavior:
1334
1335var debugRenderPhaseSideEffectsForStrictMode = true; // To preserve the "Pause on caught exceptions" behavior of the debugger, we
1336// replay the begin phase of a failed component inside invokeGuardedCallback.
1337
1338var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
1339
1340var warnAboutDeprecatedLifecycles = true; // Gather advanced timing metrics for Profiler subtrees.
1341
1342var enableProfilerTimer = true; // Trace which interactions trigger each commit.
1343
1344var enableSchedulerTracing = true; // Only used in www builds.
1345
1346var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false.
1347
1348var enableSelectiveHydration = false; // Only used in www builds.
1349
1350 // Only used in www builds.
1351
1352 // Disable javascript: URL strings in href for XSS protection.
1353
1354var disableJavaScriptURLs = false; // React Fire: prevent the value and checked attributes from syncing
1355// with their related DOM properties
1356
1357var disableInputAttributeSyncing = false; // These APIs will no longer be "unstable" in the upcoming 16.7 release,
1358// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
1359
1360var enableStableConcurrentModeAPIs = false;
1361var warnAboutShorthandPropertyCollision = false; // See https://github.com/react-native-community/discussions-and-proposals/issues/72 for more information
1362// This is a flag so we can fix warnings in RN core before turning it on
1363
1364 // Experimental React Flare event system and event components support.
1365
1366var enableFlareAPI = false; // Experimental Host Component support.
1367
1368var enableFundamentalAPI = false; // Experimental Scope support.
1369
1370var enableScopeAPI = false; // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
1371
1372 // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
1373// Till then, we warn about the missing mock, but still fallback to a sync mode compatible version
1374
1375var warnAboutUnmockedScheduler = false; // For tests, we flush suspense fallbacks in an act scope;
1376// *except* in some of our own tests, where we test incremental loading states.
1377
1378var flushSuspenseFallbacksInTests = true; // Changes priority of some events like mousemove to user-blocking priority,
1379// but without making them discrete. The flag exists in case it causes
1380// starvation problems.
1381
1382var enableUserBlockingEvents = false; // Add a callback property to suspense to notify which promises are currently
1383// in the update queue. This allows reporting and tracing of what is causing
1384// the user to see a loading state.
1385// Also allows hydration callbacks to fire when a dehydrated boundary gets
1386// hydrated or deleted.
1387
1388var enableSuspenseCallback = false; // Part of the simplification of React.createElement so we can eventually move
1389// from React.createElement to React.jsx
1390// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
1391
1392var warnAboutDefaultPropsOnFunctionComponents = false;
1393var warnAboutStringRefs = false;
1394var disableLegacyContext = false;
1395var disableSchedulerTimeoutBasedOnReactExpirationTime = false;
1396var enableTrustedTypesIntegration = false;
1397
1398// the renderer. Such as when we're dispatching events or if third party
1399// libraries need to call batchedUpdates. Eventually, this API will go away when
1400// everything is batched by default. We'll then have a similar API to opt-out of
1401// scheduled work and instead do synchronous work.
1402// Defaults
1403
1404var batchedUpdatesImpl = function (fn, bookkeeping) {
1405 return fn(bookkeeping);
1406};
1407
1408var discreteUpdatesImpl = function (fn, a, b, c) {
1409 return fn(a, b, c);
1410};
1411
1412var flushDiscreteUpdatesImpl = function () {};
1413
1414var batchedEventUpdatesImpl = batchedUpdatesImpl;
1415var isInsideEventHandler = false;
1416var isBatchingEventUpdates = false;
1417
1418function finishEventHandler() {
1419 // Here we wait until all updates have propagated, which is important
1420 // when using controlled components within layers:
1421 // https://github.com/facebook/react/issues/1698
1422 // Then we restore state of any controlled component.
1423 var controlledComponentsHavePendingUpdates = needsStateRestore();
1424
1425 if (controlledComponentsHavePendingUpdates) {
1426 // If a controlled event was fired, we may need to restore the state of
1427 // the DOM node back to the controlled value. This is necessary when React
1428 // bails out of the update without touching the DOM.
1429 flushDiscreteUpdatesImpl();
1430 restoreStateIfNeeded();
1431 }
1432}
1433
1434function batchedUpdates(fn, bookkeeping) {
1435 if (isInsideEventHandler) {
1436 // If we are currently inside another batch, we need to wait until it
1437 // fully completes before restoring state.
1438 return fn(bookkeeping);
1439 }
1440
1441 isInsideEventHandler = true;
1442
1443 try {
1444 return batchedUpdatesImpl(fn, bookkeeping);
1445 } finally {
1446 isInsideEventHandler = false;
1447 finishEventHandler();
1448 }
1449}
1450function batchedEventUpdates(fn, a, b) {
1451 if (isBatchingEventUpdates) {
1452 // If we are currently inside another batch, we need to wait until it
1453 // fully completes before restoring state.
1454 return fn(a, b);
1455 }
1456
1457 isBatchingEventUpdates = true;
1458
1459 try {
1460 return batchedEventUpdatesImpl(fn, a, b);
1461 } finally {
1462 isBatchingEventUpdates = false;
1463 finishEventHandler();
1464 }
1465} // This is for the React Flare event system
1466
1467function executeUserEventHandler(fn, value) {
1468 var previouslyInEventHandler = isInsideEventHandler;
1469
1470 try {
1471 isInsideEventHandler = true;
1472 var type = typeof value === 'object' && value !== null ? value.type : '';
1473 invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value);
1474 } finally {
1475 isInsideEventHandler = previouslyInEventHandler;
1476 }
1477}
1478function discreteUpdates(fn, a, b, c) {
1479 var prevIsInsideEventHandler = isInsideEventHandler;
1480 isInsideEventHandler = true;
1481
1482 try {
1483 return discreteUpdatesImpl(fn, a, b, c);
1484 } finally {
1485 isInsideEventHandler = prevIsInsideEventHandler;
1486
1487 if (!isInsideEventHandler) {
1488 finishEventHandler();
1489 }
1490 }
1491}
1492var lastFlushedEventTimeStamp = 0;
1493function flushDiscreteUpdatesIfNeeded(timeStamp) {
1494 // event.timeStamp isn't overly reliable due to inconsistencies in
1495 // how different browsers have historically provided the time stamp.
1496 // Some browsers provide high-resolution time stamps for all events,
1497 // some provide low-resolution time stamps for all events. FF < 52
1498 // even mixes both time stamps together. Some browsers even report
1499 // negative time stamps or time stamps that are 0 (iOS9) in some cases.
1500 // Given we are only comparing two time stamps with equality (!==),
1501 // we are safe from the resolution differences. If the time stamp is 0
1502 // we bail-out of preventing the flush, which can affect semantics,
1503 // such as if an earlier flush removes or adds event listeners that
1504 // are fired in the subsequent flush. However, this is the same
1505 // behaviour as we had before this change, so the risks are low.
1506 if (!isInsideEventHandler && (!enableFlareAPI || timeStamp === 0 || lastFlushedEventTimeStamp !== timeStamp)) {
1507 lastFlushedEventTimeStamp = timeStamp;
1508 flushDiscreteUpdatesImpl();
1509 }
1510}
1511function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
1512 batchedUpdatesImpl = _batchedUpdatesImpl;
1513 discreteUpdatesImpl = _discreteUpdatesImpl;
1514 flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
1515 batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
1516}
1517
1518var DiscreteEvent = 0;
1519var UserBlockingEvent = 1;
1520var ContinuousEvent = 2;
1521
1522var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1523var _ReactInternals$Sched = ReactInternals$1.Scheduler;
1524var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
1525var unstable_now = _ReactInternals$Sched.unstable_now;
1526var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
1527var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
1528var unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint;
1529var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
1530var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
1531var unstable_next = _ReactInternals$Sched.unstable_next;
1532var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
1533var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
1534var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
1535var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
1536var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
1537var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
1538var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
1539var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
1540var unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate;
1541var unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
1542
1543// CommonJS interop named imports.
1544
1545var UserBlockingPriority = unstable_UserBlockingPriority;
1546var runWithPriority = unstable_runWithPriority;
1547var listenToResponderEventTypesImpl;
1548function setListenToResponderEventTypes(_listenToResponderEventTypesImpl) {
1549 listenToResponderEventTypesImpl = _listenToResponderEventTypesImpl;
1550}
1551var activeTimeouts = new Map();
1552var rootEventTypesToEventResponderInstances = new Map();
1553var DoNotPropagateToNextResponder = 0;
1554var PropagateToNextResponder = 1;
1555var currentTimeStamp = 0;
1556var currentTimers = new Map();
1557var currentInstance = null;
1558var currentTimerIDCounter = 0;
1559var currentDocument = null;
1560var currentPropagationBehavior = DoNotPropagateToNextResponder;
1561var eventResponderContext = {
1562 dispatchEvent: function (eventValue, eventListener, eventPriority) {
1563 validateResponderContext();
1564 validateEventValue(eventValue);
1565
1566 switch (eventPriority) {
1567 case DiscreteEvent:
1568 {
1569 flushDiscreteUpdatesIfNeeded(currentTimeStamp);
1570 discreteUpdates(function () {
1571 return executeUserEventHandler(eventListener, eventValue);
1572 });
1573 break;
1574 }
1575
1576 case UserBlockingEvent:
1577 {
1578 if (enableUserBlockingEvents) {
1579 runWithPriority(UserBlockingPriority, function () {
1580 return executeUserEventHandler(eventListener, eventValue);
1581 });
1582 } else {
1583 executeUserEventHandler(eventListener, eventValue);
1584 }
1585
1586 break;
1587 }
1588
1589 case ContinuousEvent:
1590 {
1591 executeUserEventHandler(eventListener, eventValue);
1592 break;
1593 }
1594 }
1595 },
1596 isTargetWithinResponder: function (target) {
1597 validateResponderContext();
1598
1599 if (target != null) {
1600 var fiber = getClosestInstanceFromNode(target);
1601 var responderFiber = currentInstance.fiber;
1602
1603 while (fiber !== null) {
1604 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1605 return true;
1606 }
1607
1608 fiber = fiber.return;
1609 }
1610 }
1611
1612 return false;
1613 },
1614 isTargetWithinResponderScope: function (target) {
1615 validateResponderContext();
1616 var componentInstance = currentInstance;
1617 var responder = componentInstance.responder;
1618
1619 if (target != null) {
1620 var fiber = getClosestInstanceFromNode(target);
1621 var responderFiber = currentInstance.fiber;
1622
1623 while (fiber !== null) {
1624 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1625 return true;
1626 }
1627
1628 if (doesFiberHaveResponder(fiber, responder)) {
1629 return false;
1630 }
1631
1632 fiber = fiber.return;
1633 }
1634 }
1635
1636 return false;
1637 },
1638 isTargetWithinNode: function (childTarget, parentTarget) {
1639 validateResponderContext();
1640 var childFiber = getClosestInstanceFromNode(childTarget);
1641 var parentFiber = getClosestInstanceFromNode(parentTarget);
1642
1643 if (childFiber != null && parentFiber != null) {
1644 var parentAlternateFiber = parentFiber.alternate;
1645 var node = childFiber;
1646
1647 while (node !== null) {
1648 if (node === parentFiber || node === parentAlternateFiber) {
1649 return true;
1650 }
1651
1652 node = node.return;
1653 }
1654
1655 return false;
1656 } // Fallback to DOM APIs
1657
1658
1659 return parentTarget.contains(childTarget);
1660 },
1661 addRootEventTypes: function (rootEventTypes) {
1662 validateResponderContext();
1663 listenToResponderEventTypesImpl(rootEventTypes, currentDocument);
1664
1665 for (var i = 0; i < rootEventTypes.length; i++) {
1666 var rootEventType = rootEventTypes[i];
1667 var eventResponderInstance = currentInstance;
1668 registerRootEventType(rootEventType, eventResponderInstance);
1669 }
1670 },
1671 removeRootEventTypes: function (rootEventTypes) {
1672 validateResponderContext();
1673
1674 for (var i = 0; i < rootEventTypes.length; i++) {
1675 var rootEventType = rootEventTypes[i];
1676 var rootEventResponders = rootEventTypesToEventResponderInstances.get(rootEventType);
1677 var rootEventTypesSet = currentInstance.rootEventTypes;
1678
1679 if (rootEventTypesSet !== null) {
1680 rootEventTypesSet.delete(rootEventType);
1681 }
1682
1683 if (rootEventResponders !== undefined) {
1684 rootEventResponders.delete(currentInstance);
1685 }
1686 }
1687 },
1688 setTimeout: function (func, delay) {
1689 validateResponderContext();
1690
1691 if (currentTimers === null) {
1692 currentTimers = new Map();
1693 }
1694
1695 var timeout = currentTimers.get(delay);
1696 var timerId = currentTimerIDCounter++;
1697
1698 if (timeout === undefined) {
1699 var timers = new Map();
1700 var id = setTimeout(function () {
1701 processTimers(timers, delay);
1702 }, delay);
1703 timeout = {
1704 id: id,
1705 timers: timers
1706 };
1707 currentTimers.set(delay, timeout);
1708 }
1709
1710 timeout.timers.set(timerId, {
1711 instance: currentInstance,
1712 func: func,
1713 id: timerId,
1714 timeStamp: currentTimeStamp
1715 });
1716 activeTimeouts.set(timerId, timeout);
1717 return timerId;
1718 },
1719 clearTimeout: function (timerId) {
1720 validateResponderContext();
1721 var timeout = activeTimeouts.get(timerId);
1722
1723 if (timeout !== undefined) {
1724 var timers = timeout.timers;
1725 timers.delete(timerId);
1726
1727 if (timers.size === 0) {
1728 clearTimeout(timeout.id);
1729 }
1730 }
1731 },
1732 getActiveDocument: getActiveDocument,
1733 objectAssign: _assign,
1734 getTimeStamp: function () {
1735 validateResponderContext();
1736 return currentTimeStamp;
1737 },
1738 isTargetWithinHostComponent: function (target, elementType) {
1739 validateResponderContext();
1740 var fiber = getClosestInstanceFromNode(target);
1741
1742 while (fiber !== null) {
1743 if (fiber.tag === HostComponent && fiber.type === elementType) {
1744 return true;
1745 }
1746
1747 fiber = fiber.return;
1748 }
1749
1750 return false;
1751 },
1752 continuePropagation: function () {
1753 currentPropagationBehavior = PropagateToNextResponder;
1754 },
1755 enqueueStateRestore: enqueueStateRestore,
1756 getResponderNode: function () {
1757 validateResponderContext();
1758 var responderFiber = currentInstance.fiber;
1759
1760 if (responderFiber.tag === ScopeComponent) {
1761 return null;
1762 }
1763
1764 return responderFiber.stateNode;
1765 }
1766};
1767
1768function validateEventValue(eventValue) {
1769 if (typeof eventValue === 'object' && eventValue !== null) {
1770 var target = eventValue.target,
1771 type = eventValue.type,
1772 timeStamp = eventValue.timeStamp;
1773
1774 if (target == null || type == null || timeStamp == null) {
1775 throw new Error('context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.');
1776 }
1777
1778 var showWarning = function (name) {
1779 {
1780 warning$1(false, '%s is not available on event objects created from event responder modules (React Flare). ' + 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.%s }`', name, name);
1781 }
1782 };
1783
1784 eventValue.isDefaultPrevented = function () {
1785 {
1786 showWarning('isDefaultPrevented()');
1787 }
1788 };
1789
1790 eventValue.isPropagationStopped = function () {
1791 {
1792 showWarning('isPropagationStopped()');
1793 }
1794 }; // $FlowFixMe: we don't need value, Flow thinks we do
1795
1796
1797 Object.defineProperty(eventValue, 'nativeEvent', {
1798 get: function () {
1799 {
1800 showWarning('nativeEvent');
1801 }
1802 }
1803 });
1804 }
1805}
1806
1807function doesFiberHaveResponder(fiber, responder) {
1808 var tag = fiber.tag;
1809
1810 if (tag === HostComponent || tag === ScopeComponent) {
1811 var dependencies = fiber.dependencies;
1812
1813 if (dependencies !== null) {
1814 var respondersMap = dependencies.responders;
1815
1816 if (respondersMap !== null && respondersMap.has(responder)) {
1817 return true;
1818 }
1819 }
1820 }
1821
1822 return false;
1823}
1824
1825function getActiveDocument() {
1826 return currentDocument;
1827}
1828
1829function processTimers(timers, delay) {
1830 var timersArr = Array.from(timers.values());
1831 var previousInstance = currentInstance;
1832 var previousTimers = currentTimers;
1833
1834 try {
1835 batchedEventUpdates(function () {
1836 for (var i = 0; i < timersArr.length; i++) {
1837 var _timersArr$i = timersArr[i],
1838 instance = _timersArr$i.instance,
1839 func = _timersArr$i.func,
1840 id = _timersArr$i.id,
1841 timeStamp = _timersArr$i.timeStamp;
1842 currentInstance = instance;
1843 currentTimeStamp = timeStamp + delay;
1844
1845 try {
1846 func();
1847 } finally {
1848 activeTimeouts.delete(id);
1849 }
1850 }
1851 });
1852 } finally {
1853 currentTimers = previousTimers;
1854 currentInstance = previousInstance;
1855 currentTimeStamp = 0;
1856 }
1857}
1858
1859function createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, passive, passiveSupported) {
1860 var _ref = nativeEvent,
1861 buttons = _ref.buttons,
1862 pointerType = _ref.pointerType;
1863 var eventPointerType = '';
1864
1865 if (pointerType !== undefined) {
1866 eventPointerType = pointerType;
1867 } else if (nativeEvent.key !== undefined) {
1868 eventPointerType = 'keyboard';
1869 } else if (buttons !== undefined) {
1870 eventPointerType = 'mouse';
1871 } else if (nativeEvent.changedTouches !== undefined) {
1872 eventPointerType = 'touch';
1873 }
1874
1875 return {
1876 nativeEvent: nativeEvent,
1877 passive: passive,
1878 passiveSupported: passiveSupported,
1879 pointerType: eventPointerType,
1880 target: nativeEventTarget,
1881 type: topLevelType
1882 };
1883}
1884
1885function responderEventTypesContainType(eventTypes, type) {
1886 for (var i = 0, len = eventTypes.length; i < len; i++) {
1887 if (eventTypes[i] === type) {
1888 return true;
1889 }
1890 }
1891
1892 return false;
1893}
1894
1895function validateResponderTargetEventTypes(eventType, responder) {
1896 var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder
1897
1898 if (targetEventTypes !== null) {
1899 return responderEventTypesContainType(targetEventTypes, eventType);
1900 }
1901
1902 return false;
1903}
1904
1905function traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1906 var isPassiveEvent = (eventSystemFlags & IS_PASSIVE) !== 0;
1907 var isPassiveSupported = (eventSystemFlags & PASSIVE_NOT_SUPPORTED) === 0;
1908 var isPassive = isPassiveEvent || !isPassiveSupported;
1909 var eventType = isPassive ? topLevelType : topLevelType + '_active'; // Trigger event responders in this order:
1910 // - Bubble target responder phase
1911 // - Root responder phase
1912
1913 var visitedResponders = new Set();
1914 var responderEvent = createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, isPassiveEvent, isPassiveSupported);
1915 var node = targetFiber;
1916 var insidePortal = false;
1917
1918 while (node !== null) {
1919 var _node = node,
1920 dependencies = _node.dependencies,
1921 tag = _node.tag;
1922
1923 if (tag === HostPortal) {
1924 insidePortal = true;
1925 } else if ((tag === HostComponent || tag === ScopeComponent) && dependencies !== null) {
1926 var respondersMap = dependencies.responders;
1927
1928 if (respondersMap !== null) {
1929 var responderInstances = Array.from(respondersMap.values());
1930
1931 for (var i = 0, length = responderInstances.length; i < length; i++) {
1932 var responderInstance = responderInstances[i];
1933 var props = responderInstance.props,
1934 responder = responderInstance.responder,
1935 state = responderInstance.state;
1936
1937 if (!visitedResponders.has(responder) && validateResponderTargetEventTypes(eventType, responder) && (!insidePortal || responder.targetPortalPropagation)) {
1938 visitedResponders.add(responder);
1939 var onEvent = responder.onEvent;
1940
1941 if (onEvent !== null) {
1942 currentInstance = responderInstance;
1943 onEvent(responderEvent, eventResponderContext, props, state);
1944
1945 if (currentPropagationBehavior === PropagateToNextResponder) {
1946 visitedResponders.delete(responder);
1947 currentPropagationBehavior = DoNotPropagateToNextResponder;
1948 }
1949 }
1950 }
1951 }
1952 }
1953 }
1954
1955 node = node.return;
1956 } // Root phase
1957
1958
1959 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(eventType);
1960
1961 if (rootEventResponderInstances !== undefined) {
1962 var _responderInstances = Array.from(rootEventResponderInstances);
1963
1964 for (var _i = 0; _i < _responderInstances.length; _i++) {
1965 var _responderInstance = _responderInstances[_i];
1966 var props = _responderInstance.props,
1967 responder = _responderInstance.responder,
1968 state = _responderInstance.state;
1969 var onRootEvent = responder.onRootEvent;
1970
1971 if (onRootEvent !== null) {
1972 currentInstance = _responderInstance;
1973 onRootEvent(responderEvent, eventResponderContext, props, state);
1974 }
1975 }
1976 }
1977}
1978
1979function mountEventResponder(responder, responderInstance, props, state) {
1980 var onMount = responder.onMount;
1981
1982 if (onMount !== null) {
1983 var previousInstance = currentInstance;
1984 var previousTimers = currentTimers;
1985 currentInstance = responderInstance;
1986
1987 try {
1988 batchedEventUpdates(function () {
1989 onMount(eventResponderContext, props, state);
1990 });
1991 } finally {
1992 currentInstance = previousInstance;
1993 currentTimers = previousTimers;
1994 }
1995 }
1996}
1997function unmountEventResponder(responderInstance) {
1998 var responder = responderInstance.responder;
1999 var onUnmount = responder.onUnmount;
2000
2001 if (onUnmount !== null) {
2002 var props = responderInstance.props,
2003 state = responderInstance.state;
2004 var previousInstance = currentInstance;
2005 var previousTimers = currentTimers;
2006 currentInstance = responderInstance;
2007
2008 try {
2009 batchedEventUpdates(function () {
2010 onUnmount(eventResponderContext, props, state);
2011 });
2012 } finally {
2013 currentInstance = previousInstance;
2014 currentTimers = previousTimers;
2015 }
2016 }
2017
2018 var rootEventTypesSet = responderInstance.rootEventTypes;
2019
2020 if (rootEventTypesSet !== null) {
2021 var rootEventTypes = Array.from(rootEventTypesSet);
2022
2023 for (var i = 0; i < rootEventTypes.length; i++) {
2024 var topLevelEventType = rootEventTypes[i];
2025 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(topLevelEventType);
2026
2027 if (rootEventResponderInstances !== undefined) {
2028 rootEventResponderInstances.delete(responderInstance);
2029 }
2030 }
2031 }
2032}
2033
2034function validateResponderContext() {
2035 (function () {
2036 if (!(currentInstance !== null)) {
2037 {
2038 throw ReactError(Error("An event responder context was used outside of an event cycle. Use context.setTimeout() to use asynchronous responder context outside of event cycle ."));
2039 }
2040 }
2041 })();
2042}
2043
2044function dispatchEventForResponderEventSystem(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
2045 if (enableFlareAPI) {
2046 var previousInstance = currentInstance;
2047 var previousTimers = currentTimers;
2048 var previousTimeStamp = currentTimeStamp;
2049 var previousDocument = currentDocument;
2050 var previousPropagationBehavior = currentPropagationBehavior;
2051 currentPropagationBehavior = DoNotPropagateToNextResponder;
2052 currentTimers = null; // nodeType 9 is DOCUMENT_NODE
2053
2054 currentDocument = nativeEventTarget.nodeType === 9 ? nativeEventTarget : nativeEventTarget.ownerDocument; // We might want to control timeStamp another way here
2055
2056 currentTimeStamp = nativeEvent.timeStamp;
2057
2058 try {
2059 batchedEventUpdates(function () {
2060 traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags);
2061 });
2062 } finally {
2063 currentTimers = previousTimers;
2064 currentInstance = previousInstance;
2065 currentTimeStamp = previousTimeStamp;
2066 currentDocument = previousDocument;
2067 currentPropagationBehavior = previousPropagationBehavior;
2068 }
2069 }
2070}
2071function addRootEventTypesForResponderInstance(responderInstance, rootEventTypes) {
2072 for (var i = 0; i < rootEventTypes.length; i++) {
2073 var rootEventType = rootEventTypes[i];
2074 registerRootEventType(rootEventType, responderInstance);
2075 }
2076}
2077
2078function registerRootEventType(rootEventType, eventResponderInstance) {
2079 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(rootEventType);
2080
2081 if (rootEventResponderInstances === undefined) {
2082 rootEventResponderInstances = new Set();
2083 rootEventTypesToEventResponderInstances.set(rootEventType, rootEventResponderInstances);
2084 }
2085
2086 var rootEventTypesSet = eventResponderInstance.rootEventTypes;
2087
2088 if (rootEventTypesSet === null) {
2089 rootEventTypesSet = eventResponderInstance.rootEventTypes = new Set();
2090 }
2091
2092 (function () {
2093 if (!!rootEventTypesSet.has(rootEventType)) {
2094 {
2095 throw ReactError(Error("addRootEventTypes() found a duplicate root event type of \"" + rootEventType + "\". This might be because the event type exists in the event responder \"rootEventTypes\" array or because of a previous addRootEventTypes() using this root event type."));
2096 }
2097 }
2098 })();
2099
2100 rootEventTypesSet.add(rootEventType);
2101 rootEventResponderInstances.add(eventResponderInstance);
2102}
2103
2104// A reserved attribute.
2105// It is handled by React separately and shouldn't be written to the DOM.
2106var RESERVED = 0; // A simple string attribute.
2107// Attributes that aren't in the whitelist are presumed to have this type.
2108
2109var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
2110// "enumerated" attributes with "true" and "false" as possible values.
2111// When true, it should be set to a "true" string.
2112// When false, it should be set to a "false" string.
2113
2114var BOOLEANISH_STRING = 2; // A real boolean attribute.
2115// When true, it should be present (set either to an empty string or its name).
2116// When false, it should be omitted.
2117
2118var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
2119// When true, it should be present (set either to an empty string or its name).
2120// When false, it should be omitted.
2121// For any other value, should be present with that value.
2122
2123var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
2124// When falsy, it should be removed.
2125
2126var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
2127// When falsy, it should be removed.
2128
2129var POSITIVE_NUMERIC = 6;
2130
2131/* eslint-disable max-len */
2132var 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";
2133/* eslint-enable max-len */
2134
2135var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
2136
2137var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2138var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2139var hasOwnProperty = Object.prototype.hasOwnProperty;
2140var illegalAttributeNameCache = {};
2141var validatedAttributeNameCache = {};
2142function isAttributeNameSafe(attributeName) {
2143 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2144 return true;
2145 }
2146
2147 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2148 return false;
2149 }
2150
2151 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2152 validatedAttributeNameCache[attributeName] = true;
2153 return true;
2154 }
2155
2156 illegalAttributeNameCache[attributeName] = true;
2157
2158 {
2159 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2160 }
2161
2162 return false;
2163}
2164function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2165 if (propertyInfo !== null) {
2166 return propertyInfo.type === RESERVED;
2167 }
2168
2169 if (isCustomComponentTag) {
2170 return false;
2171 }
2172
2173 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2174 return true;
2175 }
2176
2177 return false;
2178}
2179function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2180 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2181 return false;
2182 }
2183
2184 switch (typeof value) {
2185 case 'function': // $FlowIssue symbol is perfectly valid here
2186
2187 case 'symbol':
2188 // eslint-disable-line
2189 return true;
2190
2191 case 'boolean':
2192 {
2193 if (isCustomComponentTag) {
2194 return false;
2195 }
2196
2197 if (propertyInfo !== null) {
2198 return !propertyInfo.acceptsBooleans;
2199 } else {
2200 var prefix = name.toLowerCase().slice(0, 5);
2201 return prefix !== 'data-' && prefix !== 'aria-';
2202 }
2203 }
2204
2205 default:
2206 return false;
2207 }
2208}
2209function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2210 if (value === null || typeof value === 'undefined') {
2211 return true;
2212 }
2213
2214 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2215 return true;
2216 }
2217
2218 if (isCustomComponentTag) {
2219 return false;
2220 }
2221
2222 if (propertyInfo !== null) {
2223 switch (propertyInfo.type) {
2224 case BOOLEAN:
2225 return !value;
2226
2227 case OVERLOADED_BOOLEAN:
2228 return value === false;
2229
2230 case NUMERIC:
2231 return isNaN(value);
2232
2233 case POSITIVE_NUMERIC:
2234 return isNaN(value) || value < 1;
2235 }
2236 }
2237
2238 return false;
2239}
2240function getPropertyInfo(name) {
2241 return properties.hasOwnProperty(name) ? properties[name] : null;
2242}
2243
2244function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
2245 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2246 this.attributeName = attributeName;
2247 this.attributeNamespace = attributeNamespace;
2248 this.mustUseProperty = mustUseProperty;
2249 this.propertyName = name;
2250 this.type = type;
2251 this.sanitizeURL = sanitizeURL;
2252} // When adding attributes to this list, be sure to also add them to
2253// the `possibleStandardNames` module to ensure casing and incorrect
2254// name warnings.
2255
2256
2257var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
2258
2259['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
2260// elements (not just inputs). Now that ReactDOMInput assigns to the
2261// defaultValue property -- do we need this?
2262'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2263 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2264 name, // attributeName
2265 null, // attributeNamespace
2266 false);
2267}); // A few React string attributes have a different name.
2268// This is a mapping from React prop names to the attribute names.
2269
2270[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2271 var name = _ref[0],
2272 attributeName = _ref[1];
2273 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2274 attributeName, // attributeName
2275 null, // attributeNamespace
2276 false);
2277}); // These are "enumerated" HTML attributes that accept "true" and "false".
2278// In React, we let users pass `true` and `false` even though technically
2279// these aren't boolean attributes (they are coerced to strings).
2280
2281['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2282 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2283 name.toLowerCase(), // attributeName
2284 null, // attributeNamespace
2285 false);
2286}); // These are "enumerated" SVG attributes that accept "true" and "false".
2287// In React, we let users pass `true` and `false` even though technically
2288// these aren't boolean attributes (they are coerced to strings).
2289// Since these are SVG attributes, their attribute names are case-sensitive.
2290
2291['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2292 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2293 name, // attributeName
2294 null, // attributeNamespace
2295 false);
2296}); // These are HTML boolean attributes.
2297
2298['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
2299// on the client side because the browsers are inconsistent. Instead we call focus().
2300'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
2301'itemScope'].forEach(function (name) {
2302 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2303 name.toLowerCase(), // attributeName
2304 null, // attributeNamespace
2305 false);
2306}); // These are the few React props that we set as DOM properties
2307// rather than attributes. These are all booleans.
2308
2309['checked', // Note: `option.selected` is not updated if `select.multiple` is
2310// disabled with `removeAttribute`. We have special logic for handling this.
2311'multiple', 'muted', 'selected'].forEach(function (name) {
2312 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2313 name, // attributeName
2314 null, // attributeNamespace
2315 false);
2316}); // These are HTML attributes that are "overloaded booleans": they behave like
2317// booleans, but can also accept a string value.
2318
2319['capture', 'download'].forEach(function (name) {
2320 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2321 name, // attributeName
2322 null, // attributeNamespace
2323 false);
2324}); // These are HTML attributes that must be positive numbers.
2325
2326['cols', 'rows', 'size', 'span'].forEach(function (name) {
2327 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2328 name, // attributeName
2329 null, // attributeNamespace
2330 false);
2331}); // These are HTML attributes that must be numbers.
2332
2333['rowSpan', 'start'].forEach(function (name) {
2334 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2335 name.toLowerCase(), // attributeName
2336 null, // attributeNamespace
2337 false);
2338});
2339var CAMELIZE = /[\-\:]([a-z])/g;
2340
2341var capitalize = function (token) {
2342 return token[1].toUpperCase();
2343}; // This is a list of all SVG attributes that need special casing, namespacing,
2344// or boolean value assignment. Regular attributes that just accept strings
2345// and have the same names are omitted, just like in the HTML whitelist.
2346// Some of these attributes can be hard to find. This list was created by
2347// scrapping the MDN documentation.
2348
2349
2350['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) {
2351 var name = attributeName.replace(CAMELIZE, capitalize);
2352 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2353 attributeName, null, // attributeNamespace
2354 false);
2355}); // String SVG attributes with the xlink namespace.
2356
2357['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2358 var name = attributeName.replace(CAMELIZE, capitalize);
2359 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2360 attributeName, 'http://www.w3.org/1999/xlink', false);
2361}); // String SVG attributes with the xml namespace.
2362
2363['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2364 var name = attributeName.replace(CAMELIZE, capitalize);
2365 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2366 attributeName, 'http://www.w3.org/XML/1998/namespace', false);
2367}); // These attribute exists both in HTML and SVG.
2368// The attribute name is case-sensitive in SVG so we can't just use
2369// the React name like we do for attributes that exist only in HTML.
2370
2371['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
2372 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2373 attributeName.toLowerCase(), // attributeName
2374 null, // attributeNamespace
2375 false);
2376}); // These attributes accept URLs. These must not allow javascript: URLS.
2377// These will also need to accept Trusted Types object in the future.
2378
2379var xlinkHref = 'xlinkHref';
2380properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
2381'xlink:href', 'http://www.w3.org/1999/xlink', true);
2382['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
2383 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2384 attributeName.toLowerCase(), // attributeName
2385 null, // attributeNamespace
2386 true);
2387});
2388
2389var ReactDebugCurrentFrame$1 = null;
2390
2391{
2392 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2393} // A javascript: URL can contain leading C0 control or \u0020 SPACE,
2394// and any newline or tab are filtered out as if they're not part of the URL.
2395// https://url.spec.whatwg.org/#url-parsing
2396// Tab or newline are defined as \r\n\t:
2397// https://infra.spec.whatwg.org/#ascii-tab-or-newline
2398// A C0 control is a code point in the range \u0000 NULL to \u001F
2399// INFORMATION SEPARATOR ONE, inclusive:
2400// https://infra.spec.whatwg.org/#c0-control-or-space
2401
2402/* eslint-disable max-len */
2403
2404
2405var 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;
2406var didWarn = false;
2407
2408function sanitizeURL(url) {
2409 if (disableJavaScriptURLs) {
2410 (function () {
2411 if (!!isJavaScriptProtocol.test(url)) {
2412 {
2413 throw ReactError(Error("React has blocked a javascript: URL as a security precaution." + (ReactDebugCurrentFrame$1.getStackAddendum())));
2414 }
2415 }
2416 })();
2417 } else if (true && !didWarn && isJavaScriptProtocol.test(url)) {
2418 didWarn = true;
2419 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));
2420 }
2421}
2422
2423// Flow does not allow string concatenation of most non-string types. To work
2424// around this limitation, we use an opaque type that can only be obtained by
2425// passing the value through getToStringValue first.
2426function toString(value) {
2427 return '' + value;
2428}
2429function getToStringValue(value) {
2430 switch (typeof value) {
2431 case 'boolean':
2432 case 'number':
2433 case 'object':
2434 case 'string':
2435 case 'undefined':
2436 return value;
2437
2438 default:
2439 // function, symbol are assigned as empty strings
2440 return '';
2441 }
2442}
2443/** Trusted value is a wrapper for "safe" values which can be assigned to DOM execution sinks. */
2444
2445/**
2446 * We allow passing objects with toString method as element attributes or in dangerouslySetInnerHTML
2447 * and we do validations that the value is safe. Once we do validation we want to use the validated
2448 * value instead of the object (because object.toString may return something else on next call).
2449 *
2450 * If application uses Trusted Types we don't stringify trusted values, but preserve them as objects.
2451 */
2452var toStringOrTrustedType = toString;
2453
2454if (enableTrustedTypesIntegration && typeof trustedTypes !== 'undefined') {
2455 var isHTML = trustedTypes.isHTML;
2456 var isScript = trustedTypes.isScript;
2457 var isScriptURL = trustedTypes.isScriptURL; // TrustedURLs are deprecated and will be removed soon: https://github.com/WICG/trusted-types/pull/204
2458
2459 var isURL = trustedTypes.isURL ? trustedTypes.isURL : function (value) {
2460 return false;
2461 };
2462
2463 toStringOrTrustedType = function (value) {
2464 if (typeof value === 'object' && (isHTML(value) || isScript(value) || isScriptURL(value) || isURL(value))) {
2465 // Pass Trusted Types through.
2466 return value;
2467 }
2468
2469 return toString(value);
2470 };
2471}
2472
2473/**
2474 * Set attribute for a node. The attribute value can be either string or
2475 * Trusted value (if application uses Trusted Types).
2476 */
2477function setAttribute(node, attributeName, attributeValue) {
2478 node.setAttribute(attributeName, attributeValue);
2479}
2480/**
2481 * Set attribute with namespace for a node. The attribute value can be either string or
2482 * Trusted value (if application uses Trusted Types).
2483 */
2484
2485function setAttributeNS(node, attributeNamespace, attributeName, attributeValue) {
2486 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
2487}
2488
2489/**
2490 * Get the value for a property on a node. Only used in DEV for SSR validation.
2491 * The "expected" argument is used as a hint of what the expected value is.
2492 * Some properties have multiple equivalent values.
2493 */
2494function getValueForProperty(node, name, expected, propertyInfo) {
2495 {
2496 if (propertyInfo.mustUseProperty) {
2497 var propertyName = propertyInfo.propertyName;
2498 return node[propertyName];
2499 } else {
2500 if (!disableJavaScriptURLs && propertyInfo.sanitizeURL) {
2501 // If we haven't fully disabled javascript: URLs, and if
2502 // the hydration is successful of a javascript: URL, we
2503 // still want to warn on the client.
2504 sanitizeURL('' + expected);
2505 }
2506
2507 var attributeName = propertyInfo.attributeName;
2508 var stringValue = null;
2509
2510 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2511 if (node.hasAttribute(attributeName)) {
2512 var value = node.getAttribute(attributeName);
2513
2514 if (value === '') {
2515 return true;
2516 }
2517
2518 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2519 return value;
2520 }
2521
2522 if (value === '' + expected) {
2523 return expected;
2524 }
2525
2526 return value;
2527 }
2528 } else if (node.hasAttribute(attributeName)) {
2529 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2530 // We had an attribute but shouldn't have had one, so read it
2531 // for the error message.
2532 return node.getAttribute(attributeName);
2533 }
2534
2535 if (propertyInfo.type === BOOLEAN) {
2536 // If this was a boolean, it doesn't matter what the value is
2537 // the fact that we have it is the same as the expected.
2538 return expected;
2539 } // Even if this property uses a namespace we use getAttribute
2540 // because we assume its namespaced name is the same as our config.
2541 // To use getAttributeNS we need the local name which we don't have
2542 // in our config atm.
2543
2544
2545 stringValue = node.getAttribute(attributeName);
2546 }
2547
2548 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2549 return stringValue === null ? expected : stringValue;
2550 } else if (stringValue === '' + expected) {
2551 return expected;
2552 } else {
2553 return stringValue;
2554 }
2555 }
2556 }
2557}
2558/**
2559 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2560 * The third argument is used as a hint of what the expected value is. Some
2561 * attributes have multiple equivalent values.
2562 */
2563
2564function getValueForAttribute(node, name, expected) {
2565 {
2566 if (!isAttributeNameSafe(name)) {
2567 return;
2568 }
2569
2570 if (!node.hasAttribute(name)) {
2571 return expected === undefined ? undefined : null;
2572 }
2573
2574 var value = node.getAttribute(name);
2575
2576 if (value === '' + expected) {
2577 return expected;
2578 }
2579
2580 return value;
2581 }
2582}
2583/**
2584 * Sets the value for a property on a node.
2585 *
2586 * @param {DOMElement} node
2587 * @param {string} name
2588 * @param {*} value
2589 */
2590
2591function setValueForProperty(node, name, value, isCustomComponentTag) {
2592 var propertyInfo = getPropertyInfo(name);
2593
2594 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
2595 return;
2596 }
2597
2598 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
2599 value = null;
2600 } // If the prop isn't in the special list, treat it as a simple attribute.
2601
2602
2603 if (isCustomComponentTag || propertyInfo === null) {
2604 if (isAttributeNameSafe(name)) {
2605 var _attributeName = name;
2606
2607 if (value === null) {
2608 node.removeAttribute(_attributeName);
2609 } else {
2610 setAttribute(node, _attributeName, toStringOrTrustedType(value));
2611 }
2612 }
2613
2614 return;
2615 }
2616
2617 var mustUseProperty = propertyInfo.mustUseProperty;
2618
2619 if (mustUseProperty) {
2620 var propertyName = propertyInfo.propertyName;
2621
2622 if (value === null) {
2623 var type = propertyInfo.type;
2624 node[propertyName] = type === BOOLEAN ? false : '';
2625 } else {
2626 // Contrary to `setAttribute`, object properties are properly
2627 // `toString`ed by IE8/9.
2628 node[propertyName] = value;
2629 }
2630
2631 return;
2632 } // The rest are treated as attributes with special cases.
2633
2634
2635 var attributeName = propertyInfo.attributeName,
2636 attributeNamespace = propertyInfo.attributeNamespace;
2637
2638 if (value === null) {
2639 node.removeAttribute(attributeName);
2640 } else {
2641 var _type = propertyInfo.type;
2642 var attributeValue;
2643
2644 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
2645 // If attribute type is boolean, we know for sure it won't be an execution sink
2646 // and we won't require Trusted Type here.
2647 attributeValue = '';
2648 } else {
2649 // `setAttribute` with objects becomes only `[object]` in IE8/9,
2650 // ('' + value) makes it output the correct toString()-value.
2651 attributeValue = toStringOrTrustedType(value);
2652
2653 if (propertyInfo.sanitizeURL) {
2654 sanitizeURL(attributeValue.toString());
2655 }
2656 }
2657
2658 if (attributeNamespace) {
2659 setAttributeNS(node, attributeNamespace, attributeName, attributeValue);
2660 } else {
2661 setAttribute(node, attributeName, attributeValue);
2662 }
2663 }
2664}
2665
2666/**
2667 * Copyright (c) 2013-present, Facebook, Inc.
2668 *
2669 * This source code is licensed under the MIT license found in the
2670 * LICENSE file in the root directory of this source tree.
2671 */
2672
2673
2674
2675var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
2676
2677var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
2678
2679/**
2680 * Copyright (c) 2013-present, Facebook, Inc.
2681 *
2682 * This source code is licensed under the MIT license found in the
2683 * LICENSE file in the root directory of this source tree.
2684 */
2685
2686
2687
2688var printWarning = function() {};
2689
2690{
2691 var ReactPropTypesSecret = ReactPropTypesSecret_1;
2692 var loggedTypeFailures = {};
2693 var has = Function.call.bind(Object.prototype.hasOwnProperty);
2694
2695 printWarning = function(text) {
2696 var message = 'Warning: ' + text;
2697 if (typeof console !== 'undefined') {
2698 console.error(message);
2699 }
2700 try {
2701 // --- Welcome to debugging React ---
2702 // This error was thrown as a convenience so that you can use this stack
2703 // to find the callsite that caused this warning to fire.
2704 throw new Error(message);
2705 } catch (x) {}
2706 };
2707}
2708
2709/**
2710 * Assert that the values match with the type specs.
2711 * Error messages are memorized and will only be shown once.
2712 *
2713 * @param {object} typeSpecs Map of name to a ReactPropType
2714 * @param {object} values Runtime values that need to be type-checked
2715 * @param {string} location e.g. "prop", "context", "child context"
2716 * @param {string} componentName Name of the component for error messages.
2717 * @param {?Function} getStack Returns the component stack.
2718 * @private
2719 */
2720function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
2721 {
2722 for (var typeSpecName in typeSpecs) {
2723 if (has(typeSpecs, typeSpecName)) {
2724 var error;
2725 // Prop type validation may throw. In case they do, we don't want to
2726 // fail the render phase where it didn't fail before. So we log it.
2727 // After these have been cleaned up, we'll let them throw.
2728 try {
2729 // This is intentionally an invariant that gets caught. It's the same
2730 // behavior as without this statement except with a better message.
2731 if (typeof typeSpecs[typeSpecName] !== 'function') {
2732 var err = Error(
2733 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
2734 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
2735 );
2736 err.name = 'Invariant Violation';
2737 throw err;
2738 }
2739 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
2740 } catch (ex) {
2741 error = ex;
2742 }
2743 if (error && !(error instanceof Error)) {
2744 printWarning(
2745 (componentName || 'React class') + ': type specification of ' +
2746 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
2747 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
2748 'You may have forgotten to pass an argument to the type checker ' +
2749 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
2750 'shape all require an argument).'
2751 );
2752 }
2753 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
2754 // Only monitor this failure once because there tends to be a lot of the
2755 // same error.
2756 loggedTypeFailures[error.message] = true;
2757
2758 var stack = getStack ? getStack() : '';
2759
2760 printWarning(
2761 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
2762 );
2763 }
2764 }
2765 }
2766 }
2767}
2768
2769/**
2770 * Resets warning cache when testing.
2771 *
2772 * @private
2773 */
2774checkPropTypes.resetWarningCache = function() {
2775 {
2776 loggedTypeFailures = {};
2777 }
2778};
2779
2780var checkPropTypes_1 = checkPropTypes;
2781
2782var ReactDebugCurrentFrame$2 = null;
2783var ReactControlledValuePropTypes = {
2784 checkPropTypes: null
2785};
2786
2787{
2788 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
2789 var hasReadOnlyValue = {
2790 button: true,
2791 checkbox: true,
2792 image: true,
2793 hidden: true,
2794 radio: true,
2795 reset: true,
2796 submit: true
2797 };
2798 var propTypes = {
2799 value: function (props, propName, componentName) {
2800 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2801 return null;
2802 }
2803
2804 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`.');
2805 },
2806 checked: function (props, propName, componentName) {
2807 if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2808 return null;
2809 }
2810
2811 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`.');
2812 }
2813 };
2814 /**
2815 * Provide a linked `value` attribute for controlled forms. You should not use
2816 * this outside of the ReactDOM controlled form components.
2817 */
2818
2819 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
2820 checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
2821 };
2822}
2823
2824function isCheckable(elem) {
2825 var type = elem.type;
2826 var nodeName = elem.nodeName;
2827 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2828}
2829
2830function getTracker(node) {
2831 return node._valueTracker;
2832}
2833
2834function detachTracker(node) {
2835 node._valueTracker = null;
2836}
2837
2838function getValueFromNode(node) {
2839 var value = '';
2840
2841 if (!node) {
2842 return value;
2843 }
2844
2845 if (isCheckable(node)) {
2846 value = node.checked ? 'true' : 'false';
2847 } else {
2848 value = node.value;
2849 }
2850
2851 return value;
2852}
2853
2854function trackValueOnNode(node) {
2855 var valueField = isCheckable(node) ? 'checked' : 'value';
2856 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2857 var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
2858 // and don't track value will cause over reporting of changes,
2859 // but it's better then a hard failure
2860 // (needed for certain tests that spyOn input values and Safari)
2861
2862 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2863 return;
2864 }
2865
2866 var get = descriptor.get,
2867 set = descriptor.set;
2868 Object.defineProperty(node, valueField, {
2869 configurable: true,
2870 get: function () {
2871 return get.call(this);
2872 },
2873 set: function (value) {
2874 currentValue = '' + value;
2875 set.call(this, value);
2876 }
2877 }); // We could've passed this the first time
2878 // but it triggers a bug in IE11 and Edge 14/15.
2879 // Calling defineProperty() again should be equivalent.
2880 // https://github.com/facebook/react/issues/11768
2881
2882 Object.defineProperty(node, valueField, {
2883 enumerable: descriptor.enumerable
2884 });
2885 var tracker = {
2886 getValue: function () {
2887 return currentValue;
2888 },
2889 setValue: function (value) {
2890 currentValue = '' + value;
2891 },
2892 stopTracking: function () {
2893 detachTracker(node);
2894 delete node[valueField];
2895 }
2896 };
2897 return tracker;
2898}
2899
2900function track(node) {
2901 if (getTracker(node)) {
2902 return;
2903 } // TODO: Once it's just Fiber we can move this to node._wrapperState
2904
2905
2906 node._valueTracker = trackValueOnNode(node);
2907}
2908function updateValueIfChanged(node) {
2909 if (!node) {
2910 return false;
2911 }
2912
2913 var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
2914 // that trying again will succeed
2915
2916 if (!tracker) {
2917 return true;
2918 }
2919
2920 var lastValue = tracker.getValue();
2921 var nextValue = getValueFromNode(node);
2922
2923 if (nextValue !== lastValue) {
2924 tracker.setValue(nextValue);
2925 return true;
2926 }
2927
2928 return false;
2929}
2930
2931// TODO: direct imports like some-package/src/* are bad. Fix me.
2932var didWarnValueDefaultValue = false;
2933var didWarnCheckedDefaultChecked = false;
2934var didWarnControlledToUncontrolled = false;
2935var didWarnUncontrolledToControlled = false;
2936
2937function isControlled(props) {
2938 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
2939 return usesChecked ? props.checked != null : props.value != null;
2940}
2941/**
2942 * Implements an <input> host component that allows setting these optional
2943 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
2944 *
2945 * If `checked` or `value` are not supplied (or null/undefined), user actions
2946 * that affect the checked state or value will trigger updates to the element.
2947 *
2948 * If they are supplied (and not null/undefined), the rendered element will not
2949 * trigger updates to the element. Instead, the props must change in order for
2950 * the rendered element to be updated.
2951 *
2952 * The rendered element will be initialized as unchecked (or `defaultChecked`)
2953 * with an empty value (or `defaultValue`).
2954 *
2955 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
2956 */
2957
2958
2959function getHostProps(element, props) {
2960 var node = element;
2961 var checked = props.checked;
2962
2963 var hostProps = _assign({}, props, {
2964 defaultChecked: undefined,
2965 defaultValue: undefined,
2966 value: undefined,
2967 checked: checked != null ? checked : node._wrapperState.initialChecked
2968 });
2969
2970 return hostProps;
2971}
2972function initWrapperState(element, props) {
2973 {
2974 ReactControlledValuePropTypes.checkPropTypes('input', props);
2975
2976 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
2977 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);
2978 didWarnCheckedDefaultChecked = true;
2979 }
2980
2981 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
2982 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);
2983 didWarnValueDefaultValue = true;
2984 }
2985 }
2986
2987 var node = element;
2988 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
2989 node._wrapperState = {
2990 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
2991 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
2992 controlled: isControlled(props)
2993 };
2994}
2995function updateChecked(element, props) {
2996 var node = element;
2997 var checked = props.checked;
2998
2999 if (checked != null) {
3000 setValueForProperty(node, 'checked', checked, false);
3001 }
3002}
3003function updateWrapper(element, props) {
3004 var node = element;
3005
3006 {
3007 var controlled = isControlled(props);
3008
3009 if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
3010 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);
3011 didWarnUncontrolledToControlled = true;
3012 }
3013
3014 if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
3015 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);
3016 didWarnControlledToUncontrolled = true;
3017 }
3018 }
3019
3020 updateChecked(element, props);
3021 var value = getToStringValue(props.value);
3022 var type = props.type;
3023
3024 if (value != null) {
3025 if (type === 'number') {
3026 if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
3027 // eslint-disable-next-line
3028 node.value != value) {
3029 node.value = toString(value);
3030 }
3031 } else if (node.value !== toString(value)) {
3032 node.value = toString(value);
3033 }
3034 } else if (type === 'submit' || type === 'reset') {
3035 // Submit/reset inputs need the attribute removed completely to avoid
3036 // blank-text buttons.
3037 node.removeAttribute('value');
3038 return;
3039 }
3040
3041 if (disableInputAttributeSyncing) {
3042 // When not syncing the value attribute, React only assigns a new value
3043 // whenever the defaultValue React prop has changed. When not present,
3044 // React does nothing
3045 if (props.hasOwnProperty('defaultValue')) {
3046 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3047 }
3048 } else {
3049 // When syncing the value attribute, the value comes from a cascade of
3050 // properties:
3051 // 1. The value React property
3052 // 2. The defaultValue React property
3053 // 3. Otherwise there should be no change
3054 if (props.hasOwnProperty('value')) {
3055 setDefaultValue(node, props.type, value);
3056 } else if (props.hasOwnProperty('defaultValue')) {
3057 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
3058 }
3059 }
3060
3061 if (disableInputAttributeSyncing) {
3062 // When not syncing the checked attribute, the attribute is directly
3063 // controllable from the defaultValue React property. It needs to be
3064 // updated as new props come in.
3065 if (props.defaultChecked == null) {
3066 node.removeAttribute('checked');
3067 } else {
3068 node.defaultChecked = !!props.defaultChecked;
3069 }
3070 } else {
3071 // When syncing the checked attribute, it only changes when it needs
3072 // to be removed, such as transitioning from a checkbox into a text input
3073 if (props.checked == null && props.defaultChecked != null) {
3074 node.defaultChecked = !!props.defaultChecked;
3075 }
3076 }
3077}
3078function postMountWrapper(element, props, isHydrating) {
3079 var node = element; // Do not assign value if it is already set. This prevents user text input
3080 // from being lost during SSR hydration.
3081
3082 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
3083 var type = props.type;
3084 var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
3085 // default value provided by the browser. See: #12872
3086
3087 if (isButton && (props.value === undefined || props.value === null)) {
3088 return;
3089 }
3090
3091 var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
3092 // from being lost during SSR hydration.
3093
3094 if (!isHydrating) {
3095 if (disableInputAttributeSyncing) {
3096 var value = getToStringValue(props.value); // When not syncing the value attribute, the value property points
3097 // directly to the React prop. Only assign it if it exists.
3098
3099 if (value != null) {
3100 // Always assign on buttons so that it is possible to assign an
3101 // empty string to clear button text.
3102 //
3103 // Otherwise, do not re-assign the value property if is empty. This
3104 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
3105 // prematurely marking required inputs as invalid. Equality is compared
3106 // to the current value in case the browser provided value is not an
3107 // empty string.
3108 if (isButton || value !== node.value) {
3109 node.value = toString(value);
3110 }
3111 }
3112 } else {
3113 // When syncing the value attribute, the value property should use
3114 // the wrapperState._initialValue property. This uses:
3115 //
3116 // 1. The value React property when present
3117 // 2. The defaultValue React property when present
3118 // 3. An empty string
3119 if (initialValue !== node.value) {
3120 node.value = initialValue;
3121 }
3122 }
3123 }
3124
3125 if (disableInputAttributeSyncing) {
3126 // When not syncing the value attribute, assign the value attribute
3127 // directly from the defaultValue React property (when present)
3128 var defaultValue = getToStringValue(props.defaultValue);
3129
3130 if (defaultValue != null) {
3131 node.defaultValue = toString(defaultValue);
3132 }
3133 } else {
3134 // Otherwise, the value attribute is synchronized to the property,
3135 // so we assign defaultValue to the same thing as the value property
3136 // assignment step above.
3137 node.defaultValue = initialValue;
3138 }
3139 } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
3140 // this is needed to work around a chrome bug where setting defaultChecked
3141 // will sometimes influence the value of checked (even after detachment).
3142 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
3143 // We need to temporarily unset name to avoid disrupting radio button groups.
3144
3145
3146 var name = node.name;
3147
3148 if (name !== '') {
3149 node.name = '';
3150 }
3151
3152 if (disableInputAttributeSyncing) {
3153 // When not syncing the checked attribute, the checked property
3154 // never gets assigned. It must be manually set. We don't want
3155 // to do this when hydrating so that existing user input isn't
3156 // modified
3157 if (!isHydrating) {
3158 updateChecked(element, props);
3159 } // Only assign the checked attribute if it is defined. This saves
3160 // a DOM write when controlling the checked attribute isn't needed
3161 // (text inputs, submit/reset)
3162
3163
3164 if (props.hasOwnProperty('defaultChecked')) {
3165 node.defaultChecked = !node.defaultChecked;
3166 node.defaultChecked = !!props.defaultChecked;
3167 }
3168 } else {
3169 // When syncing the checked attribute, both the checked property and
3170 // attribute are assigned at the same time using defaultChecked. This uses:
3171 //
3172 // 1. The checked React property when present
3173 // 2. The defaultChecked React property when present
3174 // 3. Otherwise, false
3175 node.defaultChecked = !node.defaultChecked;
3176 node.defaultChecked = !!node._wrapperState.initialChecked;
3177 }
3178
3179 if (name !== '') {
3180 node.name = name;
3181 }
3182}
3183function restoreControlledState$1(element, props) {
3184 var node = element;
3185 updateWrapper(node, props);
3186 updateNamedCousins(node, props);
3187}
3188
3189function updateNamedCousins(rootNode, props) {
3190 var name = props.name;
3191
3192 if (props.type === 'radio' && name != null) {
3193 var queryRoot = rootNode;
3194
3195 while (queryRoot.parentNode) {
3196 queryRoot = queryRoot.parentNode;
3197 } // If `rootNode.form` was non-null, then we could try `form.elements`,
3198 // but that sometimes behaves strangely in IE8. We could also try using
3199 // `form.getElementsByName`, but that will only return direct children
3200 // and won't include inputs that use the HTML5 `form=` attribute. Since
3201 // the input might not even be in a form. It might not even be in the
3202 // document. Let's just use the local `querySelectorAll` to ensure we don't
3203 // miss anything.
3204
3205
3206 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3207
3208 for (var i = 0; i < group.length; i++) {
3209 var otherNode = group[i];
3210
3211 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3212 continue;
3213 } // This will throw if radio buttons rendered by different copies of React
3214 // and the same name are rendered into the same form (same as #1939).
3215 // That's probably okay; we don't support it just as we don't support
3216 // mixing React radio buttons with non-React ones.
3217
3218
3219 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3220
3221 (function () {
3222 if (!otherProps) {
3223 {
3224 throw ReactError(Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."));
3225 }
3226 }
3227 })(); // We need update the tracked value on the named cousin since the value
3228 // was changed but the input saw no event or value set
3229
3230
3231 updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
3232 // was previously checked to update will cause it to be come re-checked
3233 // as appropriate.
3234
3235 updateWrapper(otherNode, otherProps);
3236 }
3237 }
3238} // In Chrome, assigning defaultValue to certain input types triggers input validation.
3239// For number inputs, the display value loses trailing decimal points. For email inputs,
3240// Chrome raises "The specified value <x> is not a valid email address".
3241//
3242// Here we check to see if the defaultValue has actually changed, avoiding these problems
3243// when the user is inputting text
3244//
3245// https://github.com/facebook/react/issues/7253
3246
3247
3248function setDefaultValue(node, type, value) {
3249 if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3250 type !== 'number' || node.ownerDocument.activeElement !== node) {
3251 if (value == null) {
3252 node.defaultValue = toString(node._wrapperState.initialValue);
3253 } else if (node.defaultValue !== toString(value)) {
3254 node.defaultValue = toString(value);
3255 }
3256 }
3257}
3258
3259var didWarnSelectedSetOnOption = false;
3260var didWarnInvalidChild = false;
3261
3262function flattenChildren(children) {
3263 var content = ''; // Flatten children. We'll warn if they are invalid
3264 // during validateProps() which runs for hydration too.
3265 // Note that this would throw on non-element objects.
3266 // Elements are stringified (which is normally irrelevant
3267 // but matters for <fbt>).
3268
3269 React.Children.forEach(children, function (child) {
3270 if (child == null) {
3271 return;
3272 }
3273
3274 content += child; // Note: we don't warn about invalid children here.
3275 // Instead, this is done separately below so that
3276 // it happens during the hydration codepath too.
3277 });
3278 return content;
3279}
3280/**
3281 * Implements an <option> host component that warns when `selected` is set.
3282 */
3283
3284
3285function validateProps(element, props) {
3286 {
3287 // This mirrors the codepath above, but runs for hydration too.
3288 // Warn about invalid children here so that client and hydration are consistent.
3289 // TODO: this seems like it could cause a DEV-only throw for hydration
3290 // if children contains a non-element object. We should try to avoid that.
3291 if (typeof props.children === 'object' && props.children !== null) {
3292 React.Children.forEach(props.children, function (child) {
3293 if (child == null) {
3294 return;
3295 }
3296
3297 if (typeof child === 'string' || typeof child === 'number') {
3298 return;
3299 }
3300
3301 if (typeof child.type !== 'string') {
3302 return;
3303 }
3304
3305 if (!didWarnInvalidChild) {
3306 didWarnInvalidChild = true;
3307 warning$1(false, 'Only strings and numbers are supported as <option> children.');
3308 }
3309 });
3310 } // TODO: Remove support for `selected` in <option>.
3311
3312
3313 if (props.selected != null && !didWarnSelectedSetOnOption) {
3314 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
3315 didWarnSelectedSetOnOption = true;
3316 }
3317 }
3318}
3319function postMountWrapper$1(element, props) {
3320 // value="" should make a value attribute (#6219)
3321 if (props.value != null) {
3322 element.setAttribute('value', toString(getToStringValue(props.value)));
3323 }
3324}
3325function getHostProps$1(element, props) {
3326 var hostProps = _assign({
3327 children: undefined
3328 }, props);
3329
3330 var content = flattenChildren(props.children);
3331
3332 if (content) {
3333 hostProps.children = content;
3334 }
3335
3336 return hostProps;
3337}
3338
3339// TODO: direct imports like some-package/src/* are bad. Fix me.
3340var didWarnValueDefaultValue$1;
3341
3342{
3343 didWarnValueDefaultValue$1 = false;
3344}
3345
3346function getDeclarationErrorAddendum() {
3347 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
3348
3349 if (ownerName) {
3350 return '\n\nCheck the render method of `' + ownerName + '`.';
3351 }
3352
3353 return '';
3354}
3355
3356var valuePropNames = ['value', 'defaultValue'];
3357/**
3358 * Validation function for `value` and `defaultValue`.
3359 */
3360
3361function checkSelectPropTypes(props) {
3362 ReactControlledValuePropTypes.checkPropTypes('select', props);
3363
3364 for (var i = 0; i < valuePropNames.length; i++) {
3365 var propName = valuePropNames[i];
3366
3367 if (props[propName] == null) {
3368 continue;
3369 }
3370
3371 var isArray = Array.isArray(props[propName]);
3372
3373 if (props.multiple && !isArray) {
3374 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
3375 } else if (!props.multiple && isArray) {
3376 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
3377 }
3378 }
3379}
3380
3381function updateOptions(node, multiple, propValue, setDefaultSelected) {
3382 var options = node.options;
3383
3384 if (multiple) {
3385 var selectedValues = propValue;
3386 var selectedValue = {};
3387
3388 for (var i = 0; i < selectedValues.length; i++) {
3389 // Prefix to avoid chaos with special keys.
3390 selectedValue['$' + selectedValues[i]] = true;
3391 }
3392
3393 for (var _i = 0; _i < options.length; _i++) {
3394 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
3395
3396 if (options[_i].selected !== selected) {
3397 options[_i].selected = selected;
3398 }
3399
3400 if (selected && setDefaultSelected) {
3401 options[_i].defaultSelected = true;
3402 }
3403 }
3404 } else {
3405 // Do not set `select.value` as exact behavior isn't consistent across all
3406 // browsers for all cases.
3407 var _selectedValue = toString(getToStringValue(propValue));
3408
3409 var defaultSelected = null;
3410
3411 for (var _i2 = 0; _i2 < options.length; _i2++) {
3412 if (options[_i2].value === _selectedValue) {
3413 options[_i2].selected = true;
3414
3415 if (setDefaultSelected) {
3416 options[_i2].defaultSelected = true;
3417 }
3418
3419 return;
3420 }
3421
3422 if (defaultSelected === null && !options[_i2].disabled) {
3423 defaultSelected = options[_i2];
3424 }
3425 }
3426
3427 if (defaultSelected !== null) {
3428 defaultSelected.selected = true;
3429 }
3430 }
3431}
3432/**
3433 * Implements a <select> host component that allows optionally setting the
3434 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
3435 * stringable. If `multiple` is true, the prop must be an array of stringables.
3436 *
3437 * If `value` is not supplied (or null/undefined), user actions that change the
3438 * selected option will trigger updates to the rendered options.
3439 *
3440 * If it is supplied (and not null/undefined), the rendered options will not
3441 * update in response to user actions. Instead, the `value` prop must change in
3442 * order for the rendered options to update.
3443 *
3444 * If `defaultValue` is provided, any options with the supplied values will be
3445 * selected.
3446 */
3447
3448
3449function getHostProps$2(element, props) {
3450 return _assign({}, props, {
3451 value: undefined
3452 });
3453}
3454function initWrapperState$1(element, props) {
3455 var node = element;
3456
3457 {
3458 checkSelectPropTypes(props);
3459 }
3460
3461 node._wrapperState = {
3462 wasMultiple: !!props.multiple
3463 };
3464
3465 {
3466 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
3467 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');
3468 didWarnValueDefaultValue$1 = true;
3469 }
3470 }
3471}
3472function postMountWrapper$2(element, props) {
3473 var node = element;
3474 node.multiple = !!props.multiple;
3475 var value = props.value;
3476
3477 if (value != null) {
3478 updateOptions(node, !!props.multiple, value, false);
3479 } else if (props.defaultValue != null) {
3480 updateOptions(node, !!props.multiple, props.defaultValue, true);
3481 }
3482}
3483function postUpdateWrapper(element, props) {
3484 var node = element;
3485 var wasMultiple = node._wrapperState.wasMultiple;
3486 node._wrapperState.wasMultiple = !!props.multiple;
3487 var value = props.value;
3488
3489 if (value != null) {
3490 updateOptions(node, !!props.multiple, value, false);
3491 } else if (wasMultiple !== !!props.multiple) {
3492 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
3493 if (props.defaultValue != null) {
3494 updateOptions(node, !!props.multiple, props.defaultValue, true);
3495 } else {
3496 // Revert the select back to its default unselected state.
3497 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
3498 }
3499 }
3500}
3501function restoreControlledState$2(element, props) {
3502 var node = element;
3503 var value = props.value;
3504
3505 if (value != null) {
3506 updateOptions(node, !!props.multiple, value, false);
3507 }
3508}
3509
3510var didWarnValDefaultVal = false;
3511
3512/**
3513 * Implements a <textarea> host component that allows setting `value`, and
3514 * `defaultValue`. This differs from the traditional DOM API because value is
3515 * usually set as PCDATA children.
3516 *
3517 * If `value` is not supplied (or null/undefined), user actions that affect the
3518 * value will trigger updates to the element.
3519 *
3520 * If `value` is supplied (and not null/undefined), the rendered element will
3521 * not trigger updates to the element. Instead, the `value` prop must change in
3522 * order for the rendered element to be updated.
3523 *
3524 * The rendered element will be initialized with an empty value, the prop
3525 * `defaultValue` if specified, or the children content (deprecated).
3526 */
3527function getHostProps$3(element, props) {
3528 var node = element;
3529
3530 (function () {
3531 if (!(props.dangerouslySetInnerHTML == null)) {
3532 {
3533 throw ReactError(Error("`dangerouslySetInnerHTML` does not make sense on <textarea>."));
3534 }
3535 }
3536 })(); // Always set children to the same thing. In IE9, the selection range will
3537 // get reset if `textContent` is mutated. We could add a check in setTextContent
3538 // to only set the value if/when the value differs from the node value (which would
3539 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
3540 // solution. The value can be a boolean or object so that's why it's forced
3541 // to be a string.
3542
3543
3544 var hostProps = _assign({}, props, {
3545 value: undefined,
3546 defaultValue: undefined,
3547 children: toString(node._wrapperState.initialValue)
3548 });
3549
3550 return hostProps;
3551}
3552function initWrapperState$2(element, props) {
3553 var node = element;
3554
3555 {
3556 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
3557
3558 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
3559 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');
3560 didWarnValDefaultVal = true;
3561 }
3562 }
3563
3564 var initialValue = props.value; // Only bother fetching default value if we're going to use it
3565
3566 if (initialValue == null) {
3567 var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>.
3568
3569 var children = props.children;
3570
3571 if (children != null) {
3572 {
3573 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
3574 }
3575
3576 (function () {
3577 if (!(defaultValue == null)) {
3578 {
3579 throw ReactError(Error("If you supply `defaultValue` on a <textarea>, do not pass children."));
3580 }
3581 }
3582 })();
3583
3584 if (Array.isArray(children)) {
3585 (function () {
3586 if (!(children.length <= 1)) {
3587 {
3588 throw ReactError(Error("<textarea> can only have at most one child."));
3589 }
3590 }
3591 })();
3592
3593 children = children[0];
3594 }
3595
3596 defaultValue = children;
3597 }
3598
3599 if (defaultValue == null) {
3600 defaultValue = '';
3601 }
3602
3603 initialValue = defaultValue;
3604 }
3605
3606 node._wrapperState = {
3607 initialValue: getToStringValue(initialValue)
3608 };
3609}
3610function updateWrapper$1(element, props) {
3611 var node = element;
3612 var value = getToStringValue(props.value);
3613 var defaultValue = getToStringValue(props.defaultValue);
3614
3615 if (value != null) {
3616 // Cast `value` to a string to ensure the value is set correctly. While
3617 // browsers typically do this as necessary, jsdom doesn't.
3618 var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
3619
3620 if (newValue !== node.value) {
3621 node.value = newValue;
3622 }
3623
3624 if (props.defaultValue == null && node.defaultValue !== newValue) {
3625 node.defaultValue = newValue;
3626 }
3627 }
3628
3629 if (defaultValue != null) {
3630 node.defaultValue = toString(defaultValue);
3631 }
3632}
3633function postMountWrapper$3(element, props) {
3634 var node = element; // This is in postMount because we need access to the DOM node, which is not
3635 // available until after the component has mounted.
3636
3637 var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
3638 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
3639 // will populate textContent as well.
3640 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
3641
3642 if (textContent === node._wrapperState.initialValue) {
3643 if (textContent !== '' && textContent !== null) {
3644 node.value = textContent;
3645 }
3646 }
3647}
3648function restoreControlledState$3(element, props) {
3649 // DOM component is still mounted; update
3650 updateWrapper$1(element, props);
3651}
3652
3653var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
3654var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3655var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
3656var Namespaces = {
3657 html: HTML_NAMESPACE$1,
3658 mathml: MATH_NAMESPACE,
3659 svg: SVG_NAMESPACE
3660}; // Assumes there is no parent namespace.
3661
3662function getIntrinsicNamespace(type) {
3663 switch (type) {
3664 case 'svg':
3665 return SVG_NAMESPACE;
3666
3667 case 'math':
3668 return MATH_NAMESPACE;
3669
3670 default:
3671 return HTML_NAMESPACE$1;
3672 }
3673}
3674function getChildNamespace(parentNamespace, type) {
3675 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
3676 // No (or default) parent namespace: potential entry point.
3677 return getIntrinsicNamespace(type);
3678 }
3679
3680 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
3681 // We're leaving SVG.
3682 return HTML_NAMESPACE$1;
3683 } // By default, pass namespace below.
3684
3685
3686 return parentNamespace;
3687}
3688
3689/* globals MSApp */
3690
3691/**
3692 * Create a function which has 'unsafe' privileges (required by windows8 apps)
3693 */
3694var createMicrosoftUnsafeLocalFunction = function (func) {
3695 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
3696 return function (arg0, arg1, arg2, arg3) {
3697 MSApp.execUnsafeLocalFunction(function () {
3698 return func(arg0, arg1, arg2, arg3);
3699 });
3700 };
3701 } else {
3702 return func;
3703 }
3704};
3705
3706var reusableSVGContainer;
3707/**
3708 * Set the innerHTML property of a node
3709 *
3710 * @param {DOMElement} node
3711 * @param {string} html
3712 * @internal
3713 */
3714
3715var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
3716 if (node.namespaceURI === Namespaces.svg) {
3717 {
3718 if (enableTrustedTypesIntegration) {
3719 // TODO: reconsider the text of this warning and when it should show
3720 // before enabling the feature flag.
3721 !(typeof trustedTypes === 'undefined') ? warning$1(false, "Using 'dangerouslySetInnerHTML' in an svg element with " + 'Trusted Types enabled in an Internet Explorer will cause ' + 'the trusted value to be converted to string. Assigning string ' + "to 'innerHTML' will throw an error if Trusted Types are enforced. " + "You can try to wrap your svg element inside a div and use 'dangerouslySetInnerHTML' " + 'on the enclosing div instead.') : void 0;
3722 }
3723 }
3724
3725 if (!('innerHTML' in node)) {
3726 // IE does not have innerHTML for SVG nodes, so instead we inject the
3727 // new markup in a temp node and then move the child nodes across into
3728 // the target node
3729 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
3730 reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
3731 var svgNode = reusableSVGContainer.firstChild;
3732
3733 while (node.firstChild) {
3734 node.removeChild(node.firstChild);
3735 }
3736
3737 while (svgNode.firstChild) {
3738 node.appendChild(svgNode.firstChild);
3739 }
3740
3741 return;
3742 }
3743 }
3744
3745 node.innerHTML = html;
3746});
3747
3748/**
3749 * HTML nodeType values that represent the type of the node
3750 */
3751var ELEMENT_NODE = 1;
3752var TEXT_NODE = 3;
3753var COMMENT_NODE = 8;
3754var DOCUMENT_NODE = 9;
3755var DOCUMENT_FRAGMENT_NODE = 11;
3756
3757/**
3758 * Set the textContent property of a node. For text updates, it's faster
3759 * to set the `nodeValue` of the Text node directly instead of using
3760 * `.textContent` which will remove the existing node and create a new one.
3761 *
3762 * @param {DOMElement} node
3763 * @param {string} text
3764 * @internal
3765 */
3766
3767var setTextContent = function (node, text) {
3768 if (text) {
3769 var firstChild = node.firstChild;
3770
3771 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
3772 firstChild.nodeValue = text;
3773 return;
3774 }
3775 }
3776
3777 node.textContent = text;
3778};
3779
3780// Do not use the below two methods directly!
3781// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
3782// (It is the only module that is allowed to access these methods.)
3783function unsafeCastStringToDOMTopLevelType(topLevelType) {
3784 return topLevelType;
3785}
3786function unsafeCastDOMTopLevelTypeToString(topLevelType) {
3787 return topLevelType;
3788}
3789
3790/**
3791 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
3792 *
3793 * @param {string} styleProp
3794 * @param {string} eventName
3795 * @returns {object}
3796 */
3797
3798function makePrefixMap(styleProp, eventName) {
3799 var prefixes = {};
3800 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
3801 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
3802 prefixes['Moz' + styleProp] = 'moz' + eventName;
3803 return prefixes;
3804}
3805/**
3806 * A list of event names to a configurable list of vendor prefixes.
3807 */
3808
3809
3810var vendorPrefixes = {
3811 animationend: makePrefixMap('Animation', 'AnimationEnd'),
3812 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
3813 animationstart: makePrefixMap('Animation', 'AnimationStart'),
3814 transitionend: makePrefixMap('Transition', 'TransitionEnd')
3815};
3816/**
3817 * Event names that have already been detected and prefixed (if applicable).
3818 */
3819
3820var prefixedEventNames = {};
3821/**
3822 * Element to check for prefixes on.
3823 */
3824
3825var style = {};
3826/**
3827 * Bootstrap if a DOM exists.
3828 */
3829
3830if (canUseDOM) {
3831 style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
3832 // the un-prefixed "animation" and "transition" properties are defined on the
3833 // style object but the events that fire will still be prefixed, so we need
3834 // to check if the un-prefixed events are usable, and if not remove them from the map.
3835
3836 if (!('AnimationEvent' in window)) {
3837 delete vendorPrefixes.animationend.animation;
3838 delete vendorPrefixes.animationiteration.animation;
3839 delete vendorPrefixes.animationstart.animation;
3840 } // Same as above
3841
3842
3843 if (!('TransitionEvent' in window)) {
3844 delete vendorPrefixes.transitionend.transition;
3845 }
3846}
3847/**
3848 * Attempts to determine the correct vendor prefixed event name.
3849 *
3850 * @param {string} eventName
3851 * @returns {string}
3852 */
3853
3854
3855function getVendorPrefixedEventName(eventName) {
3856 if (prefixedEventNames[eventName]) {
3857 return prefixedEventNames[eventName];
3858 } else if (!vendorPrefixes[eventName]) {
3859 return eventName;
3860 }
3861
3862 var prefixMap = vendorPrefixes[eventName];
3863
3864 for (var styleProp in prefixMap) {
3865 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
3866 return prefixedEventNames[eventName] = prefixMap[styleProp];
3867 }
3868 }
3869
3870 return eventName;
3871}
3872
3873/**
3874 * To identify top level events in ReactDOM, we use constants defined by this
3875 * module. This is the only module that uses the unsafe* methods to express
3876 * that the constants actually correspond to the browser event names. This lets
3877 * us save some bundle size by avoiding a top level type -> event name map.
3878 * The rest of ReactDOM code should import top level types from this file.
3879 */
3880
3881var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
3882var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
3883var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
3884var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
3885var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
3886var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
3887var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
3888var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
3889var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
3890var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
3891var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
3892var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
3893var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
3894var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
3895var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
3896var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
3897var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
3898var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
3899var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
3900var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
3901var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
3902var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
3903var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
3904var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
3905var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
3906var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
3907var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
3908var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
3909var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
3910var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
3911var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
3912var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
3913var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
3914var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
3915var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
3916var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
3917var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
3918var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
3919var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
3920var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
3921var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
3922var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
3923var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
3924var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
3925var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
3926var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
3927var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
3928var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
3929var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
3930var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
3931var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
3932var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
3933var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
3934var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
3935var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
3936
3937
3938var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
3939var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
3940var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
3941var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
3942var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
3943var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
3944var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
3945var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
3946var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
3947var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
3948var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
3949var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
3950var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
3951var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
3952var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
3953var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
3954var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
3955var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
3956var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
3957var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
3958var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
3959var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
3960var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
3961var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
3962var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
3963// Note that events in this list will *not* be listened to at the top level
3964// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
3965
3966var 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];
3967function getRawEventName(topLevelType) {
3968 return unsafeCastDOMTopLevelTypeToString(topLevelType);
3969}
3970
3971var attemptSynchronousHydration;
3972function setAttemptSynchronousHydration(fn) {
3973 attemptSynchronousHydration = fn;
3974} // TODO: Upgrade this definition once we're on a newer version of Flow that
3975// has this definition built-in.
3976
3977var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
3978
3979var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
3980
3981// if the last target was dehydrated.
3982
3983var queuedFocus = null;
3984var queuedDrag = null;
3985var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
3986
3987var queuedPointers = new Map();
3988var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
3989
3990function hasQueuedDiscreteEvents() {
3991 return queuedDiscreteEvents.length > 0;
3992}
3993
3994var discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];
3995var continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];
3996function isReplayableDiscreteEvent(eventType) {
3997 return discreteReplayableEvents.indexOf(eventType) > -1;
3998}
3999
4000function trapReplayableEvent(topLevelType, document, listeningSet) {
4001 listenToTopLevel(topLevelType, document, listeningSet);
4002
4003 if (enableFlareAPI) {
4004 // Trap events for the responder system.
4005 var passiveEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_passive';
4006
4007 if (!listeningSet.has(passiveEventKey)) {
4008 trapEventForResponderEventSystem(document, topLevelType, true);
4009 listeningSet.add(passiveEventKey);
4010 } // TODO: This listens to all events as active which might have
4011 // undesirable effects. It's also unnecessary to have both
4012 // passive and active listeners. Instead, we could start with
4013 // a passive and upgrade it to an active one if needed.
4014 // For replaying purposes the active is never needed since we
4015 // currently don't preventDefault.
4016
4017
4018 var activeEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_active';
4019
4020 if (!listeningSet.has(activeEventKey)) {
4021 trapEventForResponderEventSystem(document, topLevelType, false);
4022 listeningSet.add(activeEventKey);
4023 }
4024 }
4025}
4026
4027function eagerlyTrapReplayableEvents(document) {
4028 var listeningSet = getListeningSetForElement(document); // Discrete
4029
4030 discreteReplayableEvents.forEach(function (topLevelType) {
4031 trapReplayableEvent(topLevelType, document, listeningSet);
4032 }); // Continuous
4033
4034 continuousReplayableEvents.forEach(function (topLevelType) {
4035 trapReplayableEvent(topLevelType, document, listeningSet);
4036 });
4037}
4038
4039function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4040 return {
4041 blockedOn: blockedOn,
4042 topLevelType: topLevelType,
4043 eventSystemFlags: eventSystemFlags | IS_REPLAYED,
4044 nativeEvent: nativeEvent
4045 };
4046}
4047
4048function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4049 var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4050 queuedDiscreteEvents.push(queuedEvent);
4051
4052 if (enableSelectiveHydration) {
4053 if (queuedDiscreteEvents.length === 1) {
4054 // If this was the first discrete event, we might be able to
4055 // synchronously unblock it so that preventDefault still works.
4056 while (queuedEvent.blockedOn !== null) {
4057 var _fiber = getInstanceFromNode$1(queuedEvent.blockedOn);
4058
4059 if (_fiber === null) {
4060 break;
4061 }
4062
4063 attemptSynchronousHydration(_fiber);
4064
4065 if (queuedEvent.blockedOn === null) {
4066 // We got unblocked by hydration. Let's try again.
4067 replayUnblockedEvents(); // If we're reblocked, on an inner boundary, we might need
4068 // to attempt hydrating that one.
4069
4070 continue;
4071 } else {
4072 // We're still blocked from hydation, we have to give up
4073 // and replay later.
4074 break;
4075 }
4076 }
4077 }
4078 }
4079} // Resets the replaying for this type of continuous event to no event.
4080
4081function clearIfContinuousEvent(topLevelType, nativeEvent) {
4082 switch (topLevelType) {
4083 case TOP_FOCUS:
4084 case TOP_BLUR:
4085 queuedFocus = null;
4086 break;
4087
4088 case TOP_DRAG_ENTER:
4089 case TOP_DRAG_LEAVE:
4090 queuedDrag = null;
4091 break;
4092
4093 case TOP_MOUSE_OVER:
4094 case TOP_MOUSE_OUT:
4095 queuedMouse = null;
4096 break;
4097
4098 case TOP_POINTER_OVER:
4099 case TOP_POINTER_OUT:
4100 {
4101 var pointerId = nativeEvent.pointerId;
4102 queuedPointers.delete(pointerId);
4103 break;
4104 }
4105
4106 case TOP_GOT_POINTER_CAPTURE:
4107 case TOP_LOST_POINTER_CAPTURE:
4108 {
4109 var _pointerId = nativeEvent.pointerId;
4110 queuedPointerCaptures.delete(_pointerId);
4111 break;
4112 }
4113 }
4114}
4115
4116function accumulateOrCreateQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4117 if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
4118 return createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4119 } // If we have already queued this exact event, then it's because
4120 // the different event systems have different DOM event listeners.
4121 // We can accumulate the flags and store a single event to be
4122 // replayed.
4123
4124
4125 existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
4126 return existingQueuedEvent;
4127}
4128
4129function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4130 // These set relatedTarget to null because the replayed event will be treated as if we
4131 // moved from outside the window (no target) onto the target once it hydrates.
4132 // Instead of mutating we could clone the event.
4133 switch (topLevelType) {
4134 case TOP_FOCUS:
4135 {
4136 var focusEvent = nativeEvent;
4137 queuedFocus = accumulateOrCreateQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, focusEvent);
4138 return true;
4139 }
4140
4141 case TOP_DRAG_ENTER:
4142 {
4143 var dragEvent = nativeEvent;
4144 queuedDrag = accumulateOrCreateQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, dragEvent);
4145 return true;
4146 }
4147
4148 case TOP_MOUSE_OVER:
4149 {
4150 var mouseEvent = nativeEvent;
4151 queuedMouse = accumulateOrCreateQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, mouseEvent);
4152 return true;
4153 }
4154
4155 case TOP_POINTER_OVER:
4156 {
4157 var pointerEvent = nativeEvent;
4158 var pointerId = pointerEvent.pointerId;
4159 queuedPointers.set(pointerId, accumulateOrCreateQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, pointerEvent));
4160 return true;
4161 }
4162
4163 case TOP_GOT_POINTER_CAPTURE:
4164 {
4165 var _pointerEvent = nativeEvent;
4166 var _pointerId2 = _pointerEvent.pointerId;
4167 queuedPointerCaptures.set(_pointerId2, accumulateOrCreateQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, _pointerEvent));
4168 return true;
4169 }
4170 }
4171
4172 return false;
4173}
4174
4175function attemptReplayQueuedEvent(queuedEvent) {
4176 if (queuedEvent.blockedOn !== null) {
4177 return false;
4178 }
4179
4180 var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.nativeEvent);
4181
4182 if (nextBlockedOn !== null) {
4183 // We're still blocked. Try again later.
4184 queuedEvent.blockedOn = nextBlockedOn;
4185 return false;
4186 }
4187
4188 return true;
4189}
4190
4191function attemptReplayQueuedEventInMap(queuedEvent, key, map) {
4192 if (attemptReplayQueuedEvent(queuedEvent)) {
4193 map.delete(key);
4194 }
4195}
4196
4197function replayUnblockedEvents() {
4198 hasScheduledReplayAttempt = false; // First replay discrete events.
4199
4200 while (queuedDiscreteEvents.length > 0) {
4201 var nextDiscreteEvent = queuedDiscreteEvents[0];
4202
4203 if (nextDiscreteEvent.blockedOn !== null) {
4204 // We're still blocked.
4205 break;
4206 }
4207
4208 var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.nativeEvent);
4209
4210 if (nextBlockedOn !== null) {
4211 // We're still blocked. Try again later.
4212 nextDiscreteEvent.blockedOn = nextBlockedOn;
4213 } else {
4214 // We've successfully replayed the first event. Let's try the next one.
4215 queuedDiscreteEvents.shift();
4216 }
4217 } // Next replay any continuous events.
4218
4219
4220 if (queuedFocus !== null && attemptReplayQueuedEvent(queuedFocus)) {
4221 queuedFocus = null;
4222 }
4223
4224 if (queuedDrag !== null && attemptReplayQueuedEvent(queuedDrag)) {
4225 queuedDrag = null;
4226 }
4227
4228 if (queuedMouse !== null && attemptReplayQueuedEvent(queuedMouse)) {
4229 queuedMouse = null;
4230 }
4231
4232 queuedPointers.forEach(attemptReplayQueuedEventInMap);
4233 queuedPointerCaptures.forEach(attemptReplayQueuedEventInMap);
4234}
4235
4236function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
4237 if (queuedEvent.blockedOn === unblocked) {
4238 queuedEvent.blockedOn = null;
4239
4240 if (!hasScheduledReplayAttempt) {
4241 hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
4242 // now unblocked. This first might not actually be unblocked yet.
4243 // We could check it early to avoid scheduling an unnecessary callback.
4244
4245 unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
4246 }
4247 }
4248}
4249
4250function retryIfBlockedOn(unblocked) {
4251 // Mark anything that was blocked on this as no longer blocked
4252 // and eligible for a replay.
4253 if (queuedDiscreteEvents.length > 0) {
4254 scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
4255 // worth it because we expect very few discrete events to queue up and once
4256 // we are actually fully unblocked it will be fast to replay them.
4257
4258 for (var i = 1; i < queuedDiscreteEvents.length; i++) {
4259 var queuedEvent = queuedDiscreteEvents[i];
4260
4261 if (queuedEvent.blockedOn === unblocked) {
4262 queuedEvent.blockedOn = null;
4263 }
4264 }
4265 }
4266
4267 if (queuedFocus !== null) {
4268 scheduleCallbackIfUnblocked(queuedFocus, unblocked);
4269 }
4270
4271 if (queuedDrag !== null) {
4272 scheduleCallbackIfUnblocked(queuedDrag, unblocked);
4273 }
4274
4275 if (queuedMouse !== null) {
4276 scheduleCallbackIfUnblocked(queuedMouse, unblocked);
4277 }
4278
4279 var unblock = function (queuedEvent) {
4280 return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
4281 };
4282
4283 queuedPointers.forEach(unblock);
4284 queuedPointerCaptures.forEach(unblock);
4285}
4286
4287/**
4288 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4289 * instance (key) and the internal representation (value). This allows public
4290 * methods to accept the user facing instance as an argument and map them back
4291 * to internal methods.
4292 *
4293 * Note that this module is currently shared and assumed to be stateless.
4294 * If this becomes an actual Map, that will break.
4295 */
4296
4297/**
4298 * This API should be called `delete` but we'd have to make sure to always
4299 * transform these to strings for IE support. When this transform is fully
4300 * supported we can rename it.
4301 */
4302
4303function get(key) {
4304 return key._reactInternalFiber;
4305}
4306function has$1(key) {
4307 return key._reactInternalFiber !== undefined;
4308}
4309function set(key, value) {
4310 key._reactInternalFiber = value;
4311}
4312
4313// Don't change these two values. They're used by React Dev Tools.
4314var NoEffect =
4315/* */
43160;
4317var PerformedWork =
4318/* */
43191; // You can change the rest (and add more).
4320
4321var Placement =
4322/* */
43232;
4324var Update =
4325/* */
43264;
4327var PlacementAndUpdate =
4328/* */
43296;
4330var Deletion =
4331/* */
43328;
4333var ContentReset =
4334/* */
433516;
4336var Callback =
4337/* */
433832;
4339var DidCapture =
4340/* */
434164;
4342var Ref =
4343/* */
4344128;
4345var Snapshot =
4346/* */
4347256;
4348var Passive =
4349/* */
4350512;
4351var Hydrating =
4352/* */
43531024;
4354var HydratingAndUpdate =
4355/* */
43561028; // Passive & Update & Callback & Ref & Snapshot
4357
4358var LifecycleEffectMask =
4359/* */
4360932; // Union of all host effects
4361
4362var HostEffectMask =
4363/* */
43642047;
4365var Incomplete =
4366/* */
43672048;
4368var ShouldCapture =
4369/* */
43704096;
4371
4372var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
4373function getNearestMountedFiber(fiber) {
4374 var node = fiber;
4375 var nearestMounted = fiber;
4376
4377 if (!fiber.alternate) {
4378 // If there is no alternate, this might be a new tree that isn't inserted
4379 // yet. If it is, then it will have a pending insertion effect on it.
4380 var nextNode = node;
4381
4382 do {
4383 node = nextNode;
4384
4385 if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
4386 // This is an insertion or in-progress hydration. The nearest possible
4387 // mounted fiber is the parent but we need to continue to figure out
4388 // if that one is still mounted.
4389 nearestMounted = node.return;
4390 }
4391
4392 nextNode = node.return;
4393 } while (nextNode);
4394 } else {
4395 while (node.return) {
4396 node = node.return;
4397 }
4398 }
4399
4400 if (node.tag === HostRoot) {
4401 // TODO: Check if this was a nested HostRoot when used with
4402 // renderContainerIntoSubtree.
4403 return nearestMounted;
4404 } // If we didn't hit the root, that means that we're in an disconnected tree
4405 // that has been unmounted.
4406
4407
4408 return null;
4409}
4410function getSuspenseInstanceFromFiber(fiber) {
4411 if (fiber.tag === SuspenseComponent) {
4412 var suspenseState = fiber.memoizedState;
4413
4414 if (suspenseState === null) {
4415 var current = fiber.alternate;
4416
4417 if (current !== null) {
4418 suspenseState = current.memoizedState;
4419 }
4420 }
4421
4422 if (suspenseState !== null) {
4423 return suspenseState.dehydrated;
4424 }
4425 }
4426
4427 return null;
4428}
4429function getContainerFromFiber(fiber) {
4430 return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
4431}
4432function isFiberMounted(fiber) {
4433 return getNearestMountedFiber(fiber) === fiber;
4434}
4435function isMounted(component) {
4436 {
4437 var owner = ReactCurrentOwner$1.current;
4438
4439 if (owner !== null && owner.tag === ClassComponent) {
4440 var ownerFiber = owner;
4441 var instance = ownerFiber.stateNode;
4442 !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;
4443 instance._warnedAboutRefsInRender = true;
4444 }
4445 }
4446
4447 var fiber = get(component);
4448
4449 if (!fiber) {
4450 return false;
4451 }
4452
4453 return getNearestMountedFiber(fiber) === fiber;
4454}
4455
4456function assertIsMounted(fiber) {
4457 (function () {
4458 if (!(getNearestMountedFiber(fiber) === fiber)) {
4459 {
4460 throw ReactError(Error("Unable to find node on an unmounted component."));
4461 }
4462 }
4463 })();
4464}
4465
4466function findCurrentFiberUsingSlowPath(fiber) {
4467 var alternate = fiber.alternate;
4468
4469 if (!alternate) {
4470 // If there is no alternate, then we only need to check if it is mounted.
4471 var nearestMounted = getNearestMountedFiber(fiber);
4472
4473 (function () {
4474 if (!(nearestMounted !== null)) {
4475 {
4476 throw ReactError(Error("Unable to find node on an unmounted component."));
4477 }
4478 }
4479 })();
4480
4481 if (nearestMounted !== fiber) {
4482 return null;
4483 }
4484
4485 return fiber;
4486 } // If we have two possible branches, we'll walk backwards up to the root
4487 // to see what path the root points to. On the way we may hit one of the
4488 // special cases and we'll deal with them.
4489
4490
4491 var a = fiber;
4492 var b = alternate;
4493
4494 while (true) {
4495 var parentA = a.return;
4496
4497 if (parentA === null) {
4498 // We're at the root.
4499 break;
4500 }
4501
4502 var parentB = parentA.alternate;
4503
4504 if (parentB === null) {
4505 // There is no alternate. This is an unusual case. Currently, it only
4506 // happens when a Suspense component is hidden. An extra fragment fiber
4507 // is inserted in between the Suspense fiber and its children. Skip
4508 // over this extra fragment fiber and proceed to the next parent.
4509 var nextParent = parentA.return;
4510
4511 if (nextParent !== null) {
4512 a = b = nextParent;
4513 continue;
4514 } // If there's no parent, we're at the root.
4515
4516
4517 break;
4518 } // If both copies of the parent fiber point to the same child, we can
4519 // assume that the child is current. This happens when we bailout on low
4520 // priority: the bailed out fiber's child reuses the current child.
4521
4522
4523 if (parentA.child === parentB.child) {
4524 var child = parentA.child;
4525
4526 while (child) {
4527 if (child === a) {
4528 // We've determined that A is the current branch.
4529 assertIsMounted(parentA);
4530 return fiber;
4531 }
4532
4533 if (child === b) {
4534 // We've determined that B is the current branch.
4535 assertIsMounted(parentA);
4536 return alternate;
4537 }
4538
4539 child = child.sibling;
4540 } // We should never have an alternate for any mounting node. So the only
4541 // way this could possibly happen is if this was unmounted, if at all.
4542
4543
4544 (function () {
4545 {
4546 {
4547 throw ReactError(Error("Unable to find node on an unmounted component."));
4548 }
4549 }
4550 })();
4551 }
4552
4553 if (a.return !== b.return) {
4554 // The return pointer of A and the return pointer of B point to different
4555 // fibers. We assume that return pointers never criss-cross, so A must
4556 // belong to the child set of A.return, and B must belong to the child
4557 // set of B.return.
4558 a = parentA;
4559 b = parentB;
4560 } else {
4561 // The return pointers point to the same fiber. We'll have to use the
4562 // default, slow path: scan the child sets of each parent alternate to see
4563 // which child belongs to which set.
4564 //
4565 // Search parent A's child set
4566 var didFindChild = false;
4567 var _child = parentA.child;
4568
4569 while (_child) {
4570 if (_child === a) {
4571 didFindChild = true;
4572 a = parentA;
4573 b = parentB;
4574 break;
4575 }
4576
4577 if (_child === b) {
4578 didFindChild = true;
4579 b = parentA;
4580 a = parentB;
4581 break;
4582 }
4583
4584 _child = _child.sibling;
4585 }
4586
4587 if (!didFindChild) {
4588 // Search parent B's child set
4589 _child = parentB.child;
4590
4591 while (_child) {
4592 if (_child === a) {
4593 didFindChild = true;
4594 a = parentB;
4595 b = parentA;
4596 break;
4597 }
4598
4599 if (_child === b) {
4600 didFindChild = true;
4601 b = parentB;
4602 a = parentA;
4603 break;
4604 }
4605
4606 _child = _child.sibling;
4607 }
4608
4609 (function () {
4610 if (!didFindChild) {
4611 {
4612 throw ReactError(Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."));
4613 }
4614 }
4615 })();
4616 }
4617 }
4618
4619 (function () {
4620 if (!(a.alternate === b)) {
4621 {
4622 throw ReactError(Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."));
4623 }
4624 }
4625 })();
4626 } // If the root is not a host container, we're in a disconnected tree. I.e.
4627 // unmounted.
4628
4629
4630 (function () {
4631 if (!(a.tag === HostRoot)) {
4632 {
4633 throw ReactError(Error("Unable to find node on an unmounted component."));
4634 }
4635 }
4636 })();
4637
4638 if (a.stateNode.current === a) {
4639 // We've determined that A is the current branch.
4640 return fiber;
4641 } // Otherwise B has to be current branch.
4642
4643
4644 return alternate;
4645}
4646function findCurrentHostFiber(parent) {
4647 var currentParent = findCurrentFiberUsingSlowPath(parent);
4648
4649 if (!currentParent) {
4650 return null;
4651 } // Next we'll drill down this component to find the first HostComponent/Text.
4652
4653
4654 var node = currentParent;
4655
4656 while (true) {
4657 if (node.tag === HostComponent || node.tag === HostText) {
4658 return node;
4659 } else if (node.child) {
4660 node.child.return = node;
4661 node = node.child;
4662 continue;
4663 }
4664
4665 if (node === currentParent) {
4666 return null;
4667 }
4668
4669 while (!node.sibling) {
4670 if (!node.return || node.return === currentParent) {
4671 return null;
4672 }
4673
4674 node = node.return;
4675 }
4676
4677 node.sibling.return = node.return;
4678 node = node.sibling;
4679 } // Flow needs the return null here, but ESLint complains about it.
4680 // eslint-disable-next-line no-unreachable
4681
4682
4683 return null;
4684}
4685function findCurrentHostFiberWithNoPortals(parent) {
4686 var currentParent = findCurrentFiberUsingSlowPath(parent);
4687
4688 if (!currentParent) {
4689 return null;
4690 } // Next we'll drill down this component to find the first HostComponent/Text.
4691
4692
4693 var node = currentParent;
4694
4695 while (true) {
4696 if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI && node.tag === FundamentalComponent) {
4697 return node;
4698 } else if (node.child && node.tag !== HostPortal) {
4699 node.child.return = node;
4700 node = node.child;
4701 continue;
4702 }
4703
4704 if (node === currentParent) {
4705 return null;
4706 }
4707
4708 while (!node.sibling) {
4709 if (!node.return || node.return === currentParent) {
4710 return null;
4711 }
4712
4713 node = node.return;
4714 }
4715
4716 node.sibling.return = node.return;
4717 node = node.sibling;
4718 } // Flow needs the return null here, but ESLint complains about it.
4719 // eslint-disable-next-line no-unreachable
4720
4721
4722 return null;
4723}
4724
4725function addEventBubbleListener(element, eventType, listener) {
4726 element.addEventListener(eventType, listener, false);
4727}
4728function addEventCaptureListener(element, eventType, listener) {
4729 element.addEventListener(eventType, listener, true);
4730}
4731function addEventCaptureListenerWithPassiveFlag(element, eventType, listener, passive) {
4732 element.addEventListener(eventType, listener, {
4733 capture: true,
4734 passive: passive
4735 });
4736}
4737
4738/**
4739 * Gets the target node from a native browser event by accounting for
4740 * inconsistencies in browser DOM APIs.
4741 *
4742 * @param {object} nativeEvent Native browser event.
4743 * @return {DOMEventTarget} Target node.
4744 */
4745
4746function getEventTarget(nativeEvent) {
4747 // Fallback to nativeEvent.srcElement for IE9
4748 // https://github.com/facebook/react/issues/12506
4749 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
4750
4751 if (target.correspondingUseElement) {
4752 target = target.correspondingUseElement;
4753 } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
4754 // @see http://www.quirksmode.org/js/events_properties.html
4755
4756
4757 return target.nodeType === TEXT_NODE ? target.parentNode : target;
4758}
4759
4760function getParent(inst) {
4761 do {
4762 inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
4763 // That is depending on if we want nested subtrees (layers) to bubble
4764 // events to their parent. We could also go through parentNode on the
4765 // host node but that wouldn't work for React Native and doesn't let us
4766 // do the portal feature.
4767 } while (inst && inst.tag !== HostComponent);
4768
4769 if (inst) {
4770 return inst;
4771 }
4772
4773 return null;
4774}
4775/**
4776 * Return the lowest common ancestor of A and B, or null if they are in
4777 * different trees.
4778 */
4779
4780
4781function getLowestCommonAncestor(instA, instB) {
4782 var depthA = 0;
4783
4784 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
4785 depthA++;
4786 }
4787
4788 var depthB = 0;
4789
4790 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
4791 depthB++;
4792 } // If A is deeper, crawl up.
4793
4794
4795 while (depthA - depthB > 0) {
4796 instA = getParent(instA);
4797 depthA--;
4798 } // If B is deeper, crawl up.
4799
4800
4801 while (depthB - depthA > 0) {
4802 instB = getParent(instB);
4803 depthB--;
4804 } // Walk in lockstep until we find a match.
4805
4806
4807 var depth = depthA;
4808
4809 while (depth--) {
4810 if (instA === instB || instA === instB.alternate) {
4811 return instA;
4812 }
4813
4814 instA = getParent(instA);
4815 instB = getParent(instB);
4816 }
4817
4818 return null;
4819}
4820/**
4821 * Return if A is an ancestor of B.
4822 */
4823
4824
4825/**
4826 * Return the parent instance of the passed-in instance.
4827 */
4828
4829
4830/**
4831 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
4832 */
4833
4834function traverseTwoPhase(inst, fn, arg) {
4835 var path = [];
4836
4837 while (inst) {
4838 path.push(inst);
4839 inst = getParent(inst);
4840 }
4841
4842 var i;
4843
4844 for (i = path.length; i-- > 0;) {
4845 fn(path[i], 'captured', arg);
4846 }
4847
4848 for (i = 0; i < path.length; i++) {
4849 fn(path[i], 'bubbled', arg);
4850 }
4851}
4852/**
4853 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
4854 * should would receive a `mouseEnter` or `mouseLeave` event.
4855 *
4856 * Does not invoke the callback on the nearest common ancestor because nothing
4857 * "entered" or "left" that element.
4858 */
4859
4860function traverseEnterLeave(from, to, fn, argFrom, argTo) {
4861 var common = from && to ? getLowestCommonAncestor(from, to) : null;
4862 var pathFrom = [];
4863
4864 while (true) {
4865 if (!from) {
4866 break;
4867 }
4868
4869 if (from === common) {
4870 break;
4871 }
4872
4873 var alternate = from.alternate;
4874
4875 if (alternate !== null && alternate === common) {
4876 break;
4877 }
4878
4879 pathFrom.push(from);
4880 from = getParent(from);
4881 }
4882
4883 var pathTo = [];
4884
4885 while (true) {
4886 if (!to) {
4887 break;
4888 }
4889
4890 if (to === common) {
4891 break;
4892 }
4893
4894 var _alternate = to.alternate;
4895
4896 if (_alternate !== null && _alternate === common) {
4897 break;
4898 }
4899
4900 pathTo.push(to);
4901 to = getParent(to);
4902 }
4903
4904 for (var i = 0; i < pathFrom.length; i++) {
4905 fn(pathFrom[i], 'bubbled', argFrom);
4906 }
4907
4908 for (var _i = pathTo.length; _i-- > 0;) {
4909 fn(pathTo[_i], 'captured', argTo);
4910 }
4911}
4912
4913/**
4914 * Some event types have a notion of different registration names for different
4915 * "phases" of propagation. This finds listeners by a given phase.
4916 */
4917function listenerAtPhase(inst, event, propagationPhase) {
4918 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
4919 return getListener(inst, registrationName);
4920}
4921/**
4922 * A small set of propagation patterns, each of which will accept a small amount
4923 * of information, and generate a set of "dispatch ready event objects" - which
4924 * are sets of events that have already been annotated with a set of dispatched
4925 * listener functions/ids. The API is designed this way to discourage these
4926 * propagation strategies from actually executing the dispatches, since we
4927 * always want to collect the entire set of dispatches before executing even a
4928 * single one.
4929 */
4930
4931/**
4932 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
4933 * here, allows us to not have to bind or create functions for each event.
4934 * Mutating the event's members allows us to not have to create a wrapping
4935 * "dispatch" object that pairs the event with the listener.
4936 */
4937
4938
4939function accumulateDirectionalDispatches(inst, phase, event) {
4940 {
4941 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
4942 }
4943
4944 var listener = listenerAtPhase(inst, event, phase);
4945
4946 if (listener) {
4947 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4948 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4949 }
4950}
4951/**
4952 * Collect dispatches (must be entirely collected before dispatching - see unit
4953 * tests). Lazily allocate the array to conserve memory. We must loop through
4954 * each event and perform the traversal for each one. We cannot perform a
4955 * single traversal for the entire collection of events because each event may
4956 * have a different target.
4957 */
4958
4959
4960function accumulateTwoPhaseDispatchesSingle(event) {
4961 if (event && event.dispatchConfig.phasedRegistrationNames) {
4962 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
4963 }
4964}
4965/**
4966 * Accumulates without regard to direction, does not look for phased
4967 * registration names. Same as `accumulateDirectDispatchesSingle` but without
4968 * requiring that the `dispatchMarker` be the same as the dispatched ID.
4969 */
4970
4971
4972function accumulateDispatches(inst, ignoredDirection, event) {
4973 if (inst && event && event.dispatchConfig.registrationName) {
4974 var registrationName = event.dispatchConfig.registrationName;
4975 var listener = getListener(inst, registrationName);
4976
4977 if (listener) {
4978 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4979 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4980 }
4981 }
4982}
4983/**
4984 * Accumulates dispatches on an `SyntheticEvent`, but only for the
4985 * `dispatchMarker`.
4986 * @param {SyntheticEvent} event
4987 */
4988
4989
4990function accumulateDirectDispatchesSingle(event) {
4991 if (event && event.dispatchConfig.registrationName) {
4992 accumulateDispatches(event._targetInst, null, event);
4993 }
4994}
4995
4996function accumulateTwoPhaseDispatches(events) {
4997 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
4998}
4999
5000function accumulateEnterLeaveDispatches(leave, enter, from, to) {
5001 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
5002}
5003function accumulateDirectDispatches(events) {
5004 forEachAccumulated(events, accumulateDirectDispatchesSingle);
5005}
5006
5007/* eslint valid-typeof: 0 */
5008var EVENT_POOL_SIZE = 10;
5009/**
5010 * @interface Event
5011 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5012 */
5013
5014var EventInterface = {
5015 type: null,
5016 target: null,
5017 // currentTarget is set when dispatching; no use in copying it here
5018 currentTarget: function () {
5019 return null;
5020 },
5021 eventPhase: null,
5022 bubbles: null,
5023 cancelable: null,
5024 timeStamp: function (event) {
5025 return event.timeStamp || Date.now();
5026 },
5027 defaultPrevented: null,
5028 isTrusted: null
5029};
5030
5031function functionThatReturnsTrue() {
5032 return true;
5033}
5034
5035function functionThatReturnsFalse() {
5036 return false;
5037}
5038/**
5039 * Synthetic events are dispatched by event plugins, typically in response to a
5040 * top-level event delegation handler.
5041 *
5042 * These systems should generally use pooling to reduce the frequency of garbage
5043 * collection. The system should check `isPersistent` to determine whether the
5044 * event should be released into the pool after being dispatched. Users that
5045 * need a persisted event should invoke `persist`.
5046 *
5047 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
5048 * normalizing browser quirks. Subclasses do not necessarily have to implement a
5049 * DOM interface; custom application-specific events can also subclass this.
5050 *
5051 * @param {object} dispatchConfig Configuration used to dispatch this event.
5052 * @param {*} targetInst Marker identifying the event target.
5053 * @param {object} nativeEvent Native browser event.
5054 * @param {DOMEventTarget} nativeEventTarget Target node.
5055 */
5056
5057
5058function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
5059 {
5060 // these have a getter/setter for warnings
5061 delete this.nativeEvent;
5062 delete this.preventDefault;
5063 delete this.stopPropagation;
5064 delete this.isDefaultPrevented;
5065 delete this.isPropagationStopped;
5066 }
5067
5068 this.dispatchConfig = dispatchConfig;
5069 this._targetInst = targetInst;
5070 this.nativeEvent = nativeEvent;
5071 var Interface = this.constructor.Interface;
5072
5073 for (var propName in Interface) {
5074 if (!Interface.hasOwnProperty(propName)) {
5075 continue;
5076 }
5077
5078 {
5079 delete this[propName]; // this has a getter/setter for warnings
5080 }
5081
5082 var normalize = Interface[propName];
5083
5084 if (normalize) {
5085 this[propName] = normalize(nativeEvent);
5086 } else {
5087 if (propName === 'target') {
5088 this.target = nativeEventTarget;
5089 } else {
5090 this[propName] = nativeEvent[propName];
5091 }
5092 }
5093 }
5094
5095 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
5096
5097 if (defaultPrevented) {
5098 this.isDefaultPrevented = functionThatReturnsTrue;
5099 } else {
5100 this.isDefaultPrevented = functionThatReturnsFalse;
5101 }
5102
5103 this.isPropagationStopped = functionThatReturnsFalse;
5104 return this;
5105}
5106
5107_assign(SyntheticEvent.prototype, {
5108 preventDefault: function () {
5109 this.defaultPrevented = true;
5110 var event = this.nativeEvent;
5111
5112 if (!event) {
5113 return;
5114 }
5115
5116 if (event.preventDefault) {
5117 event.preventDefault();
5118 } else if (typeof event.returnValue !== 'unknown') {
5119 event.returnValue = false;
5120 }
5121
5122 this.isDefaultPrevented = functionThatReturnsTrue;
5123 },
5124 stopPropagation: function () {
5125 var event = this.nativeEvent;
5126
5127 if (!event) {
5128 return;
5129 }
5130
5131 if (event.stopPropagation) {
5132 event.stopPropagation();
5133 } else if (typeof event.cancelBubble !== 'unknown') {
5134 // The ChangeEventPlugin registers a "propertychange" event for
5135 // IE. This event does not support bubbling or cancelling, and
5136 // any references to cancelBubble throw "Member not found". A
5137 // typeof check of "unknown" circumvents this issue (and is also
5138 // IE specific).
5139 event.cancelBubble = true;
5140 }
5141
5142 this.isPropagationStopped = functionThatReturnsTrue;
5143 },
5144
5145 /**
5146 * We release all dispatched `SyntheticEvent`s after each event loop, adding
5147 * them back into the pool. This allows a way to hold onto a reference that
5148 * won't be added back into the pool.
5149 */
5150 persist: function () {
5151 this.isPersistent = functionThatReturnsTrue;
5152 },
5153
5154 /**
5155 * Checks if this event should be released back into the pool.
5156 *
5157 * @return {boolean} True if this should not be released, false otherwise.
5158 */
5159 isPersistent: functionThatReturnsFalse,
5160
5161 /**
5162 * `PooledClass` looks for `destructor` on each instance it releases.
5163 */
5164 destructor: function () {
5165 var Interface = this.constructor.Interface;
5166
5167 for (var propName in Interface) {
5168 {
5169 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
5170 }
5171 }
5172
5173 this.dispatchConfig = null;
5174 this._targetInst = null;
5175 this.nativeEvent = null;
5176 this.isDefaultPrevented = functionThatReturnsFalse;
5177 this.isPropagationStopped = functionThatReturnsFalse;
5178 this._dispatchListeners = null;
5179 this._dispatchInstances = null;
5180
5181 {
5182 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
5183 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
5184 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
5185 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
5186 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
5187 }
5188 }
5189});
5190
5191SyntheticEvent.Interface = EventInterface;
5192/**
5193 * Helper to reduce boilerplate when creating subclasses.
5194 */
5195
5196SyntheticEvent.extend = function (Interface) {
5197 var Super = this;
5198
5199 var E = function () {};
5200
5201 E.prototype = Super.prototype;
5202 var prototype = new E();
5203
5204 function Class() {
5205 return Super.apply(this, arguments);
5206 }
5207
5208 _assign(prototype, Class.prototype);
5209
5210 Class.prototype = prototype;
5211 Class.prototype.constructor = Class;
5212 Class.Interface = _assign({}, Super.Interface, Interface);
5213 Class.extend = Super.extend;
5214 addEventPoolingTo(Class);
5215 return Class;
5216};
5217
5218addEventPoolingTo(SyntheticEvent);
5219/**
5220 * Helper to nullify syntheticEvent instance properties when destructing
5221 *
5222 * @param {String} propName
5223 * @param {?object} getVal
5224 * @return {object} defineProperty object
5225 */
5226
5227function getPooledWarningPropertyDefinition(propName, getVal) {
5228 var isFunction = typeof getVal === 'function';
5229 return {
5230 configurable: true,
5231 set: set,
5232 get: get
5233 };
5234
5235 function set(val) {
5236 var action = isFunction ? 'setting the method' : 'setting the property';
5237 warn(action, 'This is effectively a no-op');
5238 return val;
5239 }
5240
5241 function get() {
5242 var action = isFunction ? 'accessing the method' : 'accessing the property';
5243 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
5244 warn(action, result);
5245 return getVal;
5246 }
5247
5248 function warn(action, result) {
5249 var warningCondition = false;
5250 !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;
5251 }
5252}
5253
5254function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
5255 var EventConstructor = this;
5256
5257 if (EventConstructor.eventPool.length) {
5258 var instance = EventConstructor.eventPool.pop();
5259 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
5260 return instance;
5261 }
5262
5263 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
5264}
5265
5266function releasePooledEvent(event) {
5267 var EventConstructor = this;
5268
5269 (function () {
5270 if (!(event instanceof EventConstructor)) {
5271 {
5272 throw ReactError(Error("Trying to release an event instance into a pool of a different type."));
5273 }
5274 }
5275 })();
5276
5277 event.destructor();
5278
5279 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
5280 EventConstructor.eventPool.push(event);
5281 }
5282}
5283
5284function addEventPoolingTo(EventConstructor) {
5285 EventConstructor.eventPool = [];
5286 EventConstructor.getPooled = getPooledEvent;
5287 EventConstructor.release = releasePooledEvent;
5288}
5289
5290/**
5291 * @interface Event
5292 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
5293 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
5294 */
5295
5296var SyntheticAnimationEvent = SyntheticEvent.extend({
5297 animationName: null,
5298 elapsedTime: null,
5299 pseudoElement: null
5300});
5301
5302/**
5303 * @interface Event
5304 * @see http://www.w3.org/TR/clipboard-apis/
5305 */
5306
5307var SyntheticClipboardEvent = SyntheticEvent.extend({
5308 clipboardData: function (event) {
5309 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
5310 }
5311});
5312
5313var SyntheticUIEvent = SyntheticEvent.extend({
5314 view: null,
5315 detail: null
5316});
5317
5318/**
5319 * @interface FocusEvent
5320 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5321 */
5322
5323var SyntheticFocusEvent = SyntheticUIEvent.extend({
5324 relatedTarget: null
5325});
5326
5327/**
5328 * `charCode` represents the actual "character code" and is safe to use with
5329 * `String.fromCharCode`. As such, only keys that correspond to printable
5330 * characters produce a valid `charCode`, the only exception to this is Enter.
5331 * The Tab-key is considered non-printable and does not have a `charCode`,
5332 * presumably because it does not produce a tab-character in browsers.
5333 *
5334 * @param {object} nativeEvent Native browser event.
5335 * @return {number} Normalized `charCode` property.
5336 */
5337function getEventCharCode(nativeEvent) {
5338 var charCode;
5339 var keyCode = nativeEvent.keyCode;
5340
5341 if ('charCode' in nativeEvent) {
5342 charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
5343
5344 if (charCode === 0 && keyCode === 13) {
5345 charCode = 13;
5346 }
5347 } else {
5348 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
5349 charCode = keyCode;
5350 } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
5351 // report Enter as charCode 10 when ctrl is pressed.
5352
5353
5354 if (charCode === 10) {
5355 charCode = 13;
5356 } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
5357 // Must not discard the (non-)printable Enter-key.
5358
5359
5360 if (charCode >= 32 || charCode === 13) {
5361 return charCode;
5362 }
5363
5364 return 0;
5365}
5366
5367/**
5368 * Normalization of deprecated HTML5 `key` values
5369 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5370 */
5371
5372var normalizeKey = {
5373 Esc: 'Escape',
5374 Spacebar: ' ',
5375 Left: 'ArrowLeft',
5376 Up: 'ArrowUp',
5377 Right: 'ArrowRight',
5378 Down: 'ArrowDown',
5379 Del: 'Delete',
5380 Win: 'OS',
5381 Menu: 'ContextMenu',
5382 Apps: 'ContextMenu',
5383 Scroll: 'ScrollLock',
5384 MozPrintableKey: 'Unidentified'
5385};
5386/**
5387 * Translation from legacy `keyCode` to HTML5 `key`
5388 * Only special keys supported, all others depend on keyboard layout or browser
5389 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5390 */
5391
5392var translateToKey = {
5393 '8': 'Backspace',
5394 '9': 'Tab',
5395 '12': 'Clear',
5396 '13': 'Enter',
5397 '16': 'Shift',
5398 '17': 'Control',
5399 '18': 'Alt',
5400 '19': 'Pause',
5401 '20': 'CapsLock',
5402 '27': 'Escape',
5403 '32': ' ',
5404 '33': 'PageUp',
5405 '34': 'PageDown',
5406 '35': 'End',
5407 '36': 'Home',
5408 '37': 'ArrowLeft',
5409 '38': 'ArrowUp',
5410 '39': 'ArrowRight',
5411 '40': 'ArrowDown',
5412 '45': 'Insert',
5413 '46': 'Delete',
5414 '112': 'F1',
5415 '113': 'F2',
5416 '114': 'F3',
5417 '115': 'F4',
5418 '116': 'F5',
5419 '117': 'F6',
5420 '118': 'F7',
5421 '119': 'F8',
5422 '120': 'F9',
5423 '121': 'F10',
5424 '122': 'F11',
5425 '123': 'F12',
5426 '144': 'NumLock',
5427 '145': 'ScrollLock',
5428 '224': 'Meta'
5429};
5430/**
5431 * @param {object} nativeEvent Native browser event.
5432 * @return {string} Normalized `key` property.
5433 */
5434
5435function getEventKey(nativeEvent) {
5436 if (nativeEvent.key) {
5437 // Normalize inconsistent values reported by browsers due to
5438 // implementations of a working draft specification.
5439 // FireFox implements `key` but returns `MozPrintableKey` for all
5440 // printable characters (normalized to `Unidentified`), ignore it.
5441 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
5442
5443 if (key !== 'Unidentified') {
5444 return key;
5445 }
5446 } // Browser does not implement `key`, polyfill as much of it as we can.
5447
5448
5449 if (nativeEvent.type === 'keypress') {
5450 var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
5451 // thus be captured by `keypress`, no other non-printable key should.
5452
5453 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
5454 }
5455
5456 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
5457 // While user keyboard layout determines the actual meaning of each
5458 // `keyCode` value, almost all function keys have a universal value.
5459 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
5460 }
5461
5462 return '';
5463}
5464
5465/**
5466 * Translation from modifier key to the associated property in the event.
5467 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
5468 */
5469var modifierKeyToProp = {
5470 Alt: 'altKey',
5471 Control: 'ctrlKey',
5472 Meta: 'metaKey',
5473 Shift: 'shiftKey'
5474}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
5475// getModifierState. If getModifierState is not supported, we map it to a set of
5476// modifier keys exposed by the event. In this case, Lock-keys are not supported.
5477
5478function modifierStateGetter(keyArg) {
5479 var syntheticEvent = this;
5480 var nativeEvent = syntheticEvent.nativeEvent;
5481
5482 if (nativeEvent.getModifierState) {
5483 return nativeEvent.getModifierState(keyArg);
5484 }
5485
5486 var keyProp = modifierKeyToProp[keyArg];
5487 return keyProp ? !!nativeEvent[keyProp] : false;
5488}
5489
5490function getEventModifierState(nativeEvent) {
5491 return modifierStateGetter;
5492}
5493
5494/**
5495 * @interface KeyboardEvent
5496 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5497 */
5498
5499var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
5500 key: getEventKey,
5501 location: null,
5502 ctrlKey: null,
5503 shiftKey: null,
5504 altKey: null,
5505 metaKey: null,
5506 repeat: null,
5507 locale: null,
5508 getModifierState: getEventModifierState,
5509 // Legacy Interface
5510 charCode: function (event) {
5511 // `charCode` is the result of a KeyPress event and represents the value of
5512 // the actual printable character.
5513 // KeyPress is deprecated, but its replacement is not yet final and not
5514 // implemented in any major browser. Only KeyPress has charCode.
5515 if (event.type === 'keypress') {
5516 return getEventCharCode(event);
5517 }
5518
5519 return 0;
5520 },
5521 keyCode: function (event) {
5522 // `keyCode` is the result of a KeyDown/Up event and represents the value of
5523 // physical keyboard key.
5524 // The actual meaning of the value depends on the users' keyboard layout
5525 // which cannot be detected. Assuming that it is a US keyboard layout
5526 // provides a surprisingly accurate mapping for US and European users.
5527 // Due to this, it is left to the user to implement at this time.
5528 if (event.type === 'keydown' || event.type === 'keyup') {
5529 return event.keyCode;
5530 }
5531
5532 return 0;
5533 },
5534 which: function (event) {
5535 // `which` is an alias for either `keyCode` or `charCode` depending on the
5536 // type of the event.
5537 if (event.type === 'keypress') {
5538 return getEventCharCode(event);
5539 }
5540
5541 if (event.type === 'keydown' || event.type === 'keyup') {
5542 return event.keyCode;
5543 }
5544
5545 return 0;
5546 }
5547});
5548
5549var previousScreenX = 0;
5550var previousScreenY = 0; // Use flags to signal movementX/Y has already been set
5551
5552var isMovementXSet = false;
5553var isMovementYSet = false;
5554/**
5555 * @interface MouseEvent
5556 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5557 */
5558
5559var SyntheticMouseEvent = SyntheticUIEvent.extend({
5560 screenX: null,
5561 screenY: null,
5562 clientX: null,
5563 clientY: null,
5564 pageX: null,
5565 pageY: null,
5566 ctrlKey: null,
5567 shiftKey: null,
5568 altKey: null,
5569 metaKey: null,
5570 getModifierState: getEventModifierState,
5571 button: null,
5572 buttons: null,
5573 relatedTarget: function (event) {
5574 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
5575 },
5576 movementX: function (event) {
5577 if ('movementX' in event) {
5578 return event.movementX;
5579 }
5580
5581 var screenX = previousScreenX;
5582 previousScreenX = event.screenX;
5583
5584 if (!isMovementXSet) {
5585 isMovementXSet = true;
5586 return 0;
5587 }
5588
5589 return event.type === 'mousemove' ? event.screenX - screenX : 0;
5590 },
5591 movementY: function (event) {
5592 if ('movementY' in event) {
5593 return event.movementY;
5594 }
5595
5596 var screenY = previousScreenY;
5597 previousScreenY = event.screenY;
5598
5599 if (!isMovementYSet) {
5600 isMovementYSet = true;
5601 return 0;
5602 }
5603
5604 return event.type === 'mousemove' ? event.screenY - screenY : 0;
5605 }
5606});
5607
5608/**
5609 * @interface PointerEvent
5610 * @see http://www.w3.org/TR/pointerevents/
5611 */
5612
5613var SyntheticPointerEvent = SyntheticMouseEvent.extend({
5614 pointerId: null,
5615 width: null,
5616 height: null,
5617 pressure: null,
5618 tangentialPressure: null,
5619 tiltX: null,
5620 tiltY: null,
5621 twist: null,
5622 pointerType: null,
5623 isPrimary: null
5624});
5625
5626/**
5627 * @interface DragEvent
5628 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5629 */
5630
5631var SyntheticDragEvent = SyntheticMouseEvent.extend({
5632 dataTransfer: null
5633});
5634
5635/**
5636 * @interface TouchEvent
5637 * @see http://www.w3.org/TR/touch-events/
5638 */
5639
5640var SyntheticTouchEvent = SyntheticUIEvent.extend({
5641 touches: null,
5642 targetTouches: null,
5643 changedTouches: null,
5644 altKey: null,
5645 metaKey: null,
5646 ctrlKey: null,
5647 shiftKey: null,
5648 getModifierState: getEventModifierState
5649});
5650
5651/**
5652 * @interface Event
5653 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
5654 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
5655 */
5656
5657var SyntheticTransitionEvent = SyntheticEvent.extend({
5658 propertyName: null,
5659 elapsedTime: null,
5660 pseudoElement: null
5661});
5662
5663/**
5664 * @interface WheelEvent
5665 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5666 */
5667
5668var SyntheticWheelEvent = SyntheticMouseEvent.extend({
5669 deltaX: function (event) {
5670 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
5671 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
5672 },
5673 deltaY: function (event) {
5674 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
5675 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
5676 'wheelDelta' in event ? -event.wheelDelta : 0;
5677 },
5678 deltaZ: null,
5679 // Browsers without "deltaMode" is reporting in raw wheel delta where one
5680 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
5681 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
5682 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
5683 deltaMode: null
5684});
5685
5686/**
5687 * Turns
5688 * ['abort', ...]
5689 * into
5690 * eventTypes = {
5691 * 'abort': {
5692 * phasedRegistrationNames: {
5693 * bubbled: 'onAbort',
5694 * captured: 'onAbortCapture',
5695 * },
5696 * dependencies: [TOP_ABORT],
5697 * },
5698 * ...
5699 * };
5700 * topLevelEventsToDispatchConfig = new Map([
5701 * [TOP_ABORT, { sameConfig }],
5702 * ]);
5703 */
5704
5705var eventTuples = [// Discrete events
5706[TOP_BLUR, 'blur', DiscreteEvent], [TOP_CANCEL, 'cancel', DiscreteEvent], [TOP_CLICK, 'click', DiscreteEvent], [TOP_CLOSE, 'close', DiscreteEvent], [TOP_CONTEXT_MENU, 'contextMenu', DiscreteEvent], [TOP_COPY, 'copy', DiscreteEvent], [TOP_CUT, 'cut', DiscreteEvent], [TOP_AUX_CLICK, 'auxClick', DiscreteEvent], [TOP_DOUBLE_CLICK, 'doubleClick', DiscreteEvent], [TOP_DRAG_END, 'dragEnd', DiscreteEvent], [TOP_DRAG_START, 'dragStart', DiscreteEvent], [TOP_DROP, 'drop', DiscreteEvent], [TOP_FOCUS, 'focus', DiscreteEvent], [TOP_INPUT, 'input', DiscreteEvent], [TOP_INVALID, 'invalid', DiscreteEvent], [TOP_KEY_DOWN, 'keyDown', DiscreteEvent], [TOP_KEY_PRESS, 'keyPress', DiscreteEvent], [TOP_KEY_UP, 'keyUp', DiscreteEvent], [TOP_MOUSE_DOWN, 'mouseDown', DiscreteEvent], [TOP_MOUSE_UP, 'mouseUp', DiscreteEvent], [TOP_PASTE, 'paste', DiscreteEvent], [TOP_PAUSE, 'pause', DiscreteEvent], [TOP_PLAY, 'play', DiscreteEvent], [TOP_POINTER_CANCEL, 'pointerCancel', DiscreteEvent], [TOP_POINTER_DOWN, 'pointerDown', DiscreteEvent], [TOP_POINTER_UP, 'pointerUp', DiscreteEvent], [TOP_RATE_CHANGE, 'rateChange', DiscreteEvent], [TOP_RESET, 'reset', DiscreteEvent], [TOP_SEEKED, 'seeked', DiscreteEvent], [TOP_SUBMIT, 'submit', DiscreteEvent], [TOP_TOUCH_CANCEL, 'touchCancel', DiscreteEvent], [TOP_TOUCH_END, 'touchEnd', DiscreteEvent], [TOP_TOUCH_START, 'touchStart', DiscreteEvent], [TOP_VOLUME_CHANGE, 'volumeChange', DiscreteEvent], // User-blocking events
5707[TOP_DRAG, 'drag', UserBlockingEvent], [TOP_DRAG_ENTER, 'dragEnter', UserBlockingEvent], [TOP_DRAG_EXIT, 'dragExit', UserBlockingEvent], [TOP_DRAG_LEAVE, 'dragLeave', UserBlockingEvent], [TOP_DRAG_OVER, 'dragOver', UserBlockingEvent], [TOP_MOUSE_MOVE, 'mouseMove', UserBlockingEvent], [TOP_MOUSE_OUT, 'mouseOut', UserBlockingEvent], [TOP_MOUSE_OVER, 'mouseOver', UserBlockingEvent], [TOP_POINTER_MOVE, 'pointerMove', UserBlockingEvent], [TOP_POINTER_OUT, 'pointerOut', UserBlockingEvent], [TOP_POINTER_OVER, 'pointerOver', UserBlockingEvent], [TOP_SCROLL, 'scroll', UserBlockingEvent], [TOP_TOGGLE, 'toggle', UserBlockingEvent], [TOP_TOUCH_MOVE, 'touchMove', UserBlockingEvent], [TOP_WHEEL, 'wheel', UserBlockingEvent], // Continuous events
5708[TOP_ABORT, 'abort', ContinuousEvent], [TOP_ANIMATION_END, 'animationEnd', ContinuousEvent], [TOP_ANIMATION_ITERATION, 'animationIteration', ContinuousEvent], [TOP_ANIMATION_START, 'animationStart', ContinuousEvent], [TOP_CAN_PLAY, 'canPlay', ContinuousEvent], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough', ContinuousEvent], [TOP_DURATION_CHANGE, 'durationChange', ContinuousEvent], [TOP_EMPTIED, 'emptied', ContinuousEvent], [TOP_ENCRYPTED, 'encrypted', ContinuousEvent], [TOP_ENDED, 'ended', ContinuousEvent], [TOP_ERROR, 'error', ContinuousEvent], [TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', ContinuousEvent], [TOP_LOAD, 'load', ContinuousEvent], [TOP_LOADED_DATA, 'loadedData', ContinuousEvent], [TOP_LOADED_METADATA, 'loadedMetadata', ContinuousEvent], [TOP_LOAD_START, 'loadStart', ContinuousEvent], [TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', ContinuousEvent], [TOP_PLAYING, 'playing', ContinuousEvent], [TOP_PROGRESS, 'progress', ContinuousEvent], [TOP_SEEKING, 'seeking', ContinuousEvent], [TOP_STALLED, 'stalled', ContinuousEvent], [TOP_SUSPEND, 'suspend', ContinuousEvent], [TOP_TIME_UPDATE, 'timeUpdate', ContinuousEvent], [TOP_TRANSITION_END, 'transitionEnd', ContinuousEvent], [TOP_WAITING, 'waiting', ContinuousEvent]];
5709var eventTypes = {};
5710var topLevelEventsToDispatchConfig = {};
5711
5712for (var i = 0; i < eventTuples.length; i++) {
5713 var eventTuple = eventTuples[i];
5714 var topEvent = eventTuple[0];
5715 var event = eventTuple[1];
5716 var eventPriority = eventTuple[2];
5717 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
5718 var onEvent = 'on' + capitalizedEvent;
5719 var config = {
5720 phasedRegistrationNames: {
5721 bubbled: onEvent,
5722 captured: onEvent + 'Capture'
5723 },
5724 dependencies: [topEvent],
5725 eventPriority: eventPriority
5726 };
5727 eventTypes[event] = config;
5728 topLevelEventsToDispatchConfig[topEvent] = config;
5729} // Only used in DEV for exhaustiveness validation.
5730
5731
5732var 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];
5733var SimpleEventPlugin = {
5734 eventTypes: eventTypes,
5735 getEventPriority: function (topLevelType) {
5736 var config = topLevelEventsToDispatchConfig[topLevelType];
5737 return config !== undefined ? config.eventPriority : ContinuousEvent;
5738 },
5739 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
5740 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
5741
5742 if (!dispatchConfig) {
5743 return null;
5744 }
5745
5746 var EventConstructor;
5747
5748 switch (topLevelType) {
5749 case TOP_KEY_PRESS:
5750 // Firefox creates a keypress event for function keys too. This removes
5751 // the unwanted keypress events. Enter is however both printable and
5752 // non-printable. One would expect Tab to be as well (but it isn't).
5753 if (getEventCharCode(nativeEvent) === 0) {
5754 return null;
5755 }
5756
5757 /* falls through */
5758
5759 case TOP_KEY_DOWN:
5760 case TOP_KEY_UP:
5761 EventConstructor = SyntheticKeyboardEvent;
5762 break;
5763
5764 case TOP_BLUR:
5765 case TOP_FOCUS:
5766 EventConstructor = SyntheticFocusEvent;
5767 break;
5768
5769 case TOP_CLICK:
5770 // Firefox creates a click event on right mouse clicks. This removes the
5771 // unwanted click events.
5772 if (nativeEvent.button === 2) {
5773 return null;
5774 }
5775
5776 /* falls through */
5777
5778 case TOP_AUX_CLICK:
5779 case TOP_DOUBLE_CLICK:
5780 case TOP_MOUSE_DOWN:
5781 case TOP_MOUSE_MOVE:
5782 case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events
5783
5784 /* falls through */
5785
5786 case TOP_MOUSE_OUT:
5787 case TOP_MOUSE_OVER:
5788 case TOP_CONTEXT_MENU:
5789 EventConstructor = SyntheticMouseEvent;
5790 break;
5791
5792 case TOP_DRAG:
5793 case TOP_DRAG_END:
5794 case TOP_DRAG_ENTER:
5795 case TOP_DRAG_EXIT:
5796 case TOP_DRAG_LEAVE:
5797 case TOP_DRAG_OVER:
5798 case TOP_DRAG_START:
5799 case TOP_DROP:
5800 EventConstructor = SyntheticDragEvent;
5801 break;
5802
5803 case TOP_TOUCH_CANCEL:
5804 case TOP_TOUCH_END:
5805 case TOP_TOUCH_MOVE:
5806 case TOP_TOUCH_START:
5807 EventConstructor = SyntheticTouchEvent;
5808 break;
5809
5810 case TOP_ANIMATION_END:
5811 case TOP_ANIMATION_ITERATION:
5812 case TOP_ANIMATION_START:
5813 EventConstructor = SyntheticAnimationEvent;
5814 break;
5815
5816 case TOP_TRANSITION_END:
5817 EventConstructor = SyntheticTransitionEvent;
5818 break;
5819
5820 case TOP_SCROLL:
5821 EventConstructor = SyntheticUIEvent;
5822 break;
5823
5824 case TOP_WHEEL:
5825 EventConstructor = SyntheticWheelEvent;
5826 break;
5827
5828 case TOP_COPY:
5829 case TOP_CUT:
5830 case TOP_PASTE:
5831 EventConstructor = SyntheticClipboardEvent;
5832 break;
5833
5834 case TOP_GOT_POINTER_CAPTURE:
5835 case TOP_LOST_POINTER_CAPTURE:
5836 case TOP_POINTER_CANCEL:
5837 case TOP_POINTER_DOWN:
5838 case TOP_POINTER_MOVE:
5839 case TOP_POINTER_OUT:
5840 case TOP_POINTER_OVER:
5841 case TOP_POINTER_UP:
5842 EventConstructor = SyntheticPointerEvent;
5843 break;
5844
5845 default:
5846 {
5847 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
5848 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
5849 }
5850 } // HTML Events
5851 // @see http://www.w3.org/TR/html5/index.html#events-0
5852
5853
5854 EventConstructor = SyntheticEvent;
5855 break;
5856 }
5857
5858 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
5859 accumulateTwoPhaseDispatches(event);
5860 return event;
5861 }
5862};
5863
5864var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
5865// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
5866
5867if (enableFlareAPI && canUseDOM) {
5868 try {
5869 var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
5870
5871 Object.defineProperty(options, 'passive', {
5872 get: function () {
5873 passiveBrowserEventsSupported = true;
5874 }
5875 });
5876 window.addEventListener('test', options, options);
5877 window.removeEventListener('test', options, options);
5878 } catch (e) {
5879 passiveBrowserEventsSupported = false;
5880 }
5881}
5882
5883// Intentionally not named imports because Rollup would use dynamic dispatch for
5884// CommonJS interop named imports.
5885var UserBlockingPriority$1 = unstable_UserBlockingPriority;
5886var runWithPriority$1 = unstable_runWithPriority;
5887var getEventPriority = SimpleEventPlugin.getEventPriority;
5888var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
5889var callbackBookkeepingPool = [];
5890
5891/**
5892 * Find the deepest React component completely containing the root of the
5893 * passed-in instance (for use when entire React trees are nested within each
5894 * other). If React trees are not nested, returns null.
5895 */
5896function findRootContainerNode(inst) {
5897 if (inst.tag === HostRoot) {
5898 return inst.stateNode.containerInfo;
5899 } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
5900 // traversal, but caching is difficult to do correctly without using a
5901 // mutation observer to listen for all DOM changes.
5902
5903
5904 while (inst.return) {
5905 inst = inst.return;
5906 }
5907
5908 if (inst.tag !== HostRoot) {
5909 // This can happen if we're in a detached tree.
5910 return null;
5911 }
5912
5913 return inst.stateNode.containerInfo;
5914} // Used to store ancestor hierarchy in top level callback
5915
5916
5917function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
5918 if (callbackBookkeepingPool.length) {
5919 var instance = callbackBookkeepingPool.pop();
5920 instance.topLevelType = topLevelType;
5921 instance.eventSystemFlags = eventSystemFlags;
5922 instance.nativeEvent = nativeEvent;
5923 instance.targetInst = targetInst;
5924 return instance;
5925 }
5926
5927 return {
5928 topLevelType: topLevelType,
5929 eventSystemFlags: eventSystemFlags,
5930 nativeEvent: nativeEvent,
5931 targetInst: targetInst,
5932 ancestors: []
5933 };
5934}
5935
5936function releaseTopLevelCallbackBookKeeping(instance) {
5937 instance.topLevelType = null;
5938 instance.nativeEvent = null;
5939 instance.targetInst = null;
5940 instance.ancestors.length = 0;
5941
5942 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
5943 callbackBookkeepingPool.push(instance);
5944 }
5945}
5946
5947function handleTopLevel(bookKeeping) {
5948 var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
5949 // It's important that we build the array of ancestors before calling any
5950 // event handlers, because event handlers can modify the DOM, leading to
5951 // inconsistencies with ReactMount's node cache. See #1105.
5952
5953 var ancestor = targetInst;
5954
5955 do {
5956 if (!ancestor) {
5957 var ancestors = bookKeeping.ancestors;
5958 ancestors.push(ancestor);
5959 break;
5960 }
5961
5962 var root = findRootContainerNode(ancestor);
5963
5964 if (!root) {
5965 break;
5966 }
5967
5968 var tag = ancestor.tag;
5969
5970 if (tag === HostComponent || tag === HostText) {
5971 bookKeeping.ancestors.push(ancestor);
5972 }
5973
5974 ancestor = getClosestInstanceFromNode(root);
5975 } while (ancestor);
5976
5977 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
5978 targetInst = bookKeeping.ancestors[i];
5979 var eventTarget = getEventTarget(bookKeeping.nativeEvent);
5980 var topLevelType = bookKeeping.topLevelType;
5981 var nativeEvent = bookKeeping.nativeEvent;
5982 runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, bookKeeping.eventSystemFlags);
5983 }
5984} // TODO: can we stop exporting these?
5985
5986
5987var _enabled = true;
5988function setEnabled(enabled) {
5989 _enabled = !!enabled;
5990}
5991function isEnabled() {
5992 return _enabled;
5993}
5994function trapBubbledEvent(topLevelType, element) {
5995 trapEventForPluginEventSystem(element, topLevelType, false);
5996}
5997function trapCapturedEvent(topLevelType, element) {
5998 trapEventForPluginEventSystem(element, topLevelType, true);
5999}
6000function trapEventForResponderEventSystem(element, topLevelType, passive) {
6001 if (enableFlareAPI) {
6002 var rawEventName = getRawEventName(topLevelType);
6003 var eventFlags = RESPONDER_EVENT_SYSTEM; // If passive option is not supported, then the event will be
6004 // active and not passive, but we flag it as using not being
6005 // supported too. This way the responder event plugins know,
6006 // and can provide polyfills if needed.
6007
6008 if (passive) {
6009 if (passiveBrowserEventsSupported) {
6010 eventFlags |= IS_PASSIVE;
6011 } else {
6012 eventFlags |= IS_ACTIVE;
6013 eventFlags |= PASSIVE_NOT_SUPPORTED;
6014 passive = false;
6015 }
6016 } else {
6017 eventFlags |= IS_ACTIVE;
6018 } // Check if interactive and wrap in discreteUpdates
6019
6020
6021 var listener = dispatchEvent.bind(null, topLevelType, eventFlags);
6022
6023 if (passiveBrowserEventsSupported) {
6024 addEventCaptureListenerWithPassiveFlag(element, rawEventName, listener, passive);
6025 } else {
6026 addEventCaptureListener(element, rawEventName, listener);
6027 }
6028 }
6029}
6030
6031function trapEventForPluginEventSystem(element, topLevelType, capture) {
6032 var listener;
6033
6034 switch (getEventPriority(topLevelType)) {
6035 case DiscreteEvent:
6036 listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
6037 break;
6038
6039 case UserBlockingEvent:
6040 listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
6041 break;
6042
6043 case ContinuousEvent:
6044 default:
6045 listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
6046 break;
6047 }
6048
6049 var rawEventName = getRawEventName(topLevelType);
6050
6051 if (capture) {
6052 addEventCaptureListener(element, rawEventName, listener);
6053 } else {
6054 addEventBubbleListener(element, rawEventName, listener);
6055 }
6056}
6057
6058function dispatchDiscreteEvent(topLevelType, eventSystemFlags, nativeEvent) {
6059 flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
6060 discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
6061}
6062
6063function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, nativeEvent) {
6064 if (enableUserBlockingEvents) {
6065 runWithPriority$1(UserBlockingPriority$1, dispatchEvent.bind(null, topLevelType, eventSystemFlags, nativeEvent));
6066 } else {
6067 dispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
6068 }
6069}
6070
6071function dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
6072 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
6073
6074 try {
6075 // Event queue being processed in the same cycle allows
6076 // `preventDefault`.
6077 batchedEventUpdates(handleTopLevel, bookKeeping);
6078 } finally {
6079 releaseTopLevelCallbackBookKeeping(bookKeeping);
6080 }
6081}
6082
6083function dispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
6084 if (!_enabled) {
6085 return;
6086 }
6087
6088 if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
6089 // If we already have a queue of discrete events, and this is another discrete
6090 // event, then we can't dispatch it regardless of its target, since they
6091 // need to dispatch in order.
6092 queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
6093 topLevelType, eventSystemFlags, nativeEvent);
6094 return;
6095 }
6096
6097 var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
6098
6099 if (blockedOn === null) {
6100 // We successfully dispatched this event.
6101 clearIfContinuousEvent(topLevelType, nativeEvent);
6102 return;
6103 }
6104
6105 if (isReplayableDiscreteEvent(topLevelType)) {
6106 // This this to be replayed later once the target is available.
6107 queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
6108 return;
6109 }
6110
6111 if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent)) {
6112 return;
6113 } // We need to clear only if we didn't queue because
6114 // queueing is accummulative.
6115
6116
6117 clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
6118 // in case the event system needs to trace it.
6119
6120 if (enableFlareAPI) {
6121 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6122 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
6123 }
6124
6125 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6126 // React Flare event system
6127 dispatchEventForResponderEventSystem(topLevelType, null, nativeEvent, getEventTarget(nativeEvent), eventSystemFlags);
6128 }
6129 } else {
6130 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
6131 }
6132} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
6133
6134function attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
6135 // TODO: Warn if _enabled is false.
6136 var nativeEventTarget = getEventTarget(nativeEvent);
6137 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
6138
6139 if (targetInst !== null) {
6140 var nearestMounted = getNearestMountedFiber(targetInst);
6141
6142 if (nearestMounted === null) {
6143 // This tree has been unmounted already. Dispatch without a target.
6144 targetInst = null;
6145 } else {
6146 var tag = nearestMounted.tag;
6147
6148 if (tag === SuspenseComponent) {
6149 var instance = getSuspenseInstanceFromFiber(nearestMounted);
6150
6151 if (instance !== null) {
6152 // Queue the event to be replayed later. Abort dispatching since we
6153 // don't want this event dispatched twice through the event system.
6154 // TODO: If this is the first discrete event in the queue. Schedule an increased
6155 // priority for this boundary.
6156 return instance;
6157 } // This shouldn't happen, something went wrong but to avoid blocking
6158 // the whole system, dispatch the event without a target.
6159 // TODO: Warn.
6160
6161
6162 targetInst = null;
6163 } else if (tag === HostRoot) {
6164 var root = nearestMounted.stateNode;
6165
6166 if (root.hydrate) {
6167 // If this happens during a replay something went wrong and it might block
6168 // the whole system.
6169 return getContainerFromFiber(nearestMounted);
6170 }
6171
6172 targetInst = null;
6173 } else if (nearestMounted !== targetInst) {
6174 // If we get an event (ex: img onload) before committing that
6175 // component's mount, ignore it for now (that is, treat it as if it was an
6176 // event on a non-React tree). We might also consider queueing events and
6177 // dispatching them after the mount.
6178 targetInst = null;
6179 }
6180 }
6181 }
6182
6183 if (enableFlareAPI) {
6184 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6185 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6186 }
6187
6188 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6189 // React Flare event system
6190 dispatchEventForResponderEventSystem(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
6191 }
6192 } else {
6193 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6194 } // We're not blocked on anything.
6195
6196
6197 return null;
6198}
6199
6200/**
6201 * Checks if an event is supported in the current execution environment.
6202 *
6203 * NOTE: This will not work correctly for non-generic events such as `change`,
6204 * `reset`, `load`, `error`, and `select`.
6205 *
6206 * Borrows from Modernizr.
6207 *
6208 * @param {string} eventNameSuffix Event name, e.g. "click".
6209 * @return {boolean} True if the event is supported.
6210 * @internal
6211 * @license Modernizr 3.0.0pre (Custom Build) | MIT
6212 */
6213
6214function isEventSupported(eventNameSuffix) {
6215 if (!canUseDOM) {
6216 return false;
6217 }
6218
6219 var eventName = 'on' + eventNameSuffix;
6220 var isSupported = eventName in document;
6221
6222 if (!isSupported) {
6223 var element = document.createElement('div');
6224 element.setAttribute(eventName, 'return;');
6225 isSupported = typeof element[eventName] === 'function';
6226 }
6227
6228 return isSupported;
6229}
6230
6231/**
6232 * Summary of `ReactBrowserEventEmitter` event handling:
6233 *
6234 * - Top-level delegation is used to trap most native browser events. This
6235 * may only occur in the main thread and is the responsibility of
6236 * ReactDOMEventListener, which is injected and can therefore support
6237 * pluggable event sources. This is the only work that occurs in the main
6238 * thread.
6239 *
6240 * - We normalize and de-duplicate events to account for browser quirks. This
6241 * may be done in the worker thread.
6242 *
6243 * - Forward these native events (with the associated top-level type used to
6244 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
6245 * to extract any synthetic events.
6246 *
6247 * - The `EventPluginHub` will then process each event by annotating them with
6248 * "dispatches", a sequence of listeners and IDs that care about that event.
6249 *
6250 * - The `EventPluginHub` then dispatches the events.
6251 *
6252 * Overview of React and the event system:
6253 *
6254 * +------------+ .
6255 * | DOM | .
6256 * +------------+ .
6257 * | .
6258 * v .
6259 * +------------+ .
6260 * | ReactEvent | .
6261 * | Listener | .
6262 * +------------+ . +-----------+
6263 * | . +--------+|SimpleEvent|
6264 * | . | |Plugin |
6265 * +-----|------+ . v +-----------+
6266 * | | | . +--------------+ +------------+
6267 * | +-----------.--->|EventPluginHub| | Event |
6268 * | | . | | +-----------+ | Propagators|
6269 * | ReactEvent | . | | |TapEvent | |------------|
6270 * | Emitter | . | |<---+|Plugin | |other plugin|
6271 * | | . | | +-----------+ | utilities |
6272 * | +-----------.--->| | +------------+
6273 * | | | . +--------------+
6274 * +-----|------+ . ^ +-----------+
6275 * | . | |Enter/Leave|
6276 * + . +-------+|Plugin |
6277 * +-------------+ . +-----------+
6278 * | application | .
6279 * |-------------| .
6280 * | | .
6281 * | | .
6282 * +-------------+ .
6283 * .
6284 * React Core . General Purpose Event Plugin System
6285 */
6286
6287var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
6288var elementListeningSets = new PossiblyWeakMap();
6289function getListeningSetForElement(element) {
6290 var listeningSet = elementListeningSets.get(element);
6291
6292 if (listeningSet === undefined) {
6293 listeningSet = new Set();
6294 elementListeningSets.set(element, listeningSet);
6295 }
6296
6297 return listeningSet;
6298}
6299/**
6300 * We listen for bubbled touch events on the document object.
6301 *
6302 * Firefox v8.01 (and possibly others) exhibited strange behavior when
6303 * mounting `onmousemove` events at some node that was not the document
6304 * element. The symptoms were that if your mouse is not moving over something
6305 * contained within that mount point (for example on the background) the
6306 * top-level listeners for `onmousemove` won't be called. However, if you
6307 * register the `mousemove` on the document object, then it will of course
6308 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
6309 * top-level listeners to the document object only, at least for these
6310 * movement types of events and possibly all events.
6311 *
6312 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
6313 *
6314 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
6315 * they bubble to document.
6316 *
6317 * @param {string} registrationName Name of listener (e.g. `onClick`).
6318 * @param {object} mountAt Container where to mount the listener
6319 */
6320
6321function listenTo(registrationName, mountAt) {
6322 var listeningSet = getListeningSetForElement(mountAt);
6323 var dependencies = registrationNameDependencies[registrationName];
6324
6325 for (var i = 0; i < dependencies.length; i++) {
6326 var dependency = dependencies[i];
6327 listenToTopLevel(dependency, mountAt, listeningSet);
6328 }
6329}
6330function listenToTopLevel(topLevelType, mountAt, listeningSet) {
6331 if (!listeningSet.has(topLevelType)) {
6332 switch (topLevelType) {
6333 case TOP_SCROLL:
6334 trapCapturedEvent(TOP_SCROLL, mountAt);
6335 break;
6336
6337 case TOP_FOCUS:
6338 case TOP_BLUR:
6339 trapCapturedEvent(TOP_FOCUS, mountAt);
6340 trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
6341 // but this ensures we mark both as attached rather than just one.
6342
6343 listeningSet.add(TOP_BLUR);
6344 listeningSet.add(TOP_FOCUS);
6345 break;
6346
6347 case TOP_CANCEL:
6348 case TOP_CLOSE:
6349 if (isEventSupported(getRawEventName(topLevelType))) {
6350 trapCapturedEvent(topLevelType, mountAt);
6351 }
6352
6353 break;
6354
6355 case TOP_INVALID:
6356 case TOP_SUBMIT:
6357 case TOP_RESET:
6358 // We listen to them on the target DOM elements.
6359 // Some of them bubble so we don't want them to fire twice.
6360 break;
6361
6362 default:
6363 // By default, listen on the top level to all non-media events.
6364 // Media events don't bubble so adding the listener wouldn't do anything.
6365 var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;
6366
6367 if (!isMediaEvent) {
6368 trapBubbledEvent(topLevelType, mountAt);
6369 }
6370
6371 break;
6372 }
6373
6374 listeningSet.add(topLevelType);
6375 }
6376}
6377function isListeningToAllDependencies(registrationName, mountAt) {
6378 var listeningSet = getListeningSetForElement(mountAt);
6379 var dependencies = registrationNameDependencies[registrationName];
6380
6381 for (var i = 0; i < dependencies.length; i++) {
6382 var dependency = dependencies[i];
6383
6384 if (!listeningSet.has(dependency)) {
6385 return false;
6386 }
6387 }
6388
6389 return true;
6390}
6391
6392// List derived from Gecko source code:
6393// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6394var shorthandToLonghand = {
6395 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6396 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6397 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6398 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6399 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6400 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6401 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6402 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6403 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6404 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6405 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6406 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6407 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6408 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6409 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6410 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6411 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6412 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6413 columns: ['columnCount', 'columnWidth'],
6414 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6415 flexFlow: ['flexDirection', 'flexWrap'],
6416 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6417 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6418 gap: ['columnGap', 'rowGap'],
6419 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6420 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6421 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6422 gridColumnGap: ['columnGap'],
6423 gridGap: ['columnGap', 'rowGap'],
6424 gridRow: ['gridRowEnd', 'gridRowStart'],
6425 gridRowGap: ['rowGap'],
6426 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6427 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6428 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6429 marker: ['markerEnd', 'markerMid', 'markerStart'],
6430 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6431 maskPosition: ['maskPositionX', 'maskPositionY'],
6432 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6433 overflow: ['overflowX', 'overflowY'],
6434 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6435 placeContent: ['alignContent', 'justifyContent'],
6436 placeItems: ['alignItems', 'justifyItems'],
6437 placeSelf: ['alignSelf', 'justifySelf'],
6438 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6439 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6440 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6441 wordWrap: ['overflowWrap']
6442};
6443
6444/**
6445 * CSS properties which accept numbers but are not in units of "px".
6446 */
6447var isUnitlessNumber = {
6448 animationIterationCount: true,
6449 borderImageOutset: true,
6450 borderImageSlice: true,
6451 borderImageWidth: true,
6452 boxFlex: true,
6453 boxFlexGroup: true,
6454 boxOrdinalGroup: true,
6455 columnCount: true,
6456 columns: true,
6457 flex: true,
6458 flexGrow: true,
6459 flexPositive: true,
6460 flexShrink: true,
6461 flexNegative: true,
6462 flexOrder: true,
6463 gridArea: true,
6464 gridRow: true,
6465 gridRowEnd: true,
6466 gridRowSpan: true,
6467 gridRowStart: true,
6468 gridColumn: true,
6469 gridColumnEnd: true,
6470 gridColumnSpan: true,
6471 gridColumnStart: true,
6472 fontWeight: true,
6473 lineClamp: true,
6474 lineHeight: true,
6475 opacity: true,
6476 order: true,
6477 orphans: true,
6478 tabSize: true,
6479 widows: true,
6480 zIndex: true,
6481 zoom: true,
6482 // SVG-related properties
6483 fillOpacity: true,
6484 floodOpacity: true,
6485 stopOpacity: true,
6486 strokeDasharray: true,
6487 strokeDashoffset: true,
6488 strokeMiterlimit: true,
6489 strokeOpacity: true,
6490 strokeWidth: true
6491};
6492/**
6493 * @param {string} prefix vendor-specific prefix, eg: Webkit
6494 * @param {string} key style name, eg: transitionDuration
6495 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6496 * WebkitTransitionDuration
6497 */
6498
6499function prefixKey(prefix, key) {
6500 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6501}
6502/**
6503 * Support style names that may come passed in prefixed by adding permutations
6504 * of vendor prefixes.
6505 */
6506
6507
6508var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6509// infinite loop, because it iterates over the newly added props too.
6510
6511Object.keys(isUnitlessNumber).forEach(function (prop) {
6512 prefixes.forEach(function (prefix) {
6513 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6514 });
6515});
6516
6517/**
6518 * Convert a value into the proper css writable value. The style name `name`
6519 * should be logical (no hyphens), as specified
6520 * in `CSSProperty.isUnitlessNumber`.
6521 *
6522 * @param {string} name CSS property name such as `topMargin`.
6523 * @param {*} value CSS property value such as `10px`.
6524 * @return {string} Normalized style value with dimensions applied.
6525 */
6526
6527function dangerousStyleValue(name, value, isCustomProperty) {
6528 // Note that we've removed escapeTextForBrowser() calls here since the
6529 // whole string will be escaped when the attribute is injected into
6530 // the markup. If you provide unsafe user data here they can inject
6531 // arbitrary CSS which may be problematic (I couldn't repro this):
6532 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6533 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6534 // This is not an XSS hole but instead a potential CSS injection issue
6535 // which has lead to a greater discussion about how we're going to
6536 // trust URLs moving forward. See #2115901
6537 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6538
6539 if (isEmpty) {
6540 return '';
6541 }
6542
6543 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6544 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6545 }
6546
6547 return ('' + value).trim();
6548}
6549
6550var uppercasePattern = /([A-Z])/g;
6551var msPattern = /^ms-/;
6552/**
6553 * Hyphenates a camelcased CSS property name, for example:
6554 *
6555 * > hyphenateStyleName('backgroundColor')
6556 * < "background-color"
6557 * > hyphenateStyleName('MozTransition')
6558 * < "-moz-transition"
6559 * > hyphenateStyleName('msTransition')
6560 * < "-ms-transition"
6561 *
6562 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6563 * is converted to `-ms-`.
6564 */
6565
6566function hyphenateStyleName(name) {
6567 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6568}
6569
6570var warnValidStyle = function () {};
6571
6572{
6573 // 'msTransform' is correct, but the other prefixes should be capitalized
6574 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6575 var msPattern$1 = /^-ms-/;
6576 var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
6577
6578 var badStyleValueWithSemicolonPattern = /;\s*$/;
6579 var warnedStyleNames = {};
6580 var warnedStyleValues = {};
6581 var warnedForNaNValue = false;
6582 var warnedForInfinityValue = false;
6583
6584 var camelize = function (string) {
6585 return string.replace(hyphenPattern, function (_, character) {
6586 return character.toUpperCase();
6587 });
6588 };
6589
6590 var warnHyphenatedStyleName = function (name) {
6591 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6592 return;
6593 }
6594
6595 warnedStyleNames[name] = true;
6596 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
6597 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6598 // is converted to lowercase `ms`.
6599 camelize(name.replace(msPattern$1, 'ms-')));
6600 };
6601
6602 var warnBadVendoredStyleName = function (name) {
6603 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6604 return;
6605 }
6606
6607 warnedStyleNames[name] = true;
6608 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6609 };
6610
6611 var warnStyleValueWithSemicolon = function (name, value) {
6612 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6613 return;
6614 }
6615
6616 warnedStyleValues[value] = true;
6617 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6618 };
6619
6620 var warnStyleValueIsNaN = function (name, value) {
6621 if (warnedForNaNValue) {
6622 return;
6623 }
6624
6625 warnedForNaNValue = true;
6626 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6627 };
6628
6629 var warnStyleValueIsInfinity = function (name, value) {
6630 if (warnedForInfinityValue) {
6631 return;
6632 }
6633
6634 warnedForInfinityValue = true;
6635 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6636 };
6637
6638 warnValidStyle = function (name, value) {
6639 if (name.indexOf('-') > -1) {
6640 warnHyphenatedStyleName(name);
6641 } else if (badVendoredStyleNamePattern.test(name)) {
6642 warnBadVendoredStyleName(name);
6643 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6644 warnStyleValueWithSemicolon(name, value);
6645 }
6646
6647 if (typeof value === 'number') {
6648 if (isNaN(value)) {
6649 warnStyleValueIsNaN(name, value);
6650 } else if (!isFinite(value)) {
6651 warnStyleValueIsInfinity(name, value);
6652 }
6653 }
6654 };
6655}
6656
6657var warnValidStyle$1 = warnValidStyle;
6658
6659/**
6660 * Operations for dealing with CSS properties.
6661 */
6662
6663/**
6664 * This creates a string that is expected to be equivalent to the style
6665 * attribute generated by server-side rendering. It by-passes warnings and
6666 * security checks so it's not safe to use this value for anything other than
6667 * comparison. It is only used in DEV for SSR validation.
6668 */
6669
6670function createDangerousStringForStyles(styles) {
6671 {
6672 var serialized = '';
6673 var delimiter = '';
6674
6675 for (var styleName in styles) {
6676 if (!styles.hasOwnProperty(styleName)) {
6677 continue;
6678 }
6679
6680 var styleValue = styles[styleName];
6681
6682 if (styleValue != null) {
6683 var isCustomProperty = styleName.indexOf('--') === 0;
6684 serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
6685 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6686 delimiter = ';';
6687 }
6688 }
6689
6690 return serialized || null;
6691 }
6692}
6693/**
6694 * Sets the value for multiple styles on a node. If a value is specified as
6695 * '' (empty string), the corresponding style property will be unset.
6696 *
6697 * @param {DOMElement} node
6698 * @param {object} styles
6699 */
6700
6701function setValueForStyles(node, styles) {
6702 var style = node.style;
6703
6704 for (var styleName in styles) {
6705 if (!styles.hasOwnProperty(styleName)) {
6706 continue;
6707 }
6708
6709 var isCustomProperty = styleName.indexOf('--') === 0;
6710
6711 {
6712 if (!isCustomProperty) {
6713 warnValidStyle$1(styleName, styles[styleName]);
6714 }
6715 }
6716
6717 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6718
6719 if (styleName === 'float') {
6720 styleName = 'cssFloat';
6721 }
6722
6723 if (isCustomProperty) {
6724 style.setProperty(styleName, styleValue);
6725 } else {
6726 style[styleName] = styleValue;
6727 }
6728 }
6729}
6730
6731function isValueEmpty(value) {
6732 return value == null || typeof value === 'boolean' || value === '';
6733}
6734/**
6735 * Given {color: 'red', overflow: 'hidden'} returns {
6736 * color: 'color',
6737 * overflowX: 'overflow',
6738 * overflowY: 'overflow',
6739 * }. This can be read as "the overflowY property was set by the overflow
6740 * shorthand". That is, the values are the property that each was derived from.
6741 */
6742
6743
6744function expandShorthandMap(styles) {
6745 var expanded = {};
6746
6747 for (var key in styles) {
6748 var longhands = shorthandToLonghand[key] || [key];
6749
6750 for (var i = 0; i < longhands.length; i++) {
6751 expanded[longhands[i]] = key;
6752 }
6753 }
6754
6755 return expanded;
6756}
6757/**
6758 * When mixing shorthand and longhand property names, we warn during updates if
6759 * we expect an incorrect result to occur. In particular, we warn for:
6760 *
6761 * Updating a shorthand property (longhand gets overwritten):
6762 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6763 * becomes .style.font = 'baz'
6764 * Removing a shorthand property (longhand gets lost too):
6765 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6766 * becomes .style.font = ''
6767 * Removing a longhand property (should revert to shorthand; doesn't):
6768 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6769 * becomes .style.fontVariant = ''
6770 */
6771
6772
6773function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6774 if (!warnAboutShorthandPropertyCollision) {
6775 return;
6776 }
6777
6778 if (!nextStyles) {
6779 return;
6780 }
6781
6782 var expandedUpdates = expandShorthandMap(styleUpdates);
6783 var expandedStyles = expandShorthandMap(nextStyles);
6784 var warnedAbout = {};
6785
6786 for (var key in expandedUpdates) {
6787 var originalKey = expandedUpdates[key];
6788 var correctOriginalKey = expandedStyles[key];
6789
6790 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6791 var warningKey = originalKey + ',' + correctOriginalKey;
6792
6793 if (warnedAbout[warningKey]) {
6794 continue;
6795 }
6796
6797 warnedAbout[warningKey] = true;
6798 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);
6799 }
6800 }
6801}
6802
6803// For HTML, certain tags should omit their close tag. We keep a whitelist for
6804// those special-case tags.
6805var omittedCloseTags = {
6806 area: true,
6807 base: true,
6808 br: true,
6809 col: true,
6810 embed: true,
6811 hr: true,
6812 img: true,
6813 input: true,
6814 keygen: true,
6815 link: true,
6816 meta: true,
6817 param: true,
6818 source: true,
6819 track: true,
6820 wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
6821
6822};
6823
6824// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6825
6826var voidElementTags = _assign({
6827 menuitem: true
6828}, omittedCloseTags);
6829
6830// or add stack by default to invariants where possible.
6831
6832var HTML$1 = '__html';
6833var ReactDebugCurrentFrame$3 = null;
6834
6835{
6836 ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
6837}
6838
6839function assertValidProps(tag, props) {
6840 if (!props) {
6841 return;
6842 } // Note the use of `==` which checks for null or undefined.
6843
6844
6845 if (voidElementTags[tag]) {
6846 (function () {
6847 if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
6848 {
6849 throw ReactError(Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + (ReactDebugCurrentFrame$3.getStackAddendum())));
6850 }
6851 }
6852 })();
6853 }
6854
6855 if (props.dangerouslySetInnerHTML != null) {
6856 (function () {
6857 if (!(props.children == null)) {
6858 {
6859 throw ReactError(Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`."));
6860 }
6861 }
6862 })();
6863
6864 (function () {
6865 if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML)) {
6866 {
6867 throw ReactError(Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information."));
6868 }
6869 }
6870 })();
6871 }
6872
6873 {
6874 !(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;
6875 }
6876
6877 (function () {
6878 if (!(props.style == null || typeof props.style === 'object')) {
6879 {
6880 throw ReactError(Error("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())));
6881 }
6882 }
6883 })();
6884}
6885
6886function isCustomComponent(tagName, props) {
6887 if (tagName.indexOf('-') === -1) {
6888 return typeof props.is === 'string';
6889 }
6890
6891 switch (tagName) {
6892 // These are reserved SVG and MathML elements.
6893 // We don't mind this whitelist too much because we expect it to never grow.
6894 // The alternative is to track the namespace in a few places which is convoluted.
6895 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6896 case 'annotation-xml':
6897 case 'color-profile':
6898 case 'font-face':
6899 case 'font-face-src':
6900 case 'font-face-uri':
6901 case 'font-face-format':
6902 case 'font-face-name':
6903 case 'missing-glyph':
6904 return false;
6905
6906 default:
6907 return true;
6908 }
6909}
6910
6911// When adding attributes to the HTML or SVG whitelist, be sure to
6912// also add them to this module to ensure casing and incorrect name
6913// warnings.
6914var possibleStandardNames = {
6915 // HTML
6916 accept: 'accept',
6917 acceptcharset: 'acceptCharset',
6918 'accept-charset': 'acceptCharset',
6919 accesskey: 'accessKey',
6920 action: 'action',
6921 allowfullscreen: 'allowFullScreen',
6922 alt: 'alt',
6923 as: 'as',
6924 async: 'async',
6925 autocapitalize: 'autoCapitalize',
6926 autocomplete: 'autoComplete',
6927 autocorrect: 'autoCorrect',
6928 autofocus: 'autoFocus',
6929 autoplay: 'autoPlay',
6930 autosave: 'autoSave',
6931 capture: 'capture',
6932 cellpadding: 'cellPadding',
6933 cellspacing: 'cellSpacing',
6934 challenge: 'challenge',
6935 charset: 'charSet',
6936 checked: 'checked',
6937 children: 'children',
6938 cite: 'cite',
6939 class: 'className',
6940 classid: 'classID',
6941 classname: 'className',
6942 cols: 'cols',
6943 colspan: 'colSpan',
6944 content: 'content',
6945 contenteditable: 'contentEditable',
6946 contextmenu: 'contextMenu',
6947 controls: 'controls',
6948 controlslist: 'controlsList',
6949 coords: 'coords',
6950 crossorigin: 'crossOrigin',
6951 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6952 data: 'data',
6953 datetime: 'dateTime',
6954 default: 'default',
6955 defaultchecked: 'defaultChecked',
6956 defaultvalue: 'defaultValue',
6957 defer: 'defer',
6958 dir: 'dir',
6959 disabled: 'disabled',
6960 disablepictureinpicture: 'disablePictureInPicture',
6961 download: 'download',
6962 draggable: 'draggable',
6963 enctype: 'encType',
6964 for: 'htmlFor',
6965 form: 'form',
6966 formmethod: 'formMethod',
6967 formaction: 'formAction',
6968 formenctype: 'formEncType',
6969 formnovalidate: 'formNoValidate',
6970 formtarget: 'formTarget',
6971 frameborder: 'frameBorder',
6972 headers: 'headers',
6973 height: 'height',
6974 hidden: 'hidden',
6975 high: 'high',
6976 href: 'href',
6977 hreflang: 'hrefLang',
6978 htmlfor: 'htmlFor',
6979 httpequiv: 'httpEquiv',
6980 'http-equiv': 'httpEquiv',
6981 icon: 'icon',
6982 id: 'id',
6983 innerhtml: 'innerHTML',
6984 inputmode: 'inputMode',
6985 integrity: 'integrity',
6986 is: 'is',
6987 itemid: 'itemID',
6988 itemprop: 'itemProp',
6989 itemref: 'itemRef',
6990 itemscope: 'itemScope',
6991 itemtype: 'itemType',
6992 keyparams: 'keyParams',
6993 keytype: 'keyType',
6994 kind: 'kind',
6995 label: 'label',
6996 lang: 'lang',
6997 list: 'list',
6998 loop: 'loop',
6999 low: 'low',
7000 manifest: 'manifest',
7001 marginwidth: 'marginWidth',
7002 marginheight: 'marginHeight',
7003 max: 'max',
7004 maxlength: 'maxLength',
7005 media: 'media',
7006 mediagroup: 'mediaGroup',
7007 method: 'method',
7008 min: 'min',
7009 minlength: 'minLength',
7010 multiple: 'multiple',
7011 muted: 'muted',
7012 name: 'name',
7013 nomodule: 'noModule',
7014 nonce: 'nonce',
7015 novalidate: 'noValidate',
7016 open: 'open',
7017 optimum: 'optimum',
7018 pattern: 'pattern',
7019 placeholder: 'placeholder',
7020 playsinline: 'playsInline',
7021 poster: 'poster',
7022 preload: 'preload',
7023 profile: 'profile',
7024 radiogroup: 'radioGroup',
7025 readonly: 'readOnly',
7026 referrerpolicy: 'referrerPolicy',
7027 rel: 'rel',
7028 required: 'required',
7029 reversed: 'reversed',
7030 role: 'role',
7031 rows: 'rows',
7032 rowspan: 'rowSpan',
7033 sandbox: 'sandbox',
7034 scope: 'scope',
7035 scoped: 'scoped',
7036 scrolling: 'scrolling',
7037 seamless: 'seamless',
7038 selected: 'selected',
7039 shape: 'shape',
7040 size: 'size',
7041 sizes: 'sizes',
7042 span: 'span',
7043 spellcheck: 'spellCheck',
7044 src: 'src',
7045 srcdoc: 'srcDoc',
7046 srclang: 'srcLang',
7047 srcset: 'srcSet',
7048 start: 'start',
7049 step: 'step',
7050 style: 'style',
7051 summary: 'summary',
7052 tabindex: 'tabIndex',
7053 target: 'target',
7054 title: 'title',
7055 type: 'type',
7056 usemap: 'useMap',
7057 value: 'value',
7058 width: 'width',
7059 wmode: 'wmode',
7060 wrap: 'wrap',
7061 // SVG
7062 about: 'about',
7063 accentheight: 'accentHeight',
7064 'accent-height': 'accentHeight',
7065 accumulate: 'accumulate',
7066 additive: 'additive',
7067 alignmentbaseline: 'alignmentBaseline',
7068 'alignment-baseline': 'alignmentBaseline',
7069 allowreorder: 'allowReorder',
7070 alphabetic: 'alphabetic',
7071 amplitude: 'amplitude',
7072 arabicform: 'arabicForm',
7073 'arabic-form': 'arabicForm',
7074 ascent: 'ascent',
7075 attributename: 'attributeName',
7076 attributetype: 'attributeType',
7077 autoreverse: 'autoReverse',
7078 azimuth: 'azimuth',
7079 basefrequency: 'baseFrequency',
7080 baselineshift: 'baselineShift',
7081 'baseline-shift': 'baselineShift',
7082 baseprofile: 'baseProfile',
7083 bbox: 'bbox',
7084 begin: 'begin',
7085 bias: 'bias',
7086 by: 'by',
7087 calcmode: 'calcMode',
7088 capheight: 'capHeight',
7089 'cap-height': 'capHeight',
7090 clip: 'clip',
7091 clippath: 'clipPath',
7092 'clip-path': 'clipPath',
7093 clippathunits: 'clipPathUnits',
7094 cliprule: 'clipRule',
7095 'clip-rule': 'clipRule',
7096 color: 'color',
7097 colorinterpolation: 'colorInterpolation',
7098 'color-interpolation': 'colorInterpolation',
7099 colorinterpolationfilters: 'colorInterpolationFilters',
7100 'color-interpolation-filters': 'colorInterpolationFilters',
7101 colorprofile: 'colorProfile',
7102 'color-profile': 'colorProfile',
7103 colorrendering: 'colorRendering',
7104 'color-rendering': 'colorRendering',
7105 contentscripttype: 'contentScriptType',
7106 contentstyletype: 'contentStyleType',
7107 cursor: 'cursor',
7108 cx: 'cx',
7109 cy: 'cy',
7110 d: 'd',
7111 datatype: 'datatype',
7112 decelerate: 'decelerate',
7113 descent: 'descent',
7114 diffuseconstant: 'diffuseConstant',
7115 direction: 'direction',
7116 display: 'display',
7117 divisor: 'divisor',
7118 dominantbaseline: 'dominantBaseline',
7119 'dominant-baseline': 'dominantBaseline',
7120 dur: 'dur',
7121 dx: 'dx',
7122 dy: 'dy',
7123 edgemode: 'edgeMode',
7124 elevation: 'elevation',
7125 enablebackground: 'enableBackground',
7126 'enable-background': 'enableBackground',
7127 end: 'end',
7128 exponent: 'exponent',
7129 externalresourcesrequired: 'externalResourcesRequired',
7130 fill: 'fill',
7131 fillopacity: 'fillOpacity',
7132 'fill-opacity': 'fillOpacity',
7133 fillrule: 'fillRule',
7134 'fill-rule': 'fillRule',
7135 filter: 'filter',
7136 filterres: 'filterRes',
7137 filterunits: 'filterUnits',
7138 floodopacity: 'floodOpacity',
7139 'flood-opacity': 'floodOpacity',
7140 floodcolor: 'floodColor',
7141 'flood-color': 'floodColor',
7142 focusable: 'focusable',
7143 fontfamily: 'fontFamily',
7144 'font-family': 'fontFamily',
7145 fontsize: 'fontSize',
7146 'font-size': 'fontSize',
7147 fontsizeadjust: 'fontSizeAdjust',
7148 'font-size-adjust': 'fontSizeAdjust',
7149 fontstretch: 'fontStretch',
7150 'font-stretch': 'fontStretch',
7151 fontstyle: 'fontStyle',
7152 'font-style': 'fontStyle',
7153 fontvariant: 'fontVariant',
7154 'font-variant': 'fontVariant',
7155 fontweight: 'fontWeight',
7156 'font-weight': 'fontWeight',
7157 format: 'format',
7158 from: 'from',
7159 fx: 'fx',
7160 fy: 'fy',
7161 g1: 'g1',
7162 g2: 'g2',
7163 glyphname: 'glyphName',
7164 'glyph-name': 'glyphName',
7165 glyphorientationhorizontal: 'glyphOrientationHorizontal',
7166 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
7167 glyphorientationvertical: 'glyphOrientationVertical',
7168 'glyph-orientation-vertical': 'glyphOrientationVertical',
7169 glyphref: 'glyphRef',
7170 gradienttransform: 'gradientTransform',
7171 gradientunits: 'gradientUnits',
7172 hanging: 'hanging',
7173 horizadvx: 'horizAdvX',
7174 'horiz-adv-x': 'horizAdvX',
7175 horizoriginx: 'horizOriginX',
7176 'horiz-origin-x': 'horizOriginX',
7177 ideographic: 'ideographic',
7178 imagerendering: 'imageRendering',
7179 'image-rendering': 'imageRendering',
7180 in2: 'in2',
7181 in: 'in',
7182 inlist: 'inlist',
7183 intercept: 'intercept',
7184 k1: 'k1',
7185 k2: 'k2',
7186 k3: 'k3',
7187 k4: 'k4',
7188 k: 'k',
7189 kernelmatrix: 'kernelMatrix',
7190 kernelunitlength: 'kernelUnitLength',
7191 kerning: 'kerning',
7192 keypoints: 'keyPoints',
7193 keysplines: 'keySplines',
7194 keytimes: 'keyTimes',
7195 lengthadjust: 'lengthAdjust',
7196 letterspacing: 'letterSpacing',
7197 'letter-spacing': 'letterSpacing',
7198 lightingcolor: 'lightingColor',
7199 'lighting-color': 'lightingColor',
7200 limitingconeangle: 'limitingConeAngle',
7201 local: 'local',
7202 markerend: 'markerEnd',
7203 'marker-end': 'markerEnd',
7204 markerheight: 'markerHeight',
7205 markermid: 'markerMid',
7206 'marker-mid': 'markerMid',
7207 markerstart: 'markerStart',
7208 'marker-start': 'markerStart',
7209 markerunits: 'markerUnits',
7210 markerwidth: 'markerWidth',
7211 mask: 'mask',
7212 maskcontentunits: 'maskContentUnits',
7213 maskunits: 'maskUnits',
7214 mathematical: 'mathematical',
7215 mode: 'mode',
7216 numoctaves: 'numOctaves',
7217 offset: 'offset',
7218 opacity: 'opacity',
7219 operator: 'operator',
7220 order: 'order',
7221 orient: 'orient',
7222 orientation: 'orientation',
7223 origin: 'origin',
7224 overflow: 'overflow',
7225 overlineposition: 'overlinePosition',
7226 'overline-position': 'overlinePosition',
7227 overlinethickness: 'overlineThickness',
7228 'overline-thickness': 'overlineThickness',
7229 paintorder: 'paintOrder',
7230 'paint-order': 'paintOrder',
7231 panose1: 'panose1',
7232 'panose-1': 'panose1',
7233 pathlength: 'pathLength',
7234 patterncontentunits: 'patternContentUnits',
7235 patterntransform: 'patternTransform',
7236 patternunits: 'patternUnits',
7237 pointerevents: 'pointerEvents',
7238 'pointer-events': 'pointerEvents',
7239 points: 'points',
7240 pointsatx: 'pointsAtX',
7241 pointsaty: 'pointsAtY',
7242 pointsatz: 'pointsAtZ',
7243 prefix: 'prefix',
7244 preservealpha: 'preserveAlpha',
7245 preserveaspectratio: 'preserveAspectRatio',
7246 primitiveunits: 'primitiveUnits',
7247 property: 'property',
7248 r: 'r',
7249 radius: 'radius',
7250 refx: 'refX',
7251 refy: 'refY',
7252 renderingintent: 'renderingIntent',
7253 'rendering-intent': 'renderingIntent',
7254 repeatcount: 'repeatCount',
7255 repeatdur: 'repeatDur',
7256 requiredextensions: 'requiredExtensions',
7257 requiredfeatures: 'requiredFeatures',
7258 resource: 'resource',
7259 restart: 'restart',
7260 result: 'result',
7261 results: 'results',
7262 rotate: 'rotate',
7263 rx: 'rx',
7264 ry: 'ry',
7265 scale: 'scale',
7266 security: 'security',
7267 seed: 'seed',
7268 shaperendering: 'shapeRendering',
7269 'shape-rendering': 'shapeRendering',
7270 slope: 'slope',
7271 spacing: 'spacing',
7272 specularconstant: 'specularConstant',
7273 specularexponent: 'specularExponent',
7274 speed: 'speed',
7275 spreadmethod: 'spreadMethod',
7276 startoffset: 'startOffset',
7277 stddeviation: 'stdDeviation',
7278 stemh: 'stemh',
7279 stemv: 'stemv',
7280 stitchtiles: 'stitchTiles',
7281 stopcolor: 'stopColor',
7282 'stop-color': 'stopColor',
7283 stopopacity: 'stopOpacity',
7284 'stop-opacity': 'stopOpacity',
7285 strikethroughposition: 'strikethroughPosition',
7286 'strikethrough-position': 'strikethroughPosition',
7287 strikethroughthickness: 'strikethroughThickness',
7288 'strikethrough-thickness': 'strikethroughThickness',
7289 string: 'string',
7290 stroke: 'stroke',
7291 strokedasharray: 'strokeDasharray',
7292 'stroke-dasharray': 'strokeDasharray',
7293 strokedashoffset: 'strokeDashoffset',
7294 'stroke-dashoffset': 'strokeDashoffset',
7295 strokelinecap: 'strokeLinecap',
7296 'stroke-linecap': 'strokeLinecap',
7297 strokelinejoin: 'strokeLinejoin',
7298 'stroke-linejoin': 'strokeLinejoin',
7299 strokemiterlimit: 'strokeMiterlimit',
7300 'stroke-miterlimit': 'strokeMiterlimit',
7301 strokewidth: 'strokeWidth',
7302 'stroke-width': 'strokeWidth',
7303 strokeopacity: 'strokeOpacity',
7304 'stroke-opacity': 'strokeOpacity',
7305 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7306 suppresshydrationwarning: 'suppressHydrationWarning',
7307 surfacescale: 'surfaceScale',
7308 systemlanguage: 'systemLanguage',
7309 tablevalues: 'tableValues',
7310 targetx: 'targetX',
7311 targety: 'targetY',
7312 textanchor: 'textAnchor',
7313 'text-anchor': 'textAnchor',
7314 textdecoration: 'textDecoration',
7315 'text-decoration': 'textDecoration',
7316 textlength: 'textLength',
7317 textrendering: 'textRendering',
7318 'text-rendering': 'textRendering',
7319 to: 'to',
7320 transform: 'transform',
7321 typeof: 'typeof',
7322 u1: 'u1',
7323 u2: 'u2',
7324 underlineposition: 'underlinePosition',
7325 'underline-position': 'underlinePosition',
7326 underlinethickness: 'underlineThickness',
7327 'underline-thickness': 'underlineThickness',
7328 unicode: 'unicode',
7329 unicodebidi: 'unicodeBidi',
7330 'unicode-bidi': 'unicodeBidi',
7331 unicoderange: 'unicodeRange',
7332 'unicode-range': 'unicodeRange',
7333 unitsperem: 'unitsPerEm',
7334 'units-per-em': 'unitsPerEm',
7335 unselectable: 'unselectable',
7336 valphabetic: 'vAlphabetic',
7337 'v-alphabetic': 'vAlphabetic',
7338 values: 'values',
7339 vectoreffect: 'vectorEffect',
7340 'vector-effect': 'vectorEffect',
7341 version: 'version',
7342 vertadvy: 'vertAdvY',
7343 'vert-adv-y': 'vertAdvY',
7344 vertoriginx: 'vertOriginX',
7345 'vert-origin-x': 'vertOriginX',
7346 vertoriginy: 'vertOriginY',
7347 'vert-origin-y': 'vertOriginY',
7348 vhanging: 'vHanging',
7349 'v-hanging': 'vHanging',
7350 videographic: 'vIdeographic',
7351 'v-ideographic': 'vIdeographic',
7352 viewbox: 'viewBox',
7353 viewtarget: 'viewTarget',
7354 visibility: 'visibility',
7355 vmathematical: 'vMathematical',
7356 'v-mathematical': 'vMathematical',
7357 vocab: 'vocab',
7358 widths: 'widths',
7359 wordspacing: 'wordSpacing',
7360 'word-spacing': 'wordSpacing',
7361 writingmode: 'writingMode',
7362 'writing-mode': 'writingMode',
7363 x1: 'x1',
7364 x2: 'x2',
7365 x: 'x',
7366 xchannelselector: 'xChannelSelector',
7367 xheight: 'xHeight',
7368 'x-height': 'xHeight',
7369 xlinkactuate: 'xlinkActuate',
7370 'xlink:actuate': 'xlinkActuate',
7371 xlinkarcrole: 'xlinkArcrole',
7372 'xlink:arcrole': 'xlinkArcrole',
7373 xlinkhref: 'xlinkHref',
7374 'xlink:href': 'xlinkHref',
7375 xlinkrole: 'xlinkRole',
7376 'xlink:role': 'xlinkRole',
7377 xlinkshow: 'xlinkShow',
7378 'xlink:show': 'xlinkShow',
7379 xlinktitle: 'xlinkTitle',
7380 'xlink:title': 'xlinkTitle',
7381 xlinktype: 'xlinkType',
7382 'xlink:type': 'xlinkType',
7383 xmlbase: 'xmlBase',
7384 'xml:base': 'xmlBase',
7385 xmllang: 'xmlLang',
7386 'xml:lang': 'xmlLang',
7387 xmlns: 'xmlns',
7388 'xml:space': 'xmlSpace',
7389 xmlnsxlink: 'xmlnsXlink',
7390 'xmlns:xlink': 'xmlnsXlink',
7391 xmlspace: 'xmlSpace',
7392 y1: 'y1',
7393 y2: 'y2',
7394 y: 'y',
7395 ychannelselector: 'yChannelSelector',
7396 z: 'z',
7397 zoomandpan: 'zoomAndPan'
7398};
7399
7400var ariaProperties = {
7401 'aria-current': 0,
7402 // state
7403 'aria-details': 0,
7404 'aria-disabled': 0,
7405 // state
7406 'aria-hidden': 0,
7407 // state
7408 'aria-invalid': 0,
7409 // state
7410 'aria-keyshortcuts': 0,
7411 'aria-label': 0,
7412 'aria-roledescription': 0,
7413 // Widget Attributes
7414 'aria-autocomplete': 0,
7415 'aria-checked': 0,
7416 'aria-expanded': 0,
7417 'aria-haspopup': 0,
7418 'aria-level': 0,
7419 'aria-modal': 0,
7420 'aria-multiline': 0,
7421 'aria-multiselectable': 0,
7422 'aria-orientation': 0,
7423 'aria-placeholder': 0,
7424 'aria-pressed': 0,
7425 'aria-readonly': 0,
7426 'aria-required': 0,
7427 'aria-selected': 0,
7428 'aria-sort': 0,
7429 'aria-valuemax': 0,
7430 'aria-valuemin': 0,
7431 'aria-valuenow': 0,
7432 'aria-valuetext': 0,
7433 // Live Region Attributes
7434 'aria-atomic': 0,
7435 'aria-busy': 0,
7436 'aria-live': 0,
7437 'aria-relevant': 0,
7438 // Drag-and-Drop Attributes
7439 'aria-dropeffect': 0,
7440 'aria-grabbed': 0,
7441 // Relationship Attributes
7442 'aria-activedescendant': 0,
7443 'aria-colcount': 0,
7444 'aria-colindex': 0,
7445 'aria-colspan': 0,
7446 'aria-controls': 0,
7447 'aria-describedby': 0,
7448 'aria-errormessage': 0,
7449 'aria-flowto': 0,
7450 'aria-labelledby': 0,
7451 'aria-owns': 0,
7452 'aria-posinset': 0,
7453 'aria-rowcount': 0,
7454 'aria-rowindex': 0,
7455 'aria-rowspan': 0,
7456 'aria-setsize': 0
7457};
7458
7459var warnedProperties = {};
7460var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7461var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7462var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
7463
7464function validateProperty(tagName, name) {
7465 if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
7466 return true;
7467 }
7468
7469 if (rARIACamel.test(name)) {
7470 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7471 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7472 // DOM properties, then it is an invalid aria-* attribute.
7473
7474 if (correctName == null) {
7475 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7476 warnedProperties[name] = true;
7477 return true;
7478 } // aria-* attributes should be lowercase; suggest the lowercase version.
7479
7480
7481 if (name !== correctName) {
7482 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7483 warnedProperties[name] = true;
7484 return true;
7485 }
7486 }
7487
7488 if (rARIA.test(name)) {
7489 var lowerCasedName = name.toLowerCase();
7490 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7491 // DOM properties, then it is an invalid aria-* attribute.
7492
7493 if (standardName == null) {
7494 warnedProperties[name] = true;
7495 return false;
7496 } // aria-* attributes should be lowercase; suggest the lowercase version.
7497
7498
7499 if (name !== standardName) {
7500 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7501 warnedProperties[name] = true;
7502 return true;
7503 }
7504 }
7505
7506 return true;
7507}
7508
7509function warnInvalidARIAProps(type, props) {
7510 var invalidProps = [];
7511
7512 for (var key in props) {
7513 var isValid = validateProperty(type, key);
7514
7515 if (!isValid) {
7516 invalidProps.push(key);
7517 }
7518 }
7519
7520 var unknownPropString = invalidProps.map(function (prop) {
7521 return '`' + prop + '`';
7522 }).join(', ');
7523
7524 if (invalidProps.length === 1) {
7525 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7526 } else if (invalidProps.length > 1) {
7527 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7528 }
7529}
7530
7531function validateProperties(type, props) {
7532 if (isCustomComponent(type, props)) {
7533 return;
7534 }
7535
7536 warnInvalidARIAProps(type, props);
7537}
7538
7539var didWarnValueNull = false;
7540function validateProperties$1(type, props) {
7541 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7542 return;
7543 }
7544
7545 if (props != null && props.value === null && !didWarnValueNull) {
7546 didWarnValueNull = true;
7547
7548 if (type === 'select' && props.multiple) {
7549 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);
7550 } else {
7551 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);
7552 }
7553 }
7554}
7555
7556var validateProperty$1 = function () {};
7557
7558{
7559 var warnedProperties$1 = {};
7560 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7561 var EVENT_NAME_REGEX = /^on./;
7562 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7563 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7564 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7565
7566 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7567 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7568 return true;
7569 }
7570
7571 var lowerCasedName = name.toLowerCase();
7572
7573 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7574 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.');
7575 warnedProperties$1[name] = true;
7576 return true;
7577 } // We can't rely on the event system being injected on the server.
7578
7579
7580 if (canUseEventSystem) {
7581 if (registrationNameModules.hasOwnProperty(name)) {
7582 return true;
7583 }
7584
7585 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7586
7587 if (registrationName != null) {
7588 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7589 warnedProperties$1[name] = true;
7590 return true;
7591 }
7592
7593 if (EVENT_NAME_REGEX.test(name)) {
7594 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7595 warnedProperties$1[name] = true;
7596 return true;
7597 }
7598 } else if (EVENT_NAME_REGEX.test(name)) {
7599 // If no event plugins have been injected, we are in a server environment.
7600 // So we can't tell if the event name is correct for sure, but we can filter
7601 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7602 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7603 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7604 }
7605
7606 warnedProperties$1[name] = true;
7607 return true;
7608 } // Let the ARIA attribute hook validate ARIA attributes
7609
7610
7611 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7612 return true;
7613 }
7614
7615 if (lowerCasedName === 'innerhtml') {
7616 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7617 warnedProperties$1[name] = true;
7618 return true;
7619 }
7620
7621 if (lowerCasedName === 'aria') {
7622 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7623 warnedProperties$1[name] = true;
7624 return true;
7625 }
7626
7627 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7628 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7629 warnedProperties$1[name] = true;
7630 return true;
7631 }
7632
7633 if (typeof value === 'number' && isNaN(value)) {
7634 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7635 warnedProperties$1[name] = true;
7636 return true;
7637 }
7638
7639 var propertyInfo = getPropertyInfo(name);
7640 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
7641
7642 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7643 var standardName = possibleStandardNames[lowerCasedName];
7644
7645 if (standardName !== name) {
7646 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7647 warnedProperties$1[name] = true;
7648 return true;
7649 }
7650 } else if (!isReserved && name !== lowerCasedName) {
7651 // Unknown attributes should have lowercase casing since that's how they
7652 // will be cased anyway with server rendering.
7653 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);
7654 warnedProperties$1[name] = true;
7655 return true;
7656 }
7657
7658 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7659 if (value) {
7660 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);
7661 } else {
7662 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);
7663 }
7664
7665 warnedProperties$1[name] = true;
7666 return true;
7667 } // Now that we've validated casing, do not validate
7668 // data types for reserved props
7669
7670
7671 if (isReserved) {
7672 return true;
7673 } // Warn when a known attribute is a bad type
7674
7675
7676 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7677 warnedProperties$1[name] = true;
7678 return false;
7679 } // Warn when passing the strings 'false' or 'true' into a boolean prop
7680
7681
7682 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7683 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);
7684 warnedProperties$1[name] = true;
7685 return true;
7686 }
7687
7688 return true;
7689 };
7690}
7691
7692var warnUnknownProperties = function (type, props, canUseEventSystem) {
7693 var unknownProps = [];
7694
7695 for (var key in props) {
7696 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7697
7698 if (!isValid) {
7699 unknownProps.push(key);
7700 }
7701 }
7702
7703 var unknownPropString = unknownProps.map(function (prop) {
7704 return '`' + prop + '`';
7705 }).join(', ');
7706
7707 if (unknownProps.length === 1) {
7708 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);
7709 } else if (unknownProps.length > 1) {
7710 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);
7711 }
7712};
7713
7714function validateProperties$2(type, props, canUseEventSystem) {
7715 if (isCustomComponent(type, props)) {
7716 return;
7717 }
7718
7719 warnUnknownProperties(type, props, canUseEventSystem);
7720}
7721
7722// TODO: direct imports like some-package/src/* are bad. Fix me.
7723var didWarnInvalidHydration = false;
7724var didWarnShadyDOM = false;
7725var didWarnScriptTags = false;
7726var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7727var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7728var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7729var AUTOFOCUS = 'autoFocus';
7730var CHILDREN = 'children';
7731var STYLE$1 = 'style';
7732var HTML = '__html';
7733var LISTENERS = 'listeners';
7734var HTML_NAMESPACE = Namespaces.html;
7735var warnedUnknownTags;
7736var suppressHydrationWarning;
7737var validatePropertiesInDevelopment;
7738var warnForTextDifference;
7739var warnForPropDifference;
7740var warnForExtraAttributes;
7741var warnForInvalidEventListener;
7742var canDiffStyleForHydrationWarning;
7743var normalizeMarkupForTextOrAttribute;
7744var normalizeHTML;
7745
7746{
7747 warnedUnknownTags = {
7748 // Chrome is the only major browser not shipping <time>. But as of July
7749 // 2017 it intends to ship it due to widespread usage. We intentionally
7750 // *don't* warn for <time> even if it's unrecognized by Chrome because
7751 // it soon will be, and many apps have been using it anyway.
7752 time: true,
7753 // There are working polyfills for <dialog>. Let people use it.
7754 dialog: true,
7755 // Electron ships a custom <webview> tag to display external web content in
7756 // an isolated frame and process.
7757 // This tag is not present in non Electron environments such as JSDom which
7758 // is often used for testing purposes.
7759 // @see https://electronjs.org/docs/api/webview-tag
7760 webview: true
7761 };
7762
7763 validatePropertiesInDevelopment = function (type, props) {
7764 validateProperties(type, props);
7765 validateProperties$1(type, props);
7766 validateProperties$2(type, props,
7767 /* canUseEventSystem */
7768 true);
7769 }; // IE 11 parses & normalizes the style attribute as opposed to other
7770 // browsers. It adds spaces and sorts the properties in some
7771 // non-alphabetical order. Handling that would require sorting CSS
7772 // properties in the client & server versions or applying
7773 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7774 // normalized. Since it only affects IE, we're skipping style warnings
7775 // in that browser completely in favor of doing all that work.
7776 // See https://github.com/facebook/react/issues/11807
7777
7778
7779 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
7780 // It also can turn \u0000 into \uFFFD inside attributes.
7781 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7782 // If we have a mismatch, it might be caused by that.
7783 // We will still patch up in this case but not fire the warning.
7784
7785 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7786 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7787
7788 normalizeMarkupForTextOrAttribute = function (markup) {
7789 var markupString = typeof markup === 'string' ? markup : '' + markup;
7790 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7791 };
7792
7793 warnForTextDifference = function (serverText, clientText) {
7794 if (didWarnInvalidHydration) {
7795 return;
7796 }
7797
7798 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7799 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7800
7801 if (normalizedServerText === normalizedClientText) {
7802 return;
7803 }
7804
7805 didWarnInvalidHydration = true;
7806 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7807 };
7808
7809 warnForPropDifference = function (propName, serverValue, clientValue) {
7810 if (didWarnInvalidHydration) {
7811 return;
7812 }
7813
7814 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7815 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7816
7817 if (normalizedServerValue === normalizedClientValue) {
7818 return;
7819 }
7820
7821 didWarnInvalidHydration = true;
7822 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7823 };
7824
7825 warnForExtraAttributes = function (attributeNames) {
7826 if (didWarnInvalidHydration) {
7827 return;
7828 }
7829
7830 didWarnInvalidHydration = true;
7831 var names = [];
7832 attributeNames.forEach(function (name) {
7833 names.push(name);
7834 });
7835 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7836 };
7837
7838 warnForInvalidEventListener = function (registrationName, listener) {
7839 if (listener === false) {
7840 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);
7841 } else {
7842 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7843 }
7844 }; // Parse the HTML and read it back to normalize the HTML string so that it
7845 // can be used for comparison.
7846
7847
7848 normalizeHTML = function (parent, html) {
7849 // We could have created a separate document here to avoid
7850 // re-initializing custom elements if they exist. But this breaks
7851 // how <noscript> is being handled. So we use the same document.
7852 // See the discussion in https://github.com/facebook/react/pull/11157.
7853 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7854 testElement.innerHTML = html;
7855 return testElement.innerHTML;
7856 };
7857}
7858
7859function ensureListeningTo(rootContainerElement, registrationName) {
7860 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7861 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7862 listenTo(registrationName, doc);
7863}
7864
7865function getOwnerDocumentFromRootContainer(rootContainerElement) {
7866 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7867}
7868
7869function noop() {}
7870
7871function trapClickOnNonInteractiveElement(node) {
7872 // Mobile Safari does not fire properly bubble click events on
7873 // non-interactive elements, which means delegated click listeners do not
7874 // fire. The workaround for this bug involves attaching an empty click
7875 // listener on the target node.
7876 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7877 // Just set it using the onclick property so that we don't have to manage any
7878 // bookkeeping for it. Not sure if we need to clear it when the listener is
7879 // removed.
7880 // TODO: Only do this for the relevant Safaris maybe?
7881 node.onclick = noop;
7882}
7883
7884function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7885 for (var propKey in nextProps) {
7886 if (!nextProps.hasOwnProperty(propKey)) {
7887 continue;
7888 }
7889
7890 var nextProp = nextProps[propKey];
7891
7892 if (propKey === STYLE$1) {
7893 {
7894 if (nextProp) {
7895 // Freeze the next style object so that we can assume it won't be
7896 // mutated. We have already warned for this in the past.
7897 Object.freeze(nextProp);
7898 }
7899 } // Relies on `updateStylesByID` not mutating `styleUpdates`.
7900
7901
7902 setValueForStyles(domElement, nextProp);
7903 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7904 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7905
7906 if (nextHtml != null) {
7907 setInnerHTML(domElement, nextHtml);
7908 }
7909 } else if (propKey === CHILDREN) {
7910 if (typeof nextProp === 'string') {
7911 // Avoid setting initial textContent when the text is empty. In IE11 setting
7912 // textContent on a <textarea> will cause the placeholder to not
7913 // show within the <textarea> until it has been focused and blurred again.
7914 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7915 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7916
7917 if (canSetTextContent) {
7918 setTextContent(domElement, nextProp);
7919 }
7920 } else if (typeof nextProp === 'number') {
7921 setTextContent(domElement, '' + nextProp);
7922 }
7923 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
7924 } else if (propKey === AUTOFOCUS) {// We polyfill it separately on the client during commit.
7925 // We could have excluded it in the property list instead of
7926 // adding a special case here, but then it wouldn't be emitted
7927 // on server rendering (but we *do* want to emit it in SSR).
7928 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7929 if (nextProp != null) {
7930 if (true && typeof nextProp !== 'function') {
7931 warnForInvalidEventListener(propKey, nextProp);
7932 }
7933
7934 ensureListeningTo(rootContainerElement, propKey);
7935 }
7936 } else if (nextProp != null) {
7937 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7938 }
7939 }
7940}
7941
7942function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7943 // TODO: Handle wasCustomComponentTag
7944 for (var i = 0; i < updatePayload.length; i += 2) {
7945 var propKey = updatePayload[i];
7946 var propValue = updatePayload[i + 1];
7947
7948 if (propKey === STYLE$1) {
7949 setValueForStyles(domElement, propValue);
7950 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7951 setInnerHTML(domElement, propValue);
7952 } else if (propKey === CHILDREN) {
7953 setTextContent(domElement, propValue);
7954 } else {
7955 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7956 }
7957 }
7958}
7959
7960function createElement(type, props, rootContainerElement, parentNamespace) {
7961 var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
7962 // tags get no namespace.
7963
7964 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7965 var domElement;
7966 var namespaceURI = parentNamespace;
7967
7968 if (namespaceURI === HTML_NAMESPACE) {
7969 namespaceURI = getIntrinsicNamespace(type);
7970 }
7971
7972 if (namespaceURI === HTML_NAMESPACE) {
7973 {
7974 isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
7975 // allow <SVG> or <mATH>.
7976
7977 !(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;
7978 }
7979
7980 if (type === 'script') {
7981 // Create the script via .innerHTML so its "parser-inserted" flag is
7982 // set to true and it does not execute
7983 var div = ownerDocument.createElement('div');
7984
7985 {
7986 if (enableTrustedTypesIntegration && !didWarnScriptTags) {
7987 warning$1(false, 'Encountered a script tag while rendering React component. ' + 'Scripts inside React components are never executed when rendering ' + 'on the client. Consider using template tag instead ' + '(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).');
7988 didWarnScriptTags = true;
7989 }
7990 }
7991
7992 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7993 // This is guaranteed to yield a script element.
7994
7995 var firstChild = div.firstChild;
7996 domElement = div.removeChild(firstChild);
7997 } else if (typeof props.is === 'string') {
7998 // $FlowIssue `createElement` should be updated for Web Components
7999 domElement = ownerDocument.createElement(type, {
8000 is: props.is
8001 });
8002 } else {
8003 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
8004 // See discussion in https://github.com/facebook/react/pull/6896
8005 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
8006 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
8007 // attributes on `select`s needs to be added before `option`s are inserted.
8008 // This prevents:
8009 // - a bug where the `select` does not scroll to the correct option because singular
8010 // `select` elements automatically pick the first item #13222
8011 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
8012 // See https://github.com/facebook/react/issues/13222
8013 // and https://github.com/facebook/react/issues/14239
8014
8015 if (type === 'select') {
8016 var node = domElement;
8017
8018 if (props.multiple) {
8019 node.multiple = true;
8020 } else if (props.size) {
8021 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
8022 // it is possible that no option is selected.
8023 //
8024 // This is only necessary when a select in "single selection mode".
8025 node.size = props.size;
8026 }
8027 }
8028 }
8029 } else {
8030 domElement = ownerDocument.createElementNS(namespaceURI, type);
8031 }
8032
8033 {
8034 if (namespaceURI === HTML_NAMESPACE) {
8035 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
8036 warnedUnknownTags[type] = true;
8037 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);
8038 }
8039 }
8040 }
8041
8042 return domElement;
8043}
8044function createTextNode(text, rootContainerElement) {
8045 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
8046}
8047function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
8048 var isCustomComponentTag = isCustomComponent(tag, rawProps);
8049
8050 {
8051 validatePropertiesInDevelopment(tag, rawProps);
8052
8053 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8054 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8055 didWarnShadyDOM = true;
8056 }
8057 } // TODO: Make sure that we check isMounted before firing any of these events.
8058
8059
8060 var props;
8061
8062 switch (tag) {
8063 case 'iframe':
8064 case 'object':
8065 case 'embed':
8066 trapBubbledEvent(TOP_LOAD, domElement);
8067 props = rawProps;
8068 break;
8069
8070 case 'video':
8071 case 'audio':
8072 // Create listener for each media event
8073 for (var i = 0; i < mediaEventTypes.length; i++) {
8074 trapBubbledEvent(mediaEventTypes[i], domElement);
8075 }
8076
8077 props = rawProps;
8078 break;
8079
8080 case 'source':
8081 trapBubbledEvent(TOP_ERROR, domElement);
8082 props = rawProps;
8083 break;
8084
8085 case 'img':
8086 case 'image':
8087 case 'link':
8088 trapBubbledEvent(TOP_ERROR, domElement);
8089 trapBubbledEvent(TOP_LOAD, domElement);
8090 props = rawProps;
8091 break;
8092
8093 case 'form':
8094 trapBubbledEvent(TOP_RESET, domElement);
8095 trapBubbledEvent(TOP_SUBMIT, domElement);
8096 props = rawProps;
8097 break;
8098
8099 case 'details':
8100 trapBubbledEvent(TOP_TOGGLE, domElement);
8101 props = rawProps;
8102 break;
8103
8104 case 'input':
8105 initWrapperState(domElement, rawProps);
8106 props = getHostProps(domElement, rawProps);
8107 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8108 // to onChange. Even if there is no listener.
8109
8110 ensureListeningTo(rootContainerElement, 'onChange');
8111 break;
8112
8113 case 'option':
8114 validateProps(domElement, rawProps);
8115 props = getHostProps$1(domElement, rawProps);
8116 break;
8117
8118 case 'select':
8119 initWrapperState$1(domElement, rawProps);
8120 props = getHostProps$2(domElement, rawProps);
8121 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8122 // to onChange. Even if there is no listener.
8123
8124 ensureListeningTo(rootContainerElement, 'onChange');
8125 break;
8126
8127 case 'textarea':
8128 initWrapperState$2(domElement, rawProps);
8129 props = getHostProps$3(domElement, rawProps);
8130 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8131 // to onChange. Even if there is no listener.
8132
8133 ensureListeningTo(rootContainerElement, 'onChange');
8134 break;
8135
8136 default:
8137 props = rawProps;
8138 }
8139
8140 assertValidProps(tag, props);
8141 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
8142
8143 switch (tag) {
8144 case 'input':
8145 // TODO: Make sure we check if this is still unmounted or do any clean
8146 // up necessary since we never stop tracking anymore.
8147 track(domElement);
8148 postMountWrapper(domElement, rawProps, false);
8149 break;
8150
8151 case 'textarea':
8152 // TODO: Make sure we check if this is still unmounted or do any clean
8153 // up necessary since we never stop tracking anymore.
8154 track(domElement);
8155 postMountWrapper$3(domElement, rawProps);
8156 break;
8157
8158 case 'option':
8159 postMountWrapper$1(domElement, rawProps);
8160 break;
8161
8162 case 'select':
8163 postMountWrapper$2(domElement, rawProps);
8164 break;
8165
8166 default:
8167 if (typeof props.onClick === 'function') {
8168 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8169 trapClickOnNonInteractiveElement(domElement);
8170 }
8171
8172 break;
8173 }
8174} // Calculate the diff between the two objects.
8175
8176function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
8177 {
8178 validatePropertiesInDevelopment(tag, nextRawProps);
8179 }
8180
8181 var updatePayload = null;
8182 var lastProps;
8183 var nextProps;
8184
8185 switch (tag) {
8186 case 'input':
8187 lastProps = getHostProps(domElement, lastRawProps);
8188 nextProps = getHostProps(domElement, nextRawProps);
8189 updatePayload = [];
8190 break;
8191
8192 case 'option':
8193 lastProps = getHostProps$1(domElement, lastRawProps);
8194 nextProps = getHostProps$1(domElement, nextRawProps);
8195 updatePayload = [];
8196 break;
8197
8198 case 'select':
8199 lastProps = getHostProps$2(domElement, lastRawProps);
8200 nextProps = getHostProps$2(domElement, nextRawProps);
8201 updatePayload = [];
8202 break;
8203
8204 case 'textarea':
8205 lastProps = getHostProps$3(domElement, lastRawProps);
8206 nextProps = getHostProps$3(domElement, nextRawProps);
8207 updatePayload = [];
8208 break;
8209
8210 default:
8211 lastProps = lastRawProps;
8212 nextProps = nextRawProps;
8213
8214 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
8215 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8216 trapClickOnNonInteractiveElement(domElement);
8217 }
8218
8219 break;
8220 }
8221
8222 assertValidProps(tag, nextProps);
8223 var propKey;
8224 var styleName;
8225 var styleUpdates = null;
8226
8227 for (propKey in lastProps) {
8228 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
8229 continue;
8230 }
8231
8232 if (propKey === STYLE$1) {
8233 var lastStyle = lastProps[propKey];
8234
8235 for (styleName in lastStyle) {
8236 if (lastStyle.hasOwnProperty(styleName)) {
8237 if (!styleUpdates) {
8238 styleUpdates = {};
8239 }
8240
8241 styleUpdates[styleName] = '';
8242 }
8243 }
8244 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {// Noop. This is handled by the clear text mechanism.
8245 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8246 } else if (propKey === AUTOFOCUS) {// Noop. It doesn't work on updates anyway.
8247 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8248 // This is a special case. If any listener updates we need to ensure
8249 // that the "current" fiber pointer gets updated so we need a commit
8250 // to update this element.
8251 if (!updatePayload) {
8252 updatePayload = [];
8253 }
8254 } else {
8255 // For all other deleted properties we add it to the queue. We use
8256 // the whitelist in the commit phase instead.
8257 (updatePayload = updatePayload || []).push(propKey, null);
8258 }
8259 }
8260
8261 for (propKey in nextProps) {
8262 var nextProp = nextProps[propKey];
8263 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
8264
8265 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
8266 continue;
8267 }
8268
8269 if (propKey === STYLE$1) {
8270 {
8271 if (nextProp) {
8272 // Freeze the next style object so that we can assume it won't be
8273 // mutated. We have already warned for this in the past.
8274 Object.freeze(nextProp);
8275 }
8276 }
8277
8278 if (lastProp) {
8279 // Unset styles on `lastProp` but not on `nextProp`.
8280 for (styleName in lastProp) {
8281 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
8282 if (!styleUpdates) {
8283 styleUpdates = {};
8284 }
8285
8286 styleUpdates[styleName] = '';
8287 }
8288 } // Update styles that changed since `lastProp`.
8289
8290
8291 for (styleName in nextProp) {
8292 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8293 if (!styleUpdates) {
8294 styleUpdates = {};
8295 }
8296
8297 styleUpdates[styleName] = nextProp[styleName];
8298 }
8299 }
8300 } else {
8301 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8302 if (!styleUpdates) {
8303 if (!updatePayload) {
8304 updatePayload = [];
8305 }
8306
8307 updatePayload.push(propKey, styleUpdates);
8308 }
8309
8310 styleUpdates = nextProp;
8311 }
8312 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8313 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8314 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8315
8316 if (nextHtml != null) {
8317 if (lastHtml !== nextHtml) {
8318 (updatePayload = updatePayload || []).push(propKey, toStringOrTrustedType(nextHtml));
8319 }
8320 } else {// TODO: It might be too late to clear this if we have children
8321 // inserted already.
8322 }
8323 } else if (propKey === CHILDREN) {
8324 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8325 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8326 }
8327 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8328 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8329 if (nextProp != null) {
8330 // We eagerly listen to this even though we haven't committed yet.
8331 if (true && typeof nextProp !== 'function') {
8332 warnForInvalidEventListener(propKey, nextProp);
8333 }
8334
8335 ensureListeningTo(rootContainerElement, propKey);
8336 }
8337
8338 if (!updatePayload && lastProp !== nextProp) {
8339 // This is a special case. If any listener updates we need to ensure
8340 // that the "current" props pointer gets updated so we need a commit
8341 // to update this element.
8342 updatePayload = [];
8343 }
8344 } else {
8345 // For any other property we always add it to the queue and then we
8346 // filter it out using the whitelist during the commit.
8347 (updatePayload = updatePayload || []).push(propKey, nextProp);
8348 }
8349 }
8350
8351 if (styleUpdates) {
8352 {
8353 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8354 }
8355
8356 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8357 }
8358
8359 return updatePayload;
8360} // Apply the diff.
8361
8362function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8363 // Update checked *before* name.
8364 // In the middle of an update, it is possible to have multiple checked.
8365 // When a checked radio tries to change name, browser makes another radio's checked false.
8366 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8367 updateChecked(domElement, nextRawProps);
8368 }
8369
8370 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8371 var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
8372
8373 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
8374 // changed.
8375
8376 switch (tag) {
8377 case 'input':
8378 // Update the wrapper around inputs *after* updating props. This has to
8379 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8380 // raise warnings and prevent the new value from being assigned.
8381 updateWrapper(domElement, nextRawProps);
8382 break;
8383
8384 case 'textarea':
8385 updateWrapper$1(domElement, nextRawProps);
8386 break;
8387
8388 case 'select':
8389 // <select> value update needs to occur after <option> children
8390 // reconciliation
8391 postUpdateWrapper(domElement, nextRawProps);
8392 break;
8393 }
8394}
8395
8396function getPossibleStandardName(propName) {
8397 {
8398 var lowerCasedName = propName.toLowerCase();
8399
8400 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8401 return null;
8402 }
8403
8404 return possibleStandardNames[lowerCasedName] || null;
8405 }
8406
8407 return null;
8408}
8409
8410function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8411 var isCustomComponentTag;
8412 var extraAttributeNames;
8413
8414 {
8415 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8416 isCustomComponentTag = isCustomComponent(tag, rawProps);
8417 validatePropertiesInDevelopment(tag, rawProps);
8418
8419 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8420 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8421 didWarnShadyDOM = true;
8422 }
8423 } // TODO: Make sure that we check isMounted before firing any of these events.
8424
8425
8426 switch (tag) {
8427 case 'iframe':
8428 case 'object':
8429 case 'embed':
8430 trapBubbledEvent(TOP_LOAD, domElement);
8431 break;
8432
8433 case 'video':
8434 case 'audio':
8435 // Create listener for each media event
8436 for (var i = 0; i < mediaEventTypes.length; i++) {
8437 trapBubbledEvent(mediaEventTypes[i], domElement);
8438 }
8439
8440 break;
8441
8442 case 'source':
8443 trapBubbledEvent(TOP_ERROR, domElement);
8444 break;
8445
8446 case 'img':
8447 case 'image':
8448 case 'link':
8449 trapBubbledEvent(TOP_ERROR, domElement);
8450 trapBubbledEvent(TOP_LOAD, domElement);
8451 break;
8452
8453 case 'form':
8454 trapBubbledEvent(TOP_RESET, domElement);
8455 trapBubbledEvent(TOP_SUBMIT, domElement);
8456 break;
8457
8458 case 'details':
8459 trapBubbledEvent(TOP_TOGGLE, domElement);
8460 break;
8461
8462 case 'input':
8463 initWrapperState(domElement, rawProps);
8464 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8465 // to onChange. Even if there is no listener.
8466
8467 ensureListeningTo(rootContainerElement, 'onChange');
8468 break;
8469
8470 case 'option':
8471 validateProps(domElement, rawProps);
8472 break;
8473
8474 case 'select':
8475 initWrapperState$1(domElement, rawProps);
8476 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8477 // to onChange. Even if there is no listener.
8478
8479 ensureListeningTo(rootContainerElement, 'onChange');
8480 break;
8481
8482 case 'textarea':
8483 initWrapperState$2(domElement, rawProps);
8484 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8485 // to onChange. Even if there is no listener.
8486
8487 ensureListeningTo(rootContainerElement, 'onChange');
8488 break;
8489 }
8490
8491 assertValidProps(tag, rawProps);
8492
8493 {
8494 extraAttributeNames = new Set();
8495 var attributes = domElement.attributes;
8496
8497 for (var _i = 0; _i < attributes.length; _i++) {
8498 var name = attributes[_i].name.toLowerCase();
8499
8500 switch (name) {
8501 // Built-in SSR attribute is whitelisted
8502 case 'data-reactroot':
8503 break;
8504 // Controlled attributes are not validated
8505 // TODO: Only ignore them on controlled tags.
8506
8507 case 'value':
8508 break;
8509
8510 case 'checked':
8511 break;
8512
8513 case 'selected':
8514 break;
8515
8516 default:
8517 // Intentionally use the original name.
8518 // See discussion in https://github.com/facebook/react/pull/10676.
8519 extraAttributeNames.add(attributes[_i].name);
8520 }
8521 }
8522 }
8523
8524 var updatePayload = null;
8525
8526 for (var propKey in rawProps) {
8527 if (!rawProps.hasOwnProperty(propKey)) {
8528 continue;
8529 }
8530
8531 var nextProp = rawProps[propKey];
8532
8533 if (propKey === CHILDREN) {
8534 // For text content children we compare against textContent. This
8535 // might match additional HTML that is hidden when we read it using
8536 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8537 // satisfies our requirement. Our requirement is not to produce perfect
8538 // HTML and attributes. Ideally we should preserve structure but it's
8539 // ok not to if the visible content is still enough to indicate what
8540 // even listeners these nodes might be wired up to.
8541 // TODO: Warn if there is more than a single textNode as a child.
8542 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8543 if (typeof nextProp === 'string') {
8544 if (domElement.textContent !== nextProp) {
8545 if (true && !suppressHydrationWarning) {
8546 warnForTextDifference(domElement.textContent, nextProp);
8547 }
8548
8549 updatePayload = [CHILDREN, nextProp];
8550 }
8551 } else if (typeof nextProp === 'number') {
8552 if (domElement.textContent !== '' + nextProp) {
8553 if (true && !suppressHydrationWarning) {
8554 warnForTextDifference(domElement.textContent, nextProp);
8555 }
8556
8557 updatePayload = [CHILDREN, '' + nextProp];
8558 }
8559 }
8560 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8561 if (nextProp != null) {
8562 if (true && typeof nextProp !== 'function') {
8563 warnForInvalidEventListener(propKey, nextProp);
8564 }
8565
8566 ensureListeningTo(rootContainerElement, propKey);
8567 }
8568 } else if (true && // Convince Flow we've calculated it (it's DEV-only in this method.)
8569 typeof isCustomComponentTag === 'boolean') {
8570 // Validate that the properties correspond to their expected values.
8571 var serverValue = void 0;
8572 var propertyInfo = getPropertyInfo(propKey);
8573
8574 if (suppressHydrationWarning) {// Don't bother comparing. We're ignoring all these warnings.
8575 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 || // Controlled attributes are not validated
8576 // TODO: Only ignore them on controlled tags.
8577 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {// Noop
8578 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8579 var serverHTML = domElement.innerHTML;
8580 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8581 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8582
8583 if (expectedHTML !== serverHTML) {
8584 warnForPropDifference(propKey, serverHTML, expectedHTML);
8585 }
8586 } else if (propKey === STYLE$1) {
8587 // $FlowFixMe - Should be inferred as not undefined.
8588 extraAttributeNames.delete(propKey);
8589
8590 if (canDiffStyleForHydrationWarning) {
8591 var expectedStyle = createDangerousStringForStyles(nextProp);
8592 serverValue = domElement.getAttribute('style');
8593
8594 if (expectedStyle !== serverValue) {
8595 warnForPropDifference(propKey, serverValue, expectedStyle);
8596 }
8597 }
8598 } else if (isCustomComponentTag) {
8599 // $FlowFixMe - Should be inferred as not undefined.
8600 extraAttributeNames.delete(propKey.toLowerCase());
8601 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8602
8603 if (nextProp !== serverValue) {
8604 warnForPropDifference(propKey, serverValue, nextProp);
8605 }
8606 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8607 var isMismatchDueToBadCasing = false;
8608
8609 if (propertyInfo !== null) {
8610 // $FlowFixMe - Should be inferred as not undefined.
8611 extraAttributeNames.delete(propertyInfo.attributeName);
8612 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8613 } else {
8614 var ownNamespace = parentNamespace;
8615
8616 if (ownNamespace === HTML_NAMESPACE) {
8617 ownNamespace = getIntrinsicNamespace(tag);
8618 }
8619
8620 if (ownNamespace === HTML_NAMESPACE) {
8621 // $FlowFixMe - Should be inferred as not undefined.
8622 extraAttributeNames.delete(propKey.toLowerCase());
8623 } else {
8624 var standardName = getPossibleStandardName(propKey);
8625
8626 if (standardName !== null && standardName !== propKey) {
8627 // If an SVG prop is supplied with bad casing, it will
8628 // be successfully parsed from HTML, but will produce a mismatch
8629 // (and would be incorrectly rendered on the client).
8630 // However, we already warn about bad casing elsewhere.
8631 // So we'll skip the misleading extra mismatch warning in this case.
8632 isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
8633
8634 extraAttributeNames.delete(standardName);
8635 } // $FlowFixMe - Should be inferred as not undefined.
8636
8637
8638 extraAttributeNames.delete(propKey);
8639 }
8640
8641 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8642 }
8643
8644 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8645 warnForPropDifference(propKey, serverValue, nextProp);
8646 }
8647 }
8648 }
8649 }
8650
8651 {
8652 // $FlowFixMe - Should be inferred as not undefined.
8653 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8654 // $FlowFixMe - Should be inferred as not undefined.
8655 warnForExtraAttributes(extraAttributeNames);
8656 }
8657 }
8658
8659 switch (tag) {
8660 case 'input':
8661 // TODO: Make sure we check if this is still unmounted or do any clean
8662 // up necessary since we never stop tracking anymore.
8663 track(domElement);
8664 postMountWrapper(domElement, rawProps, true);
8665 break;
8666
8667 case 'textarea':
8668 // TODO: Make sure we check if this is still unmounted or do any clean
8669 // up necessary since we never stop tracking anymore.
8670 track(domElement);
8671 postMountWrapper$3(domElement, rawProps);
8672 break;
8673
8674 case 'select':
8675 case 'option':
8676 // For input and textarea we current always set the value property at
8677 // post mount to force it to diverge from attributes. However, for
8678 // option and select we don't quite do the same thing and select
8679 // is not resilient to the DOM state changing so we don't do that here.
8680 // TODO: Consider not doing this for input and textarea.
8681 break;
8682
8683 default:
8684 if (typeof rawProps.onClick === 'function') {
8685 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8686 trapClickOnNonInteractiveElement(domElement);
8687 }
8688
8689 break;
8690 }
8691
8692 return updatePayload;
8693}
8694function diffHydratedText(textNode, text) {
8695 var isDifferent = textNode.nodeValue !== text;
8696 return isDifferent;
8697}
8698function warnForUnmatchedText(textNode, text) {
8699 {
8700 warnForTextDifference(textNode.nodeValue, text);
8701 }
8702}
8703function warnForDeletedHydratableElement(parentNode, child) {
8704 {
8705 if (didWarnInvalidHydration) {
8706 return;
8707 }
8708
8709 didWarnInvalidHydration = true;
8710 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8711 }
8712}
8713function warnForDeletedHydratableText(parentNode, child) {
8714 {
8715 if (didWarnInvalidHydration) {
8716 return;
8717 }
8718
8719 didWarnInvalidHydration = true;
8720 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8721 }
8722}
8723function warnForInsertedHydratedElement(parentNode, tag, props) {
8724 {
8725 if (didWarnInvalidHydration) {
8726 return;
8727 }
8728
8729 didWarnInvalidHydration = true;
8730 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8731 }
8732}
8733function warnForInsertedHydratedText(parentNode, text) {
8734 {
8735 if (text === '') {
8736 // We expect to insert empty text nodes since they're not represented in
8737 // the HTML.
8738 // TODO: Remove this special case if we can just avoid inserting empty
8739 // text nodes.
8740 return;
8741 }
8742
8743 if (didWarnInvalidHydration) {
8744 return;
8745 }
8746
8747 didWarnInvalidHydration = true;
8748 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8749 }
8750}
8751function restoreControlledState$$1(domElement, tag, props) {
8752 switch (tag) {
8753 case 'input':
8754 restoreControlledState$1(domElement, props);
8755 return;
8756
8757 case 'textarea':
8758 restoreControlledState$3(domElement, props);
8759 return;
8760
8761 case 'select':
8762 restoreControlledState$2(domElement, props);
8763 return;
8764 }
8765}
8766function listenToEventResponderEventTypes(eventTypes, element) {
8767 if (enableFlareAPI) {
8768 // Get the listening Set for this element. We use this to track
8769 // what events we're listening to.
8770 var listeningSet = getListeningSetForElement(element); // Go through each target event type of the event responder
8771
8772 for (var i = 0, length = eventTypes.length; i < length; ++i) {
8773 var eventType = eventTypes[i];
8774 var isPassive = !endsWith(eventType, '_active');
8775 var eventKey = isPassive ? eventType + '_passive' : eventType;
8776 var targetEventType = isPassive ? eventType : eventType.substring(0, eventType.length - 7);
8777
8778 if (!listeningSet.has(eventKey)) {
8779 trapEventForResponderEventSystem(element, targetEventType, isPassive);
8780 listeningSet.add(eventKey);
8781 }
8782 }
8783 }
8784} // We can remove this once the event API is stable and out of a flag
8785
8786if (enableFlareAPI) {
8787 setListenToResponderEventTypes(listenToEventResponderEventTypes);
8788}
8789
8790function getActiveElement(doc) {
8791 doc = doc || (typeof document !== 'undefined' ? document : undefined);
8792
8793 if (typeof doc === 'undefined') {
8794 return null;
8795 }
8796
8797 try {
8798 return doc.activeElement || doc.body;
8799 } catch (e) {
8800 return doc.body;
8801 }
8802}
8803
8804/**
8805 * Given any node return the first leaf node without children.
8806 *
8807 * @param {DOMElement|DOMTextNode} node
8808 * @return {DOMElement|DOMTextNode}
8809 */
8810
8811function getLeafNode(node) {
8812 while (node && node.firstChild) {
8813 node = node.firstChild;
8814 }
8815
8816 return node;
8817}
8818/**
8819 * Get the next sibling within a container. This will walk up the
8820 * DOM if a node's siblings have been exhausted.
8821 *
8822 * @param {DOMElement|DOMTextNode} node
8823 * @return {?DOMElement|DOMTextNode}
8824 */
8825
8826
8827function getSiblingNode(node) {
8828 while (node) {
8829 if (node.nextSibling) {
8830 return node.nextSibling;
8831 }
8832
8833 node = node.parentNode;
8834 }
8835}
8836/**
8837 * Get object describing the nodes which contain characters at offset.
8838 *
8839 * @param {DOMElement|DOMTextNode} root
8840 * @param {number} offset
8841 * @return {?object}
8842 */
8843
8844
8845function getNodeForCharacterOffset(root, offset) {
8846 var node = getLeafNode(root);
8847 var nodeStart = 0;
8848 var nodeEnd = 0;
8849
8850 while (node) {
8851 if (node.nodeType === TEXT_NODE) {
8852 nodeEnd = nodeStart + node.textContent.length;
8853
8854 if (nodeStart <= offset && nodeEnd >= offset) {
8855 return {
8856 node: node,
8857 offset: offset - nodeStart
8858 };
8859 }
8860
8861 nodeStart = nodeEnd;
8862 }
8863
8864 node = getLeafNode(getSiblingNode(node));
8865 }
8866}
8867
8868/**
8869 * @param {DOMElement} outerNode
8870 * @return {?object}
8871 */
8872
8873function getOffsets(outerNode) {
8874 var ownerDocument = outerNode.ownerDocument;
8875 var win = ownerDocument && ownerDocument.defaultView || window;
8876 var selection = win.getSelection && win.getSelection();
8877
8878 if (!selection || selection.rangeCount === 0) {
8879 return null;
8880 }
8881
8882 var anchorNode = selection.anchorNode,
8883 anchorOffset = selection.anchorOffset,
8884 focusNode = selection.focusNode,
8885 focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
8886 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
8887 // expose properties, triggering a "Permission denied error" if any of its
8888 // properties are accessed. The only seemingly possible way to avoid erroring
8889 // is to access a property that typically works for non-anonymous divs and
8890 // catch any error that may otherwise arise. See
8891 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
8892
8893 try {
8894 /* eslint-disable no-unused-expressions */
8895 anchorNode.nodeType;
8896 focusNode.nodeType;
8897 /* eslint-enable no-unused-expressions */
8898 } catch (e) {
8899 return null;
8900 }
8901
8902 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
8903}
8904/**
8905 * Returns {start, end} where `start` is the character/codepoint index of
8906 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
8907 * `end` is the index of (focusNode, focusOffset).
8908 *
8909 * Returns null if you pass in garbage input but we should probably just crash.
8910 *
8911 * Exported only for testing.
8912 */
8913
8914function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
8915 var length = 0;
8916 var start = -1;
8917 var end = -1;
8918 var indexWithinAnchor = 0;
8919 var indexWithinFocus = 0;
8920 var node = outerNode;
8921 var parentNode = null;
8922
8923 outer: while (true) {
8924 var next = null;
8925
8926 while (true) {
8927 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
8928 start = length + anchorOffset;
8929 }
8930
8931 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
8932 end = length + focusOffset;
8933 }
8934
8935 if (node.nodeType === TEXT_NODE) {
8936 length += node.nodeValue.length;
8937 }
8938
8939 if ((next = node.firstChild) === null) {
8940 break;
8941 } // Moving from `node` to its first child `next`.
8942
8943
8944 parentNode = node;
8945 node = next;
8946 }
8947
8948 while (true) {
8949 if (node === outerNode) {
8950 // If `outerNode` has children, this is always the second time visiting
8951 // it. If it has no children, this is still the first loop, and the only
8952 // valid selection is anchorNode and focusNode both equal to this node
8953 // and both offsets 0, in which case we will have handled above.
8954 break outer;
8955 }
8956
8957 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
8958 start = length;
8959 }
8960
8961 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
8962 end = length;
8963 }
8964
8965 if ((next = node.nextSibling) !== null) {
8966 break;
8967 }
8968
8969 node = parentNode;
8970 parentNode = node.parentNode;
8971 } // Moving from `node` to its next sibling `next`.
8972
8973
8974 node = next;
8975 }
8976
8977 if (start === -1 || end === -1) {
8978 // This should never happen. (Would happen if the anchor/focus nodes aren't
8979 // actually inside the passed-in node.)
8980 return null;
8981 }
8982
8983 return {
8984 start: start,
8985 end: end
8986 };
8987}
8988/**
8989 * In modern non-IE browsers, we can support both forward and backward
8990 * selections.
8991 *
8992 * Note: IE10+ supports the Selection object, but it does not support
8993 * the `extend` method, which means that even in modern IE, it's not possible
8994 * to programmatically create a backward selection. Thus, for all IE
8995 * versions, we use the old IE API to create our selections.
8996 *
8997 * @param {DOMElement|DOMTextNode} node
8998 * @param {object} offsets
8999 */
9000
9001function setOffsets(node, offsets) {
9002 var doc = node.ownerDocument || document;
9003 var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
9004 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
9005 // fails when pasting 100+ items)
9006
9007 if (!win.getSelection) {
9008 return;
9009 }
9010
9011 var selection = win.getSelection();
9012 var length = node.textContent.length;
9013 var start = Math.min(offsets.start, length);
9014 var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
9015 // Flip backward selections, so we can set with a single range.
9016
9017 if (!selection.extend && start > end) {
9018 var temp = end;
9019 end = start;
9020 start = temp;
9021 }
9022
9023 var startMarker = getNodeForCharacterOffset(node, start);
9024 var endMarker = getNodeForCharacterOffset(node, end);
9025
9026 if (startMarker && endMarker) {
9027 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
9028 return;
9029 }
9030
9031 var range = doc.createRange();
9032 range.setStart(startMarker.node, startMarker.offset);
9033 selection.removeAllRanges();
9034
9035 if (start > end) {
9036 selection.addRange(range);
9037 selection.extend(endMarker.node, endMarker.offset);
9038 } else {
9039 range.setEnd(endMarker.node, endMarker.offset);
9040 selection.addRange(range);
9041 }
9042 }
9043}
9044
9045function isTextNode(node) {
9046 return node && node.nodeType === TEXT_NODE;
9047}
9048
9049function containsNode(outerNode, innerNode) {
9050 if (!outerNode || !innerNode) {
9051 return false;
9052 } else if (outerNode === innerNode) {
9053 return true;
9054 } else if (isTextNode(outerNode)) {
9055 return false;
9056 } else if (isTextNode(innerNode)) {
9057 return containsNode(outerNode, innerNode.parentNode);
9058 } else if ('contains' in outerNode) {
9059 return outerNode.contains(innerNode);
9060 } else if (outerNode.compareDocumentPosition) {
9061 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
9062 } else {
9063 return false;
9064 }
9065}
9066
9067function isInDocument(node) {
9068 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
9069}
9070
9071function isSameOriginFrame(iframe) {
9072 try {
9073 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
9074 // to throw, e.g. if it has a cross-origin src attribute.
9075 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
9076 // iframe.contentDocument.defaultView;
9077 // A safety way is to access one of the cross origin properties: Window or Location
9078 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
9079 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
9080 return typeof iframe.contentWindow.location.href === 'string';
9081 } catch (err) {
9082 return false;
9083 }
9084}
9085
9086function getActiveElementDeep() {
9087 var win = window;
9088 var element = getActiveElement();
9089
9090 while (element instanceof win.HTMLIFrameElement) {
9091 if (isSameOriginFrame(element)) {
9092 win = element.contentWindow;
9093 } else {
9094 return element;
9095 }
9096
9097 element = getActiveElement(win.document);
9098 }
9099
9100 return element;
9101}
9102/**
9103 * @ReactInputSelection: React input selection module. Based on Selection.js,
9104 * but modified to be suitable for react and has a couple of bug fixes (doesn't
9105 * assume buttons have range selections allowed).
9106 * Input selection module for React.
9107 */
9108
9109/**
9110 * @hasSelectionCapabilities: we get the element types that support selection
9111 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
9112 * and `selectionEnd` rows.
9113 */
9114
9115
9116function hasSelectionCapabilities(elem) {
9117 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
9118 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
9119}
9120function getSelectionInformation() {
9121 var focusedElem = getActiveElementDeep();
9122 return {
9123 focusedElem: focusedElem,
9124 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
9125 };
9126}
9127/**
9128 * @restoreSelection: If any selection information was potentially lost,
9129 * restore it. This is useful when performing operations that could remove dom
9130 * nodes and place them back in, resulting in focus being lost.
9131 */
9132
9133function restoreSelection(priorSelectionInformation) {
9134 var curFocusedElem = getActiveElementDeep();
9135 var priorFocusedElem = priorSelectionInformation.focusedElem;
9136 var priorSelectionRange = priorSelectionInformation.selectionRange;
9137
9138 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
9139 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
9140 setSelection(priorFocusedElem, priorSelectionRange);
9141 } // Focusing a node can change the scroll position, which is undesirable
9142
9143
9144 var ancestors = [];
9145 var ancestor = priorFocusedElem;
9146
9147 while (ancestor = ancestor.parentNode) {
9148 if (ancestor.nodeType === ELEMENT_NODE) {
9149 ancestors.push({
9150 element: ancestor,
9151 left: ancestor.scrollLeft,
9152 top: ancestor.scrollTop
9153 });
9154 }
9155 }
9156
9157 if (typeof priorFocusedElem.focus === 'function') {
9158 priorFocusedElem.focus();
9159 }
9160
9161 for (var i = 0; i < ancestors.length; i++) {
9162 var info = ancestors[i];
9163 info.element.scrollLeft = info.left;
9164 info.element.scrollTop = info.top;
9165 }
9166 }
9167}
9168/**
9169 * @getSelection: Gets the selection bounds of a focused textarea, input or
9170 * contentEditable node.
9171 * -@input: Look up selection bounds of this input
9172 * -@return {start: selectionStart, end: selectionEnd}
9173 */
9174
9175function getSelection(input) {
9176 var selection;
9177
9178 if ('selectionStart' in input) {
9179 // Modern browser with input or textarea.
9180 selection = {
9181 start: input.selectionStart,
9182 end: input.selectionEnd
9183 };
9184 } else {
9185 // Content editable or old IE textarea.
9186 selection = getOffsets(input);
9187 }
9188
9189 return selection || {
9190 start: 0,
9191 end: 0
9192 };
9193}
9194/**
9195 * @setSelection: Sets the selection bounds of a textarea or input and focuses
9196 * the input.
9197 * -@input Set selection bounds of this input or textarea
9198 * -@offsets Object of same form that is returned from get*
9199 */
9200
9201function setSelection(input, offsets) {
9202 var start = offsets.start,
9203 end = offsets.end;
9204
9205 if (end === undefined) {
9206 end = start;
9207 }
9208
9209 if ('selectionStart' in input) {
9210 input.selectionStart = start;
9211 input.selectionEnd = Math.min(end, input.value.length);
9212 } else {
9213 setOffsets(input, offsets);
9214 }
9215}
9216
9217var validateDOMNesting = function () {};
9218
9219var updatedAncestorInfo = function () {};
9220
9221{
9222 // This validation code was written based on the HTML5 parsing spec:
9223 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9224 //
9225 // Note: this does not catch all invalid nesting, nor does it try to (as it's
9226 // not clear what practical benefit doing so provides); instead, we warn only
9227 // for cases where the parser will give a parse tree differing from what React
9228 // intended. For example, <b><div></div></b> is invalid but we don't warn
9229 // because it still parses correctly; we do warn for other cases like nested
9230 // <p> tags where the beginning of the second element implicitly closes the
9231 // first, causing a confusing mess.
9232 // https://html.spec.whatwg.org/multipage/syntax.html#special
9233 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']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9234
9235 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
9236 // TODO: Distinguish by namespace here -- for <title>, including it here
9237 // errs on the side of fewer warnings
9238 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
9239
9240 var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
9241
9242 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
9243 var emptyAncestorInfo = {
9244 current: null,
9245 formTag: null,
9246 aTagInScope: null,
9247 buttonTagInScope: null,
9248 nobrTagInScope: null,
9249 pTagInButtonScope: null,
9250 listItemTagAutoclosing: null,
9251 dlItemTagAutoclosing: null
9252 };
9253
9254 updatedAncestorInfo = function (oldInfo, tag) {
9255 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
9256
9257 var info = {
9258 tag: tag
9259 };
9260
9261 if (inScopeTags.indexOf(tag) !== -1) {
9262 ancestorInfo.aTagInScope = null;
9263 ancestorInfo.buttonTagInScope = null;
9264 ancestorInfo.nobrTagInScope = null;
9265 }
9266
9267 if (buttonScopeTags.indexOf(tag) !== -1) {
9268 ancestorInfo.pTagInButtonScope = null;
9269 } // See rules for 'li', 'dd', 'dt' start tags in
9270 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9271
9272
9273 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
9274 ancestorInfo.listItemTagAutoclosing = null;
9275 ancestorInfo.dlItemTagAutoclosing = null;
9276 }
9277
9278 ancestorInfo.current = info;
9279
9280 if (tag === 'form') {
9281 ancestorInfo.formTag = info;
9282 }
9283
9284 if (tag === 'a') {
9285 ancestorInfo.aTagInScope = info;
9286 }
9287
9288 if (tag === 'button') {
9289 ancestorInfo.buttonTagInScope = info;
9290 }
9291
9292 if (tag === 'nobr') {
9293 ancestorInfo.nobrTagInScope = info;
9294 }
9295
9296 if (tag === 'p') {
9297 ancestorInfo.pTagInButtonScope = info;
9298 }
9299
9300 if (tag === 'li') {
9301 ancestorInfo.listItemTagAutoclosing = info;
9302 }
9303
9304 if (tag === 'dd' || tag === 'dt') {
9305 ancestorInfo.dlItemTagAutoclosing = info;
9306 }
9307
9308 return ancestorInfo;
9309 };
9310 /**
9311 * Returns whether
9312 */
9313
9314
9315 var isTagValidWithParent = function (tag, parentTag) {
9316 // First, let's check if we're in an unusual parsing mode...
9317 switch (parentTag) {
9318 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
9319 case 'select':
9320 return tag === 'option' || tag === 'optgroup' || tag === '#text';
9321
9322 case 'optgroup':
9323 return tag === 'option' || tag === '#text';
9324 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
9325 // but
9326
9327 case 'option':
9328 return tag === '#text';
9329 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
9330 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
9331 // No special behavior since these rules fall back to "in body" mode for
9332 // all except special table nodes which cause bad parsing behavior anyway.
9333 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
9334
9335 case 'tr':
9336 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
9337 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
9338
9339 case 'tbody':
9340 case 'thead':
9341 case 'tfoot':
9342 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
9343 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
9344
9345 case 'colgroup':
9346 return tag === 'col' || tag === 'template';
9347 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
9348
9349 case 'table':
9350 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
9351 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
9352
9353 case 'head':
9354 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
9355 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
9356
9357 case 'html':
9358 return tag === 'head' || tag === 'body' || tag === 'frameset';
9359
9360 case 'frameset':
9361 return tag === 'frame';
9362
9363 case '#document':
9364 return tag === 'html';
9365 } // Probably in the "in body" parsing mode, so we outlaw only tag combos
9366 // where the parsing rules cause implicit opens or closes to be added.
9367 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9368
9369
9370 switch (tag) {
9371 case 'h1':
9372 case 'h2':
9373 case 'h3':
9374 case 'h4':
9375 case 'h5':
9376 case 'h6':
9377 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
9378
9379 case 'rp':
9380 case 'rt':
9381 return impliedEndTags.indexOf(parentTag) === -1;
9382
9383 case 'body':
9384 case 'caption':
9385 case 'col':
9386 case 'colgroup':
9387 case 'frameset':
9388 case 'frame':
9389 case 'head':
9390 case 'html':
9391 case 'tbody':
9392 case 'td':
9393 case 'tfoot':
9394 case 'th':
9395 case 'thead':
9396 case 'tr':
9397 // These tags are only valid with a few parents that have special child
9398 // parsing rules -- if we're down here, then none of those matched and
9399 // so we allow it only if we don't know what the parent is, as all other
9400 // cases are invalid.
9401 return parentTag == null;
9402 }
9403
9404 return true;
9405 };
9406 /**
9407 * Returns whether
9408 */
9409
9410
9411 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
9412 switch (tag) {
9413 case 'address':
9414 case 'article':
9415 case 'aside':
9416 case 'blockquote':
9417 case 'center':
9418 case 'details':
9419 case 'dialog':
9420 case 'dir':
9421 case 'div':
9422 case 'dl':
9423 case 'fieldset':
9424 case 'figcaption':
9425 case 'figure':
9426 case 'footer':
9427 case 'header':
9428 case 'hgroup':
9429 case 'main':
9430 case 'menu':
9431 case 'nav':
9432 case 'ol':
9433 case 'p':
9434 case 'section':
9435 case 'summary':
9436 case 'ul':
9437 case 'pre':
9438 case 'listing':
9439 case 'table':
9440 case 'hr':
9441 case 'xmp':
9442 case 'h1':
9443 case 'h2':
9444 case 'h3':
9445 case 'h4':
9446 case 'h5':
9447 case 'h6':
9448 return ancestorInfo.pTagInButtonScope;
9449
9450 case 'form':
9451 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
9452
9453 case 'li':
9454 return ancestorInfo.listItemTagAutoclosing;
9455
9456 case 'dd':
9457 case 'dt':
9458 return ancestorInfo.dlItemTagAutoclosing;
9459
9460 case 'button':
9461 return ancestorInfo.buttonTagInScope;
9462
9463 case 'a':
9464 // Spec says something about storing a list of markers, but it sounds
9465 // equivalent to this check.
9466 return ancestorInfo.aTagInScope;
9467
9468 case 'nobr':
9469 return ancestorInfo.nobrTagInScope;
9470 }
9471
9472 return null;
9473 };
9474
9475 var didWarn$1 = {};
9476
9477 validateDOMNesting = function (childTag, childText, ancestorInfo) {
9478 ancestorInfo = ancestorInfo || emptyAncestorInfo;
9479 var parentInfo = ancestorInfo.current;
9480 var parentTag = parentInfo && parentInfo.tag;
9481
9482 if (childText != null) {
9483 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
9484 childTag = '#text';
9485 }
9486
9487 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
9488 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
9489 var invalidParentOrAncestor = invalidParent || invalidAncestor;
9490
9491 if (!invalidParentOrAncestor) {
9492 return;
9493 }
9494
9495 var ancestorTag = invalidParentOrAncestor.tag;
9496 var addendum = getCurrentFiberStackInDev();
9497 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
9498
9499 if (didWarn$1[warnKey]) {
9500 return;
9501 }
9502
9503 didWarn$1[warnKey] = true;
9504 var tagDisplayName = childTag;
9505 var whitespaceInfo = '';
9506
9507 if (childTag === '#text') {
9508 if (/\S/.test(childText)) {
9509 tagDisplayName = 'Text nodes';
9510 } else {
9511 tagDisplayName = 'Whitespace text nodes';
9512 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
9513 }
9514 } else {
9515 tagDisplayName = '<' + childTag + '>';
9516 }
9517
9518 if (invalidParent) {
9519 var info = '';
9520
9521 if (ancestorTag === 'table' && childTag === 'tr') {
9522 info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
9523 }
9524
9525 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
9526 } else {
9527 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
9528 }
9529 };
9530}
9531
9532// can re-export everything from this module.
9533
9534function shim() {
9535 (function () {
9536 {
9537 {
9538 throw ReactError(Error("The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue."));
9539 }
9540 }
9541 })();
9542} // Persistence (when unsupported)
9543
9544
9545var supportsPersistence = false;
9546var cloneInstance = shim;
9547var cloneFundamentalInstance = shim;
9548var createContainerChildSet = shim;
9549var appendChildToContainerChildSet = shim;
9550var finalizeContainerChildren = shim;
9551var replaceContainerChildren = shim;
9552var cloneHiddenInstance = shim;
9553var cloneHiddenTextInstance = shim;
9554
9555var SUPPRESS_HYDRATION_WARNING;
9556
9557{
9558 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9559}
9560
9561var SUSPENSE_START_DATA = '$';
9562var SUSPENSE_END_DATA = '/$';
9563var SUSPENSE_PENDING_START_DATA = '$?';
9564var SUSPENSE_FALLBACK_START_DATA = '$!';
9565var STYLE = 'style';
9566var eventsEnabled = null;
9567var selectionInformation = null;
9568
9569function shouldAutoFocusHostComponent(type, props) {
9570 switch (type) {
9571 case 'button':
9572 case 'input':
9573 case 'select':
9574 case 'textarea':
9575 return !!props.autoFocus;
9576 }
9577
9578 return false;
9579}
9580
9581function getRootHostContext(rootContainerInstance) {
9582 var type;
9583 var namespace;
9584 var nodeType = rootContainerInstance.nodeType;
9585
9586 switch (nodeType) {
9587 case DOCUMENT_NODE:
9588 case DOCUMENT_FRAGMENT_NODE:
9589 {
9590 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
9591 var root = rootContainerInstance.documentElement;
9592 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
9593 break;
9594 }
9595
9596 default:
9597 {
9598 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
9599 var ownNamespace = container.namespaceURI || null;
9600 type = container.tagName;
9601 namespace = getChildNamespace(ownNamespace, type);
9602 break;
9603 }
9604 }
9605
9606 {
9607 var validatedTag = type.toLowerCase();
9608 var ancestorInfo = updatedAncestorInfo(null, validatedTag);
9609 return {
9610 namespace: namespace,
9611 ancestorInfo: ancestorInfo
9612 };
9613 }
9614
9615 return namespace;
9616}
9617function getChildHostContext(parentHostContext, type, rootContainerInstance) {
9618 {
9619 var parentHostContextDev = parentHostContext;
9620 var namespace = getChildNamespace(parentHostContextDev.namespace, type);
9621 var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
9622 return {
9623 namespace: namespace,
9624 ancestorInfo: ancestorInfo
9625 };
9626 }
9627
9628 var parentNamespace = parentHostContext;
9629 return getChildNamespace(parentNamespace, type);
9630}
9631function getPublicInstance(instance) {
9632 return instance;
9633}
9634function prepareForCommit(containerInfo) {
9635 eventsEnabled = isEnabled();
9636 selectionInformation = getSelectionInformation();
9637 setEnabled(false);
9638}
9639function resetAfterCommit(containerInfo) {
9640 restoreSelection(selectionInformation);
9641 selectionInformation = null;
9642 setEnabled(eventsEnabled);
9643 eventsEnabled = null;
9644}
9645function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9646 var parentNamespace;
9647
9648 {
9649 // TODO: take namespace into account when validating.
9650 var hostContextDev = hostContext;
9651 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
9652
9653 if (typeof props.children === 'string' || typeof props.children === 'number') {
9654 var string = '' + props.children;
9655 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9656 validateDOMNesting(null, string, ownAncestorInfo);
9657 }
9658
9659 parentNamespace = hostContextDev.namespace;
9660 }
9661
9662 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
9663 precacheFiberNode(internalInstanceHandle, domElement);
9664 updateFiberProps(domElement, props);
9665 return domElement;
9666}
9667function appendInitialChild(parentInstance, child) {
9668 parentInstance.appendChild(child);
9669}
9670function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
9671 setInitialProperties(domElement, type, props, rootContainerInstance);
9672 return shouldAutoFocusHostComponent(type, props);
9673}
9674function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
9675 {
9676 var hostContextDev = hostContext;
9677
9678 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
9679 var string = '' + newProps.children;
9680 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9681 validateDOMNesting(null, string, ownAncestorInfo);
9682 }
9683 }
9684
9685 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
9686}
9687function shouldSetTextContent(type, props) {
9688 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;
9689}
9690function shouldDeprioritizeSubtree(type, props) {
9691 return !!props.hidden;
9692}
9693function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
9694 {
9695 var hostContextDev = hostContext;
9696 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
9697 }
9698
9699 var textNode = createTextNode(text, rootContainerInstance);
9700 precacheFiberNode(internalInstanceHandle, textNode);
9701 return textNode;
9702}
9703var isPrimaryRenderer = true;
9704var warnsIfNotActing = true; // This initialization code may run even on server environments
9705// if a component just imports ReactDOM (e.g. for findDOMNode).
9706// Some environments might not have setTimeout or clearTimeout.
9707
9708var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
9709var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
9710var noTimeout = -1; // -------------------
9711// Mutation
9712// -------------------
9713
9714var supportsMutation = true;
9715function commitMount(domElement, type, newProps, internalInstanceHandle) {
9716 // Despite the naming that might imply otherwise, this method only
9717 // fires if there is an `Update` effect scheduled during mounting.
9718 // This happens if `finalizeInitialChildren` returns `true` (which it
9719 // does to implement the `autoFocus` attribute on the client). But
9720 // there are also other cases when this might happen (such as patching
9721 // up text content during hydration mismatch). So we'll check this again.
9722 if (shouldAutoFocusHostComponent(type, newProps)) {
9723 domElement.focus();
9724 }
9725}
9726function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
9727 // Update the props handle so that we know which props are the ones with
9728 // with current event handlers.
9729 updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.
9730
9731 updateProperties(domElement, updatePayload, type, oldProps, newProps);
9732}
9733function resetTextContent(domElement) {
9734 setTextContent(domElement, '');
9735}
9736function commitTextUpdate(textInstance, oldText, newText) {
9737 textInstance.nodeValue = newText;
9738}
9739function appendChild(parentInstance, child) {
9740 parentInstance.appendChild(child);
9741}
9742function appendChildToContainer(container, child) {
9743 var parentNode;
9744
9745 if (container.nodeType === COMMENT_NODE) {
9746 parentNode = container.parentNode;
9747 parentNode.insertBefore(child, container);
9748 } else {
9749 parentNode = container;
9750 parentNode.appendChild(child);
9751 } // This container might be used for a portal.
9752 // If something inside a portal is clicked, that click should bubble
9753 // through the React tree. However, on Mobile Safari the click would
9754 // never bubble through the *DOM* tree unless an ancestor with onclick
9755 // event exists. So we wouldn't see it and dispatch it.
9756 // This is why we ensure that non React root containers have inline onclick
9757 // defined.
9758 // https://github.com/facebook/react/issues/11918
9759
9760
9761 var reactRootContainer = container._reactRootContainer;
9762
9763 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
9764 // TODO: This cast may not be sound for SVG, MathML or custom elements.
9765 trapClickOnNonInteractiveElement(parentNode);
9766 }
9767}
9768function insertBefore(parentInstance, child, beforeChild) {
9769 parentInstance.insertBefore(child, beforeChild);
9770}
9771function insertInContainerBefore(container, child, beforeChild) {
9772 if (container.nodeType === COMMENT_NODE) {
9773 container.parentNode.insertBefore(child, beforeChild);
9774 } else {
9775 container.insertBefore(child, beforeChild);
9776 }
9777}
9778function removeChild(parentInstance, child) {
9779 parentInstance.removeChild(child);
9780}
9781function removeChildFromContainer(container, child) {
9782 if (container.nodeType === COMMENT_NODE) {
9783 container.parentNode.removeChild(child);
9784 } else {
9785 container.removeChild(child);
9786 }
9787}
9788function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9789 var node = suspenseInstance; // Delete all nodes within this suspense boundary.
9790 // There might be nested nodes so we need to keep track of how
9791 // deep we are and only break out when we're back on top.
9792
9793 var depth = 0;
9794
9795 do {
9796 var nextNode = node.nextSibling;
9797 parentInstance.removeChild(node);
9798
9799 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9800 var data = nextNode.data;
9801
9802 if (data === SUSPENSE_END_DATA) {
9803 if (depth === 0) {
9804 parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
9805
9806 retryIfBlockedOn(suspenseInstance);
9807 return;
9808 } else {
9809 depth--;
9810 }
9811 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
9812 depth++;
9813 }
9814 }
9815
9816 node = nextNode;
9817 } while (node); // TODO: Warn, we didn't find the end comment boundary.
9818 // Retry if any event replaying was blocked on this.
9819
9820
9821 retryIfBlockedOn(suspenseInstance);
9822}
9823function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9824 if (container.nodeType === COMMENT_NODE) {
9825 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9826 } else if (container.nodeType === ELEMENT_NODE) {
9827 clearSuspenseBoundary(container, suspenseInstance);
9828 } else {} // Document nodes should never contain suspense boundaries.
9829 // Retry if any event replaying was blocked on this.
9830
9831
9832 retryIfBlockedOn(container);
9833}
9834function hideInstance(instance) {
9835 // TODO: Does this work for all element types? What about MathML? Should we
9836 // pass host context to this method?
9837 instance = instance;
9838 var style = instance.style;
9839
9840 if (typeof style.setProperty === 'function') {
9841 style.setProperty('display', 'none', 'important');
9842 } else {
9843 style.display = 'none';
9844 }
9845}
9846function hideTextInstance(textInstance) {
9847 textInstance.nodeValue = '';
9848}
9849function unhideInstance(instance, props) {
9850 instance = instance;
9851 var styleProp = props[STYLE];
9852 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9853 instance.style.display = dangerousStyleValue('display', display);
9854}
9855function unhideTextInstance(textInstance, text) {
9856 textInstance.nodeValue = text;
9857} // -------------------
9858// Hydration
9859// -------------------
9860
9861var supportsHydration = true;
9862function canHydrateInstance(instance, type, props) {
9863 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9864 return null;
9865 } // This has now been refined to an element node.
9866
9867
9868 return instance;
9869}
9870function canHydrateTextInstance(instance, text) {
9871 if (text === '' || instance.nodeType !== TEXT_NODE) {
9872 // Empty strings are not parsed by HTML so there won't be a correct match here.
9873 return null;
9874 } // This has now been refined to a text node.
9875
9876
9877 return instance;
9878}
9879function canHydrateSuspenseInstance(instance) {
9880 if (instance.nodeType !== COMMENT_NODE) {
9881 // Empty strings are not parsed by HTML so there won't be a correct match here.
9882 return null;
9883 } // This has now been refined to a suspense node.
9884
9885
9886 return instance;
9887}
9888function isSuspenseInstancePending(instance) {
9889 return instance.data === SUSPENSE_PENDING_START_DATA;
9890}
9891function isSuspenseInstanceFallback(instance) {
9892 return instance.data === SUSPENSE_FALLBACK_START_DATA;
9893}
9894function registerSuspenseInstanceRetry(instance, callback) {
9895 instance._reactRetry = callback;
9896}
9897
9898function getNextHydratable(node) {
9899 // Skip non-hydratable nodes.
9900 for (; node != null; node = node.nextSibling) {
9901 var nodeType = node.nodeType;
9902
9903 if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
9904 break;
9905 }
9906
9907 if (enableSuspenseServerRenderer) {
9908 if (nodeType === COMMENT_NODE) {
9909 var nodeData = node.data;
9910
9911 if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
9912 break;
9913 }
9914 }
9915 }
9916 }
9917
9918 return node;
9919}
9920
9921function getNextHydratableSibling(instance) {
9922 return getNextHydratable(instance.nextSibling);
9923}
9924function getFirstHydratableChild(parentInstance) {
9925 return getNextHydratable(parentInstance.firstChild);
9926}
9927function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9928 precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
9929 // get attached.
9930
9931 updateFiberProps(instance, props);
9932 var parentNamespace;
9933
9934 {
9935 var hostContextDev = hostContext;
9936 parentNamespace = hostContextDev.namespace;
9937 }
9938
9939 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9940}
9941function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9942 precacheFiberNode(internalInstanceHandle, textInstance);
9943 return diffHydratedText(textInstance, text);
9944}
9945function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
9946 precacheFiberNode(internalInstanceHandle, suspenseInstance);
9947}
9948function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9949 var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
9950 // There might be nested nodes so we need to keep track of how
9951 // deep we are and only break out when we're back on top.
9952
9953 var depth = 0;
9954
9955 while (node) {
9956 if (node.nodeType === COMMENT_NODE) {
9957 var data = node.data;
9958
9959 if (data === SUSPENSE_END_DATA) {
9960 if (depth === 0) {
9961 return getNextHydratableSibling(node);
9962 } else {
9963 depth--;
9964 }
9965 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9966 depth++;
9967 }
9968 }
9969
9970 node = node.nextSibling;
9971 } // TODO: Warn, we didn't find the end comment boundary.
9972
9973
9974 return null;
9975} // Returns the SuspenseInstance if this node is a direct child of a
9976// SuspenseInstance. I.e. if its previous sibling is a Comment with
9977// SUSPENSE_x_START_DATA. Otherwise, null.
9978
9979function getParentSuspenseInstance(targetInstance) {
9980 var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
9981 // There might be nested nodes so we need to keep track of how
9982 // deep we are and only break out when we're back on top.
9983
9984 var depth = 0;
9985
9986 while (node) {
9987 if (node.nodeType === COMMENT_NODE) {
9988 var data = node.data;
9989
9990 if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9991 if (depth === 0) {
9992 return node;
9993 } else {
9994 depth--;
9995 }
9996 } else if (data === SUSPENSE_END_DATA) {
9997 depth++;
9998 }
9999 }
10000
10001 node = node.previousSibling;
10002 }
10003
10004 return null;
10005}
10006function commitHydratedContainer(container) {
10007 // Retry if any event replaying was blocked on this.
10008 retryIfBlockedOn(container);
10009}
10010function commitHydratedSuspenseInstance(suspenseInstance) {
10011 // Retry if any event replaying was blocked on this.
10012 retryIfBlockedOn(suspenseInstance);
10013}
10014function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
10015 {
10016 warnForUnmatchedText(textInstance, text);
10017 }
10018}
10019function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
10020 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10021 warnForUnmatchedText(textInstance, text);
10022 }
10023}
10024function didNotHydrateContainerInstance(parentContainer, instance) {
10025 {
10026 if (instance.nodeType === ELEMENT_NODE) {
10027 warnForDeletedHydratableElement(parentContainer, instance);
10028 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
10029 } else {
10030 warnForDeletedHydratableText(parentContainer, instance);
10031 }
10032 }
10033}
10034function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
10035 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10036 if (instance.nodeType === ELEMENT_NODE) {
10037 warnForDeletedHydratableElement(parentInstance, instance);
10038 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
10039 } else {
10040 warnForDeletedHydratableText(parentInstance, instance);
10041 }
10042 }
10043}
10044function didNotFindHydratableContainerInstance(parentContainer, type, props) {
10045 {
10046 warnForInsertedHydratedElement(parentContainer, type, props);
10047 }
10048}
10049function didNotFindHydratableContainerTextInstance(parentContainer, text) {
10050 {
10051 warnForInsertedHydratedText(parentContainer, text);
10052 }
10053}
10054
10055function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
10056 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10057 warnForInsertedHydratedElement(parentInstance, type, props);
10058 }
10059}
10060function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
10061 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10062 warnForInsertedHydratedText(parentInstance, text);
10063 }
10064}
10065function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
10066 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {// TODO: warnForInsertedHydratedSuspense(parentInstance);
10067 }
10068}
10069function mountResponderInstance(responder, responderInstance, responderProps, responderState, instance) {
10070 // Listen to events
10071 var doc = instance.ownerDocument;
10072 var _ref = responder,
10073 rootEventTypes = _ref.rootEventTypes,
10074 targetEventTypes = _ref.targetEventTypes;
10075
10076 if (targetEventTypes !== null) {
10077 listenToEventResponderEventTypes(targetEventTypes, doc);
10078 }
10079
10080 if (rootEventTypes !== null) {
10081 addRootEventTypesForResponderInstance(responderInstance, rootEventTypes);
10082 listenToEventResponderEventTypes(rootEventTypes, doc);
10083 }
10084
10085 mountEventResponder(responder, responderInstance, responderProps, responderState);
10086 return responderInstance;
10087}
10088function unmountResponderInstance(responderInstance) {
10089 if (enableFlareAPI) {
10090 // TODO stop listening to targetEventTypes
10091 unmountEventResponder(responderInstance);
10092 }
10093}
10094function getFundamentalComponentInstance(fundamentalInstance) {
10095 if (enableFundamentalAPI) {
10096 var currentFiber = fundamentalInstance.currentFiber,
10097 impl = fundamentalInstance.impl,
10098 props = fundamentalInstance.props,
10099 state = fundamentalInstance.state;
10100 var instance = impl.getInstance(null, props, state);
10101 precacheFiberNode(currentFiber, instance);
10102 return instance;
10103 } // Because of the flag above, this gets around the Flow error;
10104
10105
10106 return null;
10107}
10108function mountFundamentalComponent(fundamentalInstance) {
10109 if (enableFundamentalAPI) {
10110 var impl = fundamentalInstance.impl,
10111 instance = fundamentalInstance.instance,
10112 props = fundamentalInstance.props,
10113 state = fundamentalInstance.state;
10114 var onMount = impl.onMount;
10115
10116 if (onMount !== undefined) {
10117 onMount(null, instance, props, state);
10118 }
10119 }
10120}
10121function shouldUpdateFundamentalComponent(fundamentalInstance) {
10122 if (enableFundamentalAPI) {
10123 var impl = fundamentalInstance.impl,
10124 prevProps = fundamentalInstance.prevProps,
10125 props = fundamentalInstance.props,
10126 state = fundamentalInstance.state;
10127 var shouldUpdate = impl.shouldUpdate;
10128
10129 if (shouldUpdate !== undefined) {
10130 return shouldUpdate(null, prevProps, props, state);
10131 }
10132 }
10133
10134 return true;
10135}
10136function updateFundamentalComponent(fundamentalInstance) {
10137 if (enableFundamentalAPI) {
10138 var impl = fundamentalInstance.impl,
10139 instance = fundamentalInstance.instance,
10140 prevProps = fundamentalInstance.prevProps,
10141 props = fundamentalInstance.props,
10142 state = fundamentalInstance.state;
10143 var onUpdate = impl.onUpdate;
10144
10145 if (onUpdate !== undefined) {
10146 onUpdate(null, instance, prevProps, props, state);
10147 }
10148 }
10149}
10150function unmountFundamentalComponent(fundamentalInstance) {
10151 if (enableFundamentalAPI) {
10152 var impl = fundamentalInstance.impl,
10153 instance = fundamentalInstance.instance,
10154 props = fundamentalInstance.props,
10155 state = fundamentalInstance.state;
10156 var onUnmount = impl.onUnmount;
10157
10158 if (onUnmount !== undefined) {
10159 onUnmount(null, instance, props, state);
10160 }
10161 }
10162}
10163
10164var randomKey = Math.random().toString(36).slice(2);
10165var internalInstanceKey = '__reactInternalInstance$' + randomKey;
10166var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
10167var internalContainerInstanceKey = '__reactContainere$' + randomKey;
10168function precacheFiberNode(hostInst, node) {
10169 node[internalInstanceKey] = hostInst;
10170}
10171function markContainerAsRoot(hostRoot, node) {
10172 node[internalContainerInstanceKey] = hostRoot;
10173} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
10174// If the target node is part of a hydrated or not yet rendered subtree, then
10175// this may also return a SuspenseComponent or HostRoot to indicate that.
10176// Conceptually the HostRoot fiber is a child of the Container node. So if you
10177// pass the Container node as the targetNode, you wiill not actually get the
10178// HostRoot back. To get to the HostRoot, you need to pass a child of it.
10179// The same thing applies to Suspense boundaries.
10180
10181function getClosestInstanceFromNode(targetNode) {
10182 var targetInst = targetNode[internalInstanceKey];
10183
10184 if (targetInst) {
10185 // Don't return HostRoot or SuspenseComponent here.
10186 return targetInst;
10187 } // If the direct event target isn't a React owned DOM node, we need to look
10188 // to see if one of its parents is a React owned DOM node.
10189
10190
10191 var parentNode = targetNode.parentNode;
10192
10193 while (parentNode) {
10194 // We'll check if this is a container root that could include
10195 // React nodes in the future. We need to check this first because
10196 // if we're a child of a dehydrated container, we need to first
10197 // find that inner container before moving on to finding the parent
10198 // instance. Note that we don't check this field on the targetNode
10199 // itself because the fibers are conceptually between the container
10200 // node and the first child. It isn't surrounding the container node.
10201 // If it's not a container, we check if it's an instance.
10202 targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
10203
10204 if (targetInst) {
10205 // Since this wasn't the direct target of the event, we might have
10206 // stepped past dehydrated DOM nodes to get here. However they could
10207 // also have been non-React nodes. We need to answer which one.
10208 // If we the instance doesn't have any children, then there can't be
10209 // a nested suspense boundary within it. So we can use this as a fast
10210 // bailout. Most of the time, when people add non-React children to
10211 // the tree, it is using a ref to a child-less DOM node.
10212 // Normally we'd only need to check one of the fibers because if it
10213 // has ever gone from having children to deleting them or vice versa
10214 // it would have deleted the dehydrated boundary nested inside already.
10215 // However, since the HostRoot starts out with an alternate it might
10216 // have one on the alternate so we need to check in case this was a
10217 // root.
10218 var alternate = targetInst.alternate;
10219
10220 if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
10221 // Next we need to figure out if the node that skipped past is
10222 // nested within a dehydrated boundary and if so, which one.
10223 var suspenseInstance = getParentSuspenseInstance(targetNode);
10224
10225 while (suspenseInstance !== null) {
10226 // We found a suspense instance. That means that we haven't
10227 // hydrated it yet. Even though we leave the comments in the
10228 // DOM after hydrating, and there are boundaries in the DOM
10229 // that could already be hydrated, we wouldn't have found them
10230 // through this pass since if the target is hydrated it would
10231 // have had an internalInstanceKey on it.
10232 // Let's get the fiber associated with the SuspenseComponent
10233 // as the deepest instance.
10234 var targetSuspenseInst = suspenseInstance[internalInstanceKey];
10235
10236 if (targetSuspenseInst) {
10237 return targetSuspenseInst;
10238 } // If we don't find a Fiber on the comment, it might be because
10239 // we haven't gotten to hydrate it yet. There might still be a
10240 // parent boundary that hasn't above this one so we need to find
10241 // the outer most that is known.
10242
10243
10244 suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
10245 // host component also hasn't hydrated yet. We can return it
10246 // below since it will bail out on the isMounted check later.
10247 }
10248 }
10249
10250 return targetInst;
10251 }
10252
10253 targetNode = parentNode;
10254 parentNode = targetNode.parentNode;
10255 }
10256
10257 return null;
10258}
10259/**
10260 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
10261 * instance, or null if the node was not rendered by this React.
10262 */
10263
10264function getInstanceFromNode$1(node) {
10265 var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
10266
10267 if (inst) {
10268 if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
10269 return inst;
10270 } else {
10271 return null;
10272 }
10273 }
10274
10275 return null;
10276}
10277/**
10278 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
10279 * DOM node.
10280 */
10281
10282function getNodeFromInstance$1(inst) {
10283 if (inst.tag === HostComponent || inst.tag === HostText) {
10284 // In Fiber this, is just the state node right now. We assume it will be
10285 // a host component or host text.
10286 return inst.stateNode;
10287 } // Without this first invariant, passing a non-DOM-component triggers the next
10288 // invariant for a missing parent, which is super confusing.
10289
10290
10291 (function () {
10292 {
10293 {
10294 throw ReactError(Error("getNodeFromInstance: Invalid argument."));
10295 }
10296 }
10297 })();
10298}
10299function getFiberCurrentPropsFromNode$1(node) {
10300 return node[internalEventHandlersKey] || null;
10301}
10302function updateFiberProps(node, props) {
10303 node[internalEventHandlersKey] = props;
10304}
10305
10306/**
10307 * These variables store information about text content of a target node,
10308 * allowing comparison of content before and after a given event.
10309 *
10310 * Identify the node where selection currently begins, then observe
10311 * both its text content and its current position in the DOM. Since the
10312 * browser may natively replace the target node during composition, we can
10313 * use its position to find its replacement.
10314 *
10315 *
10316 */
10317var root = null;
10318var startText = null;
10319var fallbackText = null;
10320function initialize(nativeEventTarget) {
10321 root = nativeEventTarget;
10322 startText = getText();
10323 return true;
10324}
10325function reset() {
10326 root = null;
10327 startText = null;
10328 fallbackText = null;
10329}
10330function getData() {
10331 if (fallbackText) {
10332 return fallbackText;
10333 }
10334
10335 var start;
10336 var startValue = startText;
10337 var startLength = startValue.length;
10338 var end;
10339 var endValue = getText();
10340 var endLength = endValue.length;
10341
10342 for (start = 0; start < startLength; start++) {
10343 if (startValue[start] !== endValue[start]) {
10344 break;
10345 }
10346 }
10347
10348 var minEnd = startLength - start;
10349
10350 for (end = 1; end <= minEnd; end++) {
10351 if (startValue[startLength - end] !== endValue[endLength - end]) {
10352 break;
10353 }
10354 }
10355
10356 var sliceTail = end > 1 ? 1 - end : undefined;
10357 fallbackText = endValue.slice(start, sliceTail);
10358 return fallbackText;
10359}
10360function getText() {
10361 if ('value' in root) {
10362 return root.value;
10363 }
10364
10365 return root.textContent;
10366}
10367
10368/**
10369 * @interface Event
10370 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
10371 */
10372
10373var SyntheticCompositionEvent = SyntheticEvent.extend({
10374 data: null
10375});
10376
10377/**
10378 * @interface Event
10379 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
10380 * /#events-inputevents
10381 */
10382
10383var SyntheticInputEvent = SyntheticEvent.extend({
10384 data: null
10385});
10386
10387var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
10388
10389var START_KEYCODE = 229;
10390var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
10391var documentMode = null;
10392
10393if (canUseDOM && 'documentMode' in document) {
10394 documentMode = document.documentMode;
10395} // Webkit offers a very useful `textInput` event that can be used to
10396// directly represent `beforeInput`. The IE `textinput` event is not as
10397// useful, so we don't use it.
10398
10399
10400var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
10401// by the native compositionend event may be incorrect. Japanese ideographic
10402// spaces, for instance (\u3000) are not recorded correctly.
10403
10404var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
10405var SPACEBAR_CODE = 32;
10406var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.
10407
10408var eventTypes$1 = {
10409 beforeInput: {
10410 phasedRegistrationNames: {
10411 bubbled: 'onBeforeInput',
10412 captured: 'onBeforeInputCapture'
10413 },
10414 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
10415 },
10416 compositionEnd: {
10417 phasedRegistrationNames: {
10418 bubbled: 'onCompositionEnd',
10419 captured: 'onCompositionEndCapture'
10420 },
10421 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10422 },
10423 compositionStart: {
10424 phasedRegistrationNames: {
10425 bubbled: 'onCompositionStart',
10426 captured: 'onCompositionStartCapture'
10427 },
10428 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10429 },
10430 compositionUpdate: {
10431 phasedRegistrationNames: {
10432 bubbled: 'onCompositionUpdate',
10433 captured: 'onCompositionUpdateCapture'
10434 },
10435 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10436 }
10437}; // Track whether we've ever handled a keypress on the space key.
10438
10439var hasSpaceKeypress = false;
10440/**
10441 * Return whether a native keypress event is assumed to be a command.
10442 * This is required because Firefox fires `keypress` events for key commands
10443 * (cut, copy, select-all, etc.) even though no character is inserted.
10444 */
10445
10446function isKeypressCommand(nativeEvent) {
10447 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
10448 !(nativeEvent.ctrlKey && nativeEvent.altKey);
10449}
10450/**
10451 * Translate native top level events into event types.
10452 *
10453 * @param {string} topLevelType
10454 * @return {object}
10455 */
10456
10457
10458function getCompositionEventType(topLevelType) {
10459 switch (topLevelType) {
10460 case TOP_COMPOSITION_START:
10461 return eventTypes$1.compositionStart;
10462
10463 case TOP_COMPOSITION_END:
10464 return eventTypes$1.compositionEnd;
10465
10466 case TOP_COMPOSITION_UPDATE:
10467 return eventTypes$1.compositionUpdate;
10468 }
10469}
10470/**
10471 * Does our fallback best-guess model think this event signifies that
10472 * composition has begun?
10473 *
10474 * @param {string} topLevelType
10475 * @param {object} nativeEvent
10476 * @return {boolean}
10477 */
10478
10479
10480function isFallbackCompositionStart(topLevelType, nativeEvent) {
10481 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
10482}
10483/**
10484 * Does our fallback mode think that this event is the end of composition?
10485 *
10486 * @param {string} topLevelType
10487 * @param {object} nativeEvent
10488 * @return {boolean}
10489 */
10490
10491
10492function isFallbackCompositionEnd(topLevelType, nativeEvent) {
10493 switch (topLevelType) {
10494 case TOP_KEY_UP:
10495 // Command keys insert or clear IME input.
10496 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
10497
10498 case TOP_KEY_DOWN:
10499 // Expect IME keyCode on each keydown. If we get any other
10500 // code we must have exited earlier.
10501 return nativeEvent.keyCode !== START_KEYCODE;
10502
10503 case TOP_KEY_PRESS:
10504 case TOP_MOUSE_DOWN:
10505 case TOP_BLUR:
10506 // Events are not possible without cancelling IME.
10507 return true;
10508
10509 default:
10510 return false;
10511 }
10512}
10513/**
10514 * Google Input Tools provides composition data via a CustomEvent,
10515 * with the `data` property populated in the `detail` object. If this
10516 * is available on the event object, use it. If not, this is a plain
10517 * composition event and we have nothing special to extract.
10518 *
10519 * @param {object} nativeEvent
10520 * @return {?string}
10521 */
10522
10523
10524function getDataFromCustomEvent(nativeEvent) {
10525 var detail = nativeEvent.detail;
10526
10527 if (typeof detail === 'object' && 'data' in detail) {
10528 return detail.data;
10529 }
10530
10531 return null;
10532}
10533/**
10534 * Check if a composition event was triggered by Korean IME.
10535 * Our fallback mode does not work well with IE's Korean IME,
10536 * so just use native composition events when Korean IME is used.
10537 * Although CompositionEvent.locale property is deprecated,
10538 * it is available in IE, where our fallback mode is enabled.
10539 *
10540 * @param {object} nativeEvent
10541 * @return {boolean}
10542 */
10543
10544
10545function isUsingKoreanIME(nativeEvent) {
10546 return nativeEvent.locale === 'ko';
10547} // Track the current IME composition status, if any.
10548
10549
10550var isComposing = false;
10551/**
10552 * @return {?object} A SyntheticCompositionEvent.
10553 */
10554
10555function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10556 var eventType;
10557 var fallbackData;
10558
10559 if (canUseCompositionEvent) {
10560 eventType = getCompositionEventType(topLevelType);
10561 } else if (!isComposing) {
10562 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
10563 eventType = eventTypes$1.compositionStart;
10564 }
10565 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10566 eventType = eventTypes$1.compositionEnd;
10567 }
10568
10569 if (!eventType) {
10570 return null;
10571 }
10572
10573 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
10574 // The current composition is stored statically and must not be
10575 // overwritten while composition continues.
10576 if (!isComposing && eventType === eventTypes$1.compositionStart) {
10577 isComposing = initialize(nativeEventTarget);
10578 } else if (eventType === eventTypes$1.compositionEnd) {
10579 if (isComposing) {
10580 fallbackData = getData();
10581 }
10582 }
10583 }
10584
10585 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
10586
10587 if (fallbackData) {
10588 // Inject data generated from fallback path into the synthetic event.
10589 // This matches the property of native CompositionEventInterface.
10590 event.data = fallbackData;
10591 } else {
10592 var customData = getDataFromCustomEvent(nativeEvent);
10593
10594 if (customData !== null) {
10595 event.data = customData;
10596 }
10597 }
10598
10599 accumulateTwoPhaseDispatches(event);
10600 return event;
10601}
10602/**
10603 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
10604 * @param {object} nativeEvent Native browser event.
10605 * @return {?string} The string corresponding to this `beforeInput` event.
10606 */
10607
10608
10609function getNativeBeforeInputChars(topLevelType, nativeEvent) {
10610 switch (topLevelType) {
10611 case TOP_COMPOSITION_END:
10612 return getDataFromCustomEvent(nativeEvent);
10613
10614 case TOP_KEY_PRESS:
10615 /**
10616 * If native `textInput` events are available, our goal is to make
10617 * use of them. However, there is a special case: the spacebar key.
10618 * In Webkit, preventing default on a spacebar `textInput` event
10619 * cancels character insertion, but it *also* causes the browser
10620 * to fall back to its default spacebar behavior of scrolling the
10621 * page.
10622 *
10623 * Tracking at:
10624 * https://code.google.com/p/chromium/issues/detail?id=355103
10625 *
10626 * To avoid this issue, use the keypress event as if no `textInput`
10627 * event is available.
10628 */
10629 var which = nativeEvent.which;
10630
10631 if (which !== SPACEBAR_CODE) {
10632 return null;
10633 }
10634
10635 hasSpaceKeypress = true;
10636 return SPACEBAR_CHAR;
10637
10638 case TOP_TEXT_INPUT:
10639 // Record the characters to be added to the DOM.
10640 var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
10641 // it at the keypress level and bail immediately. Android Chrome
10642 // doesn't give us keycodes, so we need to ignore it.
10643
10644 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
10645 return null;
10646 }
10647
10648 return chars;
10649
10650 default:
10651 // For other native event types, do nothing.
10652 return null;
10653 }
10654}
10655/**
10656 * For browsers that do not provide the `textInput` event, extract the
10657 * appropriate string to use for SyntheticInputEvent.
10658 *
10659 * @param {number} topLevelType Number from `TopLevelEventTypes`.
10660 * @param {object} nativeEvent Native browser event.
10661 * @return {?string} The fallback string for this `beforeInput` event.
10662 */
10663
10664
10665function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
10666 // If we are currently composing (IME) and using a fallback to do so,
10667 // try to extract the composed characters from the fallback object.
10668 // If composition event is available, we extract a string only at
10669 // compositionevent, otherwise extract it at fallback events.
10670 if (isComposing) {
10671 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10672 var chars = getData();
10673 reset();
10674 isComposing = false;
10675 return chars;
10676 }
10677
10678 return null;
10679 }
10680
10681 switch (topLevelType) {
10682 case TOP_PASTE:
10683 // If a paste event occurs after a keypress, throw out the input
10684 // chars. Paste events should not lead to BeforeInput events.
10685 return null;
10686
10687 case TOP_KEY_PRESS:
10688 /**
10689 * As of v27, Firefox may fire keypress events even when no character
10690 * will be inserted. A few possibilities:
10691 *
10692 * - `which` is `0`. Arrow keys, Esc key, etc.
10693 *
10694 * - `which` is the pressed key code, but no char is available.
10695 * Ex: 'AltGr + d` in Polish. There is no modified character for
10696 * this key combination and no character is inserted into the
10697 * document, but FF fires the keypress for char code `100` anyway.
10698 * No `input` event will occur.
10699 *
10700 * - `which` is the pressed key code, but a command combination is
10701 * being used. Ex: `Cmd+C`. No character is inserted, and no
10702 * `input` event will occur.
10703 */
10704 if (!isKeypressCommand(nativeEvent)) {
10705 // IE fires the `keypress` event when a user types an emoji via
10706 // Touch keyboard of Windows. In such a case, the `char` property
10707 // holds an emoji character like `\uD83D\uDE0A`. Because its length
10708 // is 2, the property `which` does not represent an emoji correctly.
10709 // In such a case, we directly return the `char` property instead of
10710 // using `which`.
10711 if (nativeEvent.char && nativeEvent.char.length > 1) {
10712 return nativeEvent.char;
10713 } else if (nativeEvent.which) {
10714 return String.fromCharCode(nativeEvent.which);
10715 }
10716 }
10717
10718 return null;
10719
10720 case TOP_COMPOSITION_END:
10721 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
10722
10723 default:
10724 return null;
10725 }
10726}
10727/**
10728 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
10729 * `textInput` or fallback behavior.
10730 *
10731 * @return {?object} A SyntheticInputEvent.
10732 */
10733
10734
10735function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10736 var chars;
10737
10738 if (canUseTextInputEvent) {
10739 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
10740 } else {
10741 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
10742 } // If no characters are being inserted, no BeforeInput event should
10743 // be fired.
10744
10745
10746 if (!chars) {
10747 return null;
10748 }
10749
10750 var event = SyntheticInputEvent.getPooled(eventTypes$1.beforeInput, targetInst, nativeEvent, nativeEventTarget);
10751 event.data = chars;
10752 accumulateTwoPhaseDispatches(event);
10753 return event;
10754}
10755/**
10756 * Create an `onBeforeInput` event to match
10757 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
10758 *
10759 * This event plugin is based on the native `textInput` event
10760 * available in Chrome, Safari, Opera, and IE. This event fires after
10761 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
10762 *
10763 * `beforeInput` is spec'd but not implemented in any browsers, and
10764 * the `input` event does not provide any useful information about what has
10765 * actually been added, contrary to the spec. Thus, `textInput` is the best
10766 * available event to identify the characters that have actually been inserted
10767 * into the target node.
10768 *
10769 * This plugin is also responsible for emitting `composition` events, thus
10770 * allowing us to share composition fallback code for both `beforeInput` and
10771 * `composition` event types.
10772 */
10773
10774
10775var BeforeInputEventPlugin = {
10776 eventTypes: eventTypes$1,
10777 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10778 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10779 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10780
10781 if (composition === null) {
10782 return beforeInput;
10783 }
10784
10785 if (beforeInput === null) {
10786 return composition;
10787 }
10788
10789 return [composition, beforeInput];
10790 }
10791};
10792
10793/**
10794 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
10795 */
10796var supportedInputTypes = {
10797 color: true,
10798 date: true,
10799 datetime: true,
10800 'datetime-local': true,
10801 email: true,
10802 month: true,
10803 number: true,
10804 password: true,
10805 range: true,
10806 search: true,
10807 tel: true,
10808 text: true,
10809 time: true,
10810 url: true,
10811 week: true
10812};
10813
10814function isTextInputElement(elem) {
10815 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
10816
10817 if (nodeName === 'input') {
10818 return !!supportedInputTypes[elem.type];
10819 }
10820
10821 if (nodeName === 'textarea') {
10822 return true;
10823 }
10824
10825 return false;
10826}
10827
10828var eventTypes$2 = {
10829 change: {
10830 phasedRegistrationNames: {
10831 bubbled: 'onChange',
10832 captured: 'onChangeCapture'
10833 },
10834 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
10835 }
10836};
10837
10838function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
10839 var event = SyntheticEvent.getPooled(eventTypes$2.change, inst, nativeEvent, target);
10840 event.type = 'change'; // Flag this event loop as needing state restore.
10841
10842 enqueueStateRestore(target);
10843 accumulateTwoPhaseDispatches(event);
10844 return event;
10845}
10846/**
10847 * For IE shims
10848 */
10849
10850
10851var activeElement = null;
10852var activeElementInst = null;
10853/**
10854 * SECTION: handle `change` event
10855 */
10856
10857function shouldUseChangeEvent(elem) {
10858 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
10859 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
10860}
10861
10862function manualDispatchChangeEvent(nativeEvent) {
10863 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
10864 // other events and have it go through ReactBrowserEventEmitter. Since it
10865 // doesn't, we manually listen for the events and so we have to enqueue and
10866 // process the abstract event manually.
10867 //
10868 // Batching is necessary here in order to ensure that all event handlers run
10869 // before the next rerender (including event handlers attached to ancestor
10870 // elements instead of directly on the input). Without this, controlled
10871 // components don't work properly in conjunction with event bubbling because
10872 // the component is rerendered and the value reverted before all the event
10873 // handlers can run. See https://github.com/facebook/react/issues/708.
10874
10875 batchedUpdates(runEventInBatch, event);
10876}
10877
10878function runEventInBatch(event) {
10879 runEventsInBatch(event);
10880}
10881
10882function getInstIfValueChanged(targetInst) {
10883 var targetNode = getNodeFromInstance$1(targetInst);
10884
10885 if (updateValueIfChanged(targetNode)) {
10886 return targetInst;
10887 }
10888}
10889
10890function getTargetInstForChangeEvent(topLevelType, targetInst) {
10891 if (topLevelType === TOP_CHANGE) {
10892 return targetInst;
10893 }
10894}
10895/**
10896 * SECTION: handle `input` event
10897 */
10898
10899
10900var isInputEventSupported = false;
10901
10902if (canUseDOM) {
10903 // IE9 claims to support the input event but fails to trigger it when
10904 // deleting text, so we ignore its input events.
10905 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
10906}
10907/**
10908 * (For IE <=9) Starts tracking propertychange events on the passed-in element
10909 * and override the value property so that we can distinguish user events from
10910 * value changes in JS.
10911 */
10912
10913
10914function startWatchingForValueChange(target, targetInst) {
10915 activeElement = target;
10916 activeElementInst = targetInst;
10917 activeElement.attachEvent('onpropertychange', handlePropertyChange);
10918}
10919/**
10920 * (For IE <=9) Removes the event listeners from the currently-tracked element,
10921 * if any exists.
10922 */
10923
10924
10925function stopWatchingForValueChange() {
10926 if (!activeElement) {
10927 return;
10928 }
10929
10930 activeElement.detachEvent('onpropertychange', handlePropertyChange);
10931 activeElement = null;
10932 activeElementInst = null;
10933}
10934/**
10935 * (For IE <=9) Handles a propertychange event, sending a `change` event if
10936 * the value of the active element has changed.
10937 */
10938
10939
10940function handlePropertyChange(nativeEvent) {
10941 if (nativeEvent.propertyName !== 'value') {
10942 return;
10943 }
10944
10945 if (getInstIfValueChanged(activeElementInst)) {
10946 manualDispatchChangeEvent(nativeEvent);
10947 }
10948}
10949
10950function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
10951 if (topLevelType === TOP_FOCUS) {
10952 // In IE9, propertychange fires for most input events but is buggy and
10953 // doesn't fire when text is deleted, but conveniently, selectionchange
10954 // appears to fire in all of the remaining cases so we catch those and
10955 // forward the event if the value has changed
10956 // In either case, we don't want to call the event handler if the value
10957 // is changed from JS so we redefine a setter for `.value` that updates
10958 // our activeElementValue variable, allowing us to ignore those changes
10959 //
10960 // stopWatching() should be a noop here but we call it just in case we
10961 // missed a blur event somehow.
10962 stopWatchingForValueChange();
10963 startWatchingForValueChange(target, targetInst);
10964 } else if (topLevelType === TOP_BLUR) {
10965 stopWatchingForValueChange();
10966 }
10967} // For IE8 and IE9.
10968
10969
10970function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
10971 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
10972 // On the selectionchange event, the target is just document which isn't
10973 // helpful for us so just check activeElement instead.
10974 //
10975 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
10976 // propertychange on the first input event after setting `value` from a
10977 // script and fires only keydown, keypress, keyup. Catching keyup usually
10978 // gets it and catching keydown lets us fire an event for the first
10979 // keystroke if user does a key repeat (it'll be a little delayed: right
10980 // before the second keystroke). Other input methods (e.g., paste) seem to
10981 // fire selectionchange normally.
10982 return getInstIfValueChanged(activeElementInst);
10983 }
10984}
10985/**
10986 * SECTION: handle `click` event
10987 */
10988
10989
10990function shouldUseClickEvent(elem) {
10991 // Use the `click` event to detect changes to checkbox and radio inputs.
10992 // This approach works across all browsers, whereas `change` does not fire
10993 // until `blur` in IE8.
10994 var nodeName = elem.nodeName;
10995 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
10996}
10997
10998function getTargetInstForClickEvent(topLevelType, targetInst) {
10999 if (topLevelType === TOP_CLICK) {
11000 return getInstIfValueChanged(targetInst);
11001 }
11002}
11003
11004function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
11005 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
11006 return getInstIfValueChanged(targetInst);
11007 }
11008}
11009
11010function handleControlledInputBlur(node) {
11011 var state = node._wrapperState;
11012
11013 if (!state || !state.controlled || node.type !== 'number') {
11014 return;
11015 }
11016
11017 if (!disableInputAttributeSyncing) {
11018 // If controlled, assign the value attribute to the current value on blur
11019 setDefaultValue(node, 'number', node.value);
11020 }
11021}
11022/**
11023 * This plugin creates an `onChange` event that normalizes change events
11024 * across form elements. This event fires at a time when it's possible to
11025 * change the element's value without seeing a flicker.
11026 *
11027 * Supported elements are:
11028 * - input (see `isTextInputElement`)
11029 * - textarea
11030 * - select
11031 */
11032
11033
11034var ChangeEventPlugin = {
11035 eventTypes: eventTypes$2,
11036 _isInputEventSupported: isInputEventSupported,
11037 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11038 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
11039 var getTargetInstFunc, handleEventFunc;
11040
11041 if (shouldUseChangeEvent(targetNode)) {
11042 getTargetInstFunc = getTargetInstForChangeEvent;
11043 } else if (isTextInputElement(targetNode)) {
11044 if (isInputEventSupported) {
11045 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
11046 } else {
11047 getTargetInstFunc = getTargetInstForInputEventPolyfill;
11048 handleEventFunc = handleEventsForInputEventPolyfill;
11049 }
11050 } else if (shouldUseClickEvent(targetNode)) {
11051 getTargetInstFunc = getTargetInstForClickEvent;
11052 }
11053
11054 if (getTargetInstFunc) {
11055 var inst = getTargetInstFunc(topLevelType, targetInst);
11056
11057 if (inst) {
11058 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
11059 return event;
11060 }
11061 }
11062
11063 if (handleEventFunc) {
11064 handleEventFunc(topLevelType, targetNode, targetInst);
11065 } // When blurring, set the value attribute for number inputs
11066
11067
11068 if (topLevelType === TOP_BLUR) {
11069 handleControlledInputBlur(targetNode);
11070 }
11071 }
11072};
11073
11074/**
11075 * Module that is injectable into `EventPluginHub`, that specifies a
11076 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
11077 * plugins, without having to package every one of them. This is better than
11078 * having plugins be ordered in the same order that they are injected because
11079 * that ordering would be influenced by the packaging order.
11080 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
11081 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
11082 */
11083var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
11084
11085var eventTypes$3 = {
11086 mouseEnter: {
11087 registrationName: 'onMouseEnter',
11088 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
11089 },
11090 mouseLeave: {
11091 registrationName: 'onMouseLeave',
11092 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
11093 },
11094 pointerEnter: {
11095 registrationName: 'onPointerEnter',
11096 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
11097 },
11098 pointerLeave: {
11099 registrationName: 'onPointerLeave',
11100 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
11101 }
11102};
11103var EnterLeaveEventPlugin = {
11104 eventTypes: eventTypes$3,
11105
11106 /**
11107 * For almost every interaction we care about, there will be both a top-level
11108 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
11109 * we do not extract duplicate events. However, moving the mouse into the
11110 * browser from outside will not fire a `mouseout` event. In this case, we use
11111 * the `mouseover` top-level event.
11112 */
11113 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11114 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
11115 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
11116
11117 if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
11118 // If this is an over event with a target, then we've already dispatched
11119 // the event in the out event of the other target. If this is replayed,
11120 // then it's because we couldn't dispatch against this target previously
11121 // so we have to do it now instead.
11122 return null;
11123 }
11124
11125 if (!isOutEvent && !isOverEvent) {
11126 // Must not be a mouse or pointer in or out - ignoring.
11127 return null;
11128 }
11129
11130 var win;
11131
11132 if (nativeEventTarget.window === nativeEventTarget) {
11133 // `nativeEventTarget` is probably a window object.
11134 win = nativeEventTarget;
11135 } else {
11136 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
11137 var doc = nativeEventTarget.ownerDocument;
11138
11139 if (doc) {
11140 win = doc.defaultView || doc.parentWindow;
11141 } else {
11142 win = window;
11143 }
11144 }
11145
11146 var from;
11147 var to;
11148
11149 if (isOutEvent) {
11150 from = targetInst;
11151 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
11152 to = related ? getClosestInstanceFromNode(related) : null;
11153
11154 if (to !== null) {
11155 var nearestMounted = getNearestMountedFiber(to);
11156
11157 if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
11158 to = null;
11159 }
11160 }
11161 } else {
11162 // Moving to a node from outside the window.
11163 from = null;
11164 to = targetInst;
11165 }
11166
11167 if (from === to) {
11168 // Nothing pertains to our managed components.
11169 return null;
11170 }
11171
11172 var eventInterface, leaveEventType, enterEventType, eventTypePrefix;
11173
11174 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
11175 eventInterface = SyntheticMouseEvent;
11176 leaveEventType = eventTypes$3.mouseLeave;
11177 enterEventType = eventTypes$3.mouseEnter;
11178 eventTypePrefix = 'mouse';
11179 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
11180 eventInterface = SyntheticPointerEvent;
11181 leaveEventType = eventTypes$3.pointerLeave;
11182 enterEventType = eventTypes$3.pointerEnter;
11183 eventTypePrefix = 'pointer';
11184 }
11185
11186 var fromNode = from == null ? win : getNodeFromInstance$1(from);
11187 var toNode = to == null ? win : getNodeFromInstance$1(to);
11188 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
11189 leave.type = eventTypePrefix + 'leave';
11190 leave.target = fromNode;
11191 leave.relatedTarget = toNode;
11192 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
11193 enter.type = eventTypePrefix + 'enter';
11194 enter.target = toNode;
11195 enter.relatedTarget = fromNode;
11196 accumulateEnterLeaveDispatches(leave, enter, from, to);
11197 return [leave, enter];
11198 }
11199};
11200
11201/**
11202 * inlined Object.is polyfill to avoid requiring consumers ship their own
11203 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
11204 */
11205function is(x, y) {
11206 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
11207 ;
11208}
11209
11210var is$1 = typeof Object.is === 'function' ? Object.is : is;
11211
11212var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
11213/**
11214 * Performs equality by iterating through keys on an object and returning false
11215 * when any key has values which are not strictly equal between the arguments.
11216 * Returns true when the values of all keys are strictly equal.
11217 */
11218
11219function shallowEqual(objA, objB) {
11220 if (is$1(objA, objB)) {
11221 return true;
11222 }
11223
11224 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
11225 return false;
11226 }
11227
11228 var keysA = Object.keys(objA);
11229 var keysB = Object.keys(objB);
11230
11231 if (keysA.length !== keysB.length) {
11232 return false;
11233 } // Test for A's keys different from B.
11234
11235
11236 for (var i = 0; i < keysA.length; i++) {
11237 if (!hasOwnProperty$2.call(objB, keysA[i]) || !is$1(objA[keysA[i]], objB[keysA[i]])) {
11238 return false;
11239 }
11240 }
11241
11242 return true;
11243}
11244
11245var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
11246var eventTypes$4 = {
11247 select: {
11248 phasedRegistrationNames: {
11249 bubbled: 'onSelect',
11250 captured: 'onSelectCapture'
11251 },
11252 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]
11253 }
11254};
11255var activeElement$1 = null;
11256var activeElementInst$1 = null;
11257var lastSelection = null;
11258var mouseDown = false;
11259/**
11260 * Get an object which is a unique representation of the current selection.
11261 *
11262 * The return value will not be consistent across nodes or browsers, but
11263 * two identical selections on the same node will return identical objects.
11264 *
11265 * @param {DOMElement} node
11266 * @return {object}
11267 */
11268
11269function getSelection$1(node) {
11270 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
11271 return {
11272 start: node.selectionStart,
11273 end: node.selectionEnd
11274 };
11275 } else {
11276 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
11277 var selection = win.getSelection();
11278 return {
11279 anchorNode: selection.anchorNode,
11280 anchorOffset: selection.anchorOffset,
11281 focusNode: selection.focusNode,
11282 focusOffset: selection.focusOffset
11283 };
11284 }
11285}
11286/**
11287 * Get document associated with the event target.
11288 *
11289 * @param {object} nativeEventTarget
11290 * @return {Document}
11291 */
11292
11293
11294function getEventTargetDocument(eventTarget) {
11295 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
11296}
11297/**
11298 * Poll selection to see whether it's changed.
11299 *
11300 * @param {object} nativeEvent
11301 * @param {object} nativeEventTarget
11302 * @return {?SyntheticEvent}
11303 */
11304
11305
11306function constructSelectEvent(nativeEvent, nativeEventTarget) {
11307 // Ensure we have the right element, and that the user is not dragging a
11308 // selection (this matches native `select` event behavior). In HTML5, select
11309 // fires only on input and textarea thus if there's no focused element we
11310 // won't dispatch.
11311 var doc = getEventTargetDocument(nativeEventTarget);
11312
11313 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
11314 return null;
11315 } // Only fire when selection has actually changed.
11316
11317
11318 var currentSelection = getSelection$1(activeElement$1);
11319
11320 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
11321 lastSelection = currentSelection;
11322 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$4.select, activeElementInst$1, nativeEvent, nativeEventTarget);
11323 syntheticEvent.type = 'select';
11324 syntheticEvent.target = activeElement$1;
11325 accumulateTwoPhaseDispatches(syntheticEvent);
11326 return syntheticEvent;
11327 }
11328
11329 return null;
11330}
11331/**
11332 * This plugin creates an `onSelect` event that normalizes select events
11333 * across form elements.
11334 *
11335 * Supported elements are:
11336 * - input (see `isTextInputElement`)
11337 * - textarea
11338 * - contentEditable
11339 *
11340 * This differs from native browser implementations in the following ways:
11341 * - Fires on contentEditable fields as well as inputs.
11342 * - Fires for collapsed selection.
11343 * - Fires after user input.
11344 */
11345
11346
11347var SelectEventPlugin = {
11348 eventTypes: eventTypes$4,
11349 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11350 var doc = getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
11351 // not extract events. See #3639.
11352
11353 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
11354 return null;
11355 }
11356
11357 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
11358
11359 switch (topLevelType) {
11360 // Track the input node that has focus.
11361 case TOP_FOCUS:
11362 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
11363 activeElement$1 = targetNode;
11364 activeElementInst$1 = targetInst;
11365 lastSelection = null;
11366 }
11367
11368 break;
11369
11370 case TOP_BLUR:
11371 activeElement$1 = null;
11372 activeElementInst$1 = null;
11373 lastSelection = null;
11374 break;
11375 // Don't fire the event while the user is dragging. This matches the
11376 // semantics of the native select event.
11377
11378 case TOP_MOUSE_DOWN:
11379 mouseDown = true;
11380 break;
11381
11382 case TOP_CONTEXT_MENU:
11383 case TOP_MOUSE_UP:
11384 case TOP_DRAG_END:
11385 mouseDown = false;
11386 return constructSelectEvent(nativeEvent, nativeEventTarget);
11387 // Chrome and IE fire non-standard event when selection is changed (and
11388 // sometimes when it hasn't). IE's event fires out of order with respect
11389 // to key and input events on deletion, so we discard it.
11390 //
11391 // Firefox doesn't support selectionchange, so check selection status
11392 // after each key entry. The selection changes after keydown and before
11393 // keyup, but we check on keydown as well in the case of holding down a
11394 // key, when multiple keydown events are fired but only one keyup is.
11395 // This is also our approach for IE handling, for the reason above.
11396
11397 case TOP_SELECTION_CHANGE:
11398 if (skipSelectionChangeEvent) {
11399 break;
11400 }
11401
11402 // falls through
11403
11404 case TOP_KEY_DOWN:
11405 case TOP_KEY_UP:
11406 return constructSelectEvent(nativeEvent, nativeEventTarget);
11407 }
11408
11409 return null;
11410 }
11411};
11412
11413/**
11414 * Inject modules for resolving DOM hierarchy and plugin ordering.
11415 */
11416
11417injection.injectEventPluginOrder(DOMEventPluginOrder);
11418setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
11419/**
11420 * Some important event plugins included by default (without having to require
11421 * them).
11422 */
11423
11424injection.injectEventPluginsByName({
11425 SimpleEventPlugin: SimpleEventPlugin,
11426 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
11427 ChangeEventPlugin: ChangeEventPlugin,
11428 SelectEventPlugin: SelectEventPlugin,
11429 BeforeInputEventPlugin: BeforeInputEventPlugin
11430});
11431
11432// Prefix measurements so that it's possible to filter them.
11433// Longer prefixes are hard to read in DevTools.
11434var reactEmoji = "\u269B";
11435var warningEmoji = "\u26D4";
11436var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.
11437// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
11438
11439var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
11440// Reusing `currentFiber` would be confusing for this because user code fiber
11441// can change during commit phase too, but we don't need to unwind it (since
11442// lifecycles in the commit phase don't resemble a tree).
11443
11444var currentPhase = null;
11445var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
11446// so we will keep track of it, and include it in the report.
11447// Track commits caused by cascading updates.
11448
11449var isCommitting = false;
11450var hasScheduledUpdateInCurrentCommit = false;
11451var hasScheduledUpdateInCurrentPhase = false;
11452var commitCountInCurrentWorkLoop = 0;
11453var effectCountInCurrentCommit = 0;
11454// to avoid stretch the commit phase with measurement overhead.
11455
11456var labelsInCurrentCommit = new Set();
11457
11458var formatMarkName = function (markName) {
11459 return reactEmoji + " " + markName;
11460};
11461
11462var formatLabel = function (label, warning) {
11463 var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
11464 var suffix = warning ? " Warning: " + warning : '';
11465 return "" + prefix + label + suffix;
11466};
11467
11468var beginMark = function (markName) {
11469 performance.mark(formatMarkName(markName));
11470};
11471
11472var clearMark = function (markName) {
11473 performance.clearMarks(formatMarkName(markName));
11474};
11475
11476var endMark = function (label, markName, warning) {
11477 var formattedMarkName = formatMarkName(markName);
11478 var formattedLabel = formatLabel(label, warning);
11479
11480 try {
11481 performance.measure(formattedLabel, formattedMarkName);
11482 } catch (err) {} // If previous mark was missing for some reason, this will throw.
11483 // This could only happen if React crashed in an unexpected place earlier.
11484 // Don't pile on with more errors.
11485 // Clear marks immediately to avoid growing buffer.
11486
11487
11488 performance.clearMarks(formattedMarkName);
11489 performance.clearMeasures(formattedLabel);
11490};
11491
11492var getFiberMarkName = function (label, debugID) {
11493 return label + " (#" + debugID + ")";
11494};
11495
11496var getFiberLabel = function (componentName, isMounted, phase) {
11497 if (phase === null) {
11498 // These are composite component total time measurements.
11499 return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
11500 } else {
11501 // Composite component methods.
11502 return componentName + "." + phase;
11503 }
11504};
11505
11506var beginFiberMark = function (fiber, phase) {
11507 var componentName = getComponentName(fiber.type) || 'Unknown';
11508 var debugID = fiber._debugID;
11509 var isMounted = fiber.alternate !== null;
11510 var label = getFiberLabel(componentName, isMounted, phase);
11511
11512 if (isCommitting && labelsInCurrentCommit.has(label)) {
11513 // During the commit phase, we don't show duplicate labels because
11514 // there is a fixed overhead for every measurement, and we don't
11515 // want to stretch the commit phase beyond necessary.
11516 return false;
11517 }
11518
11519 labelsInCurrentCommit.add(label);
11520 var markName = getFiberMarkName(label, debugID);
11521 beginMark(markName);
11522 return true;
11523};
11524
11525var clearFiberMark = function (fiber, phase) {
11526 var componentName = getComponentName(fiber.type) || 'Unknown';
11527 var debugID = fiber._debugID;
11528 var isMounted = fiber.alternate !== null;
11529 var label = getFiberLabel(componentName, isMounted, phase);
11530 var markName = getFiberMarkName(label, debugID);
11531 clearMark(markName);
11532};
11533
11534var endFiberMark = function (fiber, phase, warning) {
11535 var componentName = getComponentName(fiber.type) || 'Unknown';
11536 var debugID = fiber._debugID;
11537 var isMounted = fiber.alternate !== null;
11538 var label = getFiberLabel(componentName, isMounted, phase);
11539 var markName = getFiberMarkName(label, debugID);
11540 endMark(label, markName, warning);
11541};
11542
11543var shouldIgnoreFiber = function (fiber) {
11544 // Host components should be skipped in the timeline.
11545 // We could check typeof fiber.type, but does this work with RN?
11546 switch (fiber.tag) {
11547 case HostRoot:
11548 case HostComponent:
11549 case HostText:
11550 case HostPortal:
11551 case Fragment:
11552 case ContextProvider:
11553 case ContextConsumer:
11554 case Mode:
11555 return true;
11556
11557 default:
11558 return false;
11559 }
11560};
11561
11562var clearPendingPhaseMeasurement = function () {
11563 if (currentPhase !== null && currentPhaseFiber !== null) {
11564 clearFiberMark(currentPhaseFiber, currentPhase);
11565 }
11566
11567 currentPhaseFiber = null;
11568 currentPhase = null;
11569 hasScheduledUpdateInCurrentPhase = false;
11570};
11571
11572var pauseTimers = function () {
11573 // Stops all currently active measurements so that they can be resumed
11574 // if we continue in a later deferred loop from the same unit of work.
11575 var fiber = currentFiber;
11576
11577 while (fiber) {
11578 if (fiber._debugIsCurrentlyTiming) {
11579 endFiberMark(fiber, null, null);
11580 }
11581
11582 fiber = fiber.return;
11583 }
11584};
11585
11586var resumeTimersRecursively = function (fiber) {
11587 if (fiber.return !== null) {
11588 resumeTimersRecursively(fiber.return);
11589 }
11590
11591 if (fiber._debugIsCurrentlyTiming) {
11592 beginFiberMark(fiber, null);
11593 }
11594};
11595
11596var resumeTimers = function () {
11597 // Resumes all measurements that were active during the last deferred loop.
11598 if (currentFiber !== null) {
11599 resumeTimersRecursively(currentFiber);
11600 }
11601};
11602
11603function recordEffect() {
11604 if (enableUserTimingAPI) {
11605 effectCountInCurrentCommit++;
11606 }
11607}
11608function recordScheduleUpdate() {
11609 if (enableUserTimingAPI) {
11610 if (isCommitting) {
11611 hasScheduledUpdateInCurrentCommit = true;
11612 }
11613
11614 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
11615 hasScheduledUpdateInCurrentPhase = true;
11616 }
11617 }
11618}
11619
11620
11621function startWorkTimer(fiber) {
11622 if (enableUserTimingAPI) {
11623 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11624 return;
11625 } // If we pause, this is the fiber to unwind from.
11626
11627
11628 currentFiber = fiber;
11629
11630 if (!beginFiberMark(fiber, null)) {
11631 return;
11632 }
11633
11634 fiber._debugIsCurrentlyTiming = true;
11635 }
11636}
11637function cancelWorkTimer(fiber) {
11638 if (enableUserTimingAPI) {
11639 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11640 return;
11641 } // Remember we shouldn't complete measurement for this fiber.
11642 // Otherwise flamechart will be deep even for small updates.
11643
11644
11645 fiber._debugIsCurrentlyTiming = false;
11646 clearFiberMark(fiber, null);
11647 }
11648}
11649function stopWorkTimer(fiber) {
11650 if (enableUserTimingAPI) {
11651 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11652 return;
11653 } // If we pause, its parent is the fiber to unwind from.
11654
11655
11656 currentFiber = fiber.return;
11657
11658 if (!fiber._debugIsCurrentlyTiming) {
11659 return;
11660 }
11661
11662 fiber._debugIsCurrentlyTiming = false;
11663 endFiberMark(fiber, null, null);
11664 }
11665}
11666function stopFailedWorkTimer(fiber) {
11667 if (enableUserTimingAPI) {
11668 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11669 return;
11670 } // If we pause, its parent is the fiber to unwind from.
11671
11672
11673 currentFiber = fiber.return;
11674
11675 if (!fiber._debugIsCurrentlyTiming) {
11676 return;
11677 }
11678
11679 fiber._debugIsCurrentlyTiming = false;
11680 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
11681 endFiberMark(fiber, null, warning);
11682 }
11683}
11684function startPhaseTimer(fiber, phase) {
11685 if (enableUserTimingAPI) {
11686 if (!supportsUserTiming) {
11687 return;
11688 }
11689
11690 clearPendingPhaseMeasurement();
11691
11692 if (!beginFiberMark(fiber, phase)) {
11693 return;
11694 }
11695
11696 currentPhaseFiber = fiber;
11697 currentPhase = phase;
11698 }
11699}
11700function stopPhaseTimer() {
11701 if (enableUserTimingAPI) {
11702 if (!supportsUserTiming) {
11703 return;
11704 }
11705
11706 if (currentPhase !== null && currentPhaseFiber !== null) {
11707 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
11708 endFiberMark(currentPhaseFiber, currentPhase, warning);
11709 }
11710
11711 currentPhase = null;
11712 currentPhaseFiber = null;
11713 }
11714}
11715function startWorkLoopTimer(nextUnitOfWork) {
11716 if (enableUserTimingAPI) {
11717 currentFiber = nextUnitOfWork;
11718
11719 if (!supportsUserTiming) {
11720 return;
11721 }
11722
11723 commitCountInCurrentWorkLoop = 0; // This is top level call.
11724 // Any other measurements are performed within.
11725
11726 beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.
11727
11728 resumeTimers();
11729 }
11730}
11731function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
11732 if (enableUserTimingAPI) {
11733 if (!supportsUserTiming) {
11734 return;
11735 }
11736
11737 var warning = null;
11738
11739 if (interruptedBy !== null) {
11740 if (interruptedBy.tag === HostRoot) {
11741 warning = 'A top-level update interrupted the previous render';
11742 } else {
11743 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
11744 warning = "An update to " + componentName + " interrupted the previous render";
11745 }
11746 } else if (commitCountInCurrentWorkLoop > 1) {
11747 warning = 'There were cascading updates';
11748 }
11749
11750 commitCountInCurrentWorkLoop = 0;
11751 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.
11752
11753 pauseTimers();
11754 endMark(label, '(React Tree Reconciliation)', warning);
11755 }
11756}
11757function startCommitTimer() {
11758 if (enableUserTimingAPI) {
11759 if (!supportsUserTiming) {
11760 return;
11761 }
11762
11763 isCommitting = true;
11764 hasScheduledUpdateInCurrentCommit = false;
11765 labelsInCurrentCommit.clear();
11766 beginMark('(Committing Changes)');
11767 }
11768}
11769function stopCommitTimer() {
11770 if (enableUserTimingAPI) {
11771 if (!supportsUserTiming) {
11772 return;
11773 }
11774
11775 var warning = null;
11776
11777 if (hasScheduledUpdateInCurrentCommit) {
11778 warning = 'Lifecycle hook scheduled a cascading update';
11779 } else if (commitCountInCurrentWorkLoop > 0) {
11780 warning = 'Caused by a cascading update in earlier commit';
11781 }
11782
11783 hasScheduledUpdateInCurrentCommit = false;
11784 commitCountInCurrentWorkLoop++;
11785 isCommitting = false;
11786 labelsInCurrentCommit.clear();
11787 endMark('(Committing Changes)', '(Committing Changes)', warning);
11788 }
11789}
11790function startCommitSnapshotEffectsTimer() {
11791 if (enableUserTimingAPI) {
11792 if (!supportsUserTiming) {
11793 return;
11794 }
11795
11796 effectCountInCurrentCommit = 0;
11797 beginMark('(Committing Snapshot Effects)');
11798 }
11799}
11800function stopCommitSnapshotEffectsTimer() {
11801 if (enableUserTimingAPI) {
11802 if (!supportsUserTiming) {
11803 return;
11804 }
11805
11806 var count = effectCountInCurrentCommit;
11807 effectCountInCurrentCommit = 0;
11808 endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
11809 }
11810}
11811function startCommitHostEffectsTimer() {
11812 if (enableUserTimingAPI) {
11813 if (!supportsUserTiming) {
11814 return;
11815 }
11816
11817 effectCountInCurrentCommit = 0;
11818 beginMark('(Committing Host Effects)');
11819 }
11820}
11821function stopCommitHostEffectsTimer() {
11822 if (enableUserTimingAPI) {
11823 if (!supportsUserTiming) {
11824 return;
11825 }
11826
11827 var count = effectCountInCurrentCommit;
11828 effectCountInCurrentCommit = 0;
11829 endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
11830 }
11831}
11832function startCommitLifeCyclesTimer() {
11833 if (enableUserTimingAPI) {
11834 if (!supportsUserTiming) {
11835 return;
11836 }
11837
11838 effectCountInCurrentCommit = 0;
11839 beginMark('(Calling Lifecycle Methods)');
11840 }
11841}
11842function stopCommitLifeCyclesTimer() {
11843 if (enableUserTimingAPI) {
11844 if (!supportsUserTiming) {
11845 return;
11846 }
11847
11848 var count = effectCountInCurrentCommit;
11849 effectCountInCurrentCommit = 0;
11850 endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
11851 }
11852}
11853
11854var valueStack = [];
11855var fiberStack;
11856
11857{
11858 fiberStack = [];
11859}
11860
11861var index = -1;
11862
11863function createCursor(defaultValue) {
11864 return {
11865 current: defaultValue
11866 };
11867}
11868
11869function pop(cursor, fiber) {
11870 if (index < 0) {
11871 {
11872 warningWithoutStack$1(false, 'Unexpected pop.');
11873 }
11874
11875 return;
11876 }
11877
11878 {
11879 if (fiber !== fiberStack[index]) {
11880 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
11881 }
11882 }
11883
11884 cursor.current = valueStack[index];
11885 valueStack[index] = null;
11886
11887 {
11888 fiberStack[index] = null;
11889 }
11890
11891 index--;
11892}
11893
11894function push(cursor, value, fiber) {
11895 index++;
11896 valueStack[index] = cursor.current;
11897
11898 {
11899 fiberStack[index] = fiber;
11900 }
11901
11902 cursor.current = value;
11903}
11904
11905var warnedAboutMissingGetChildContext;
11906
11907{
11908 warnedAboutMissingGetChildContext = {};
11909}
11910
11911var emptyContextObject = {};
11912
11913{
11914 Object.freeze(emptyContextObject);
11915} // A cursor to the current merged context object on the stack.
11916
11917
11918var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
11919
11920var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
11921// We use this to get access to the parent context after we have already
11922// pushed the next context provider, and now need to merge their contexts.
11923
11924var previousContext = emptyContextObject;
11925
11926function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
11927 if (disableLegacyContext) {
11928 return emptyContextObject;
11929 } else {
11930 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
11931 // If the fiber is a context provider itself, when we read its context
11932 // we may have already pushed its own child context on the stack. A context
11933 // provider should not "see" its own child context. Therefore we read the
11934 // previous (parent) context instead for a context provider.
11935 return previousContext;
11936 }
11937
11938 return contextStackCursor.current;
11939 }
11940}
11941
11942function cacheContext(workInProgress, unmaskedContext, maskedContext) {
11943 if (disableLegacyContext) {
11944 return;
11945 } else {
11946 var instance = workInProgress.stateNode;
11947 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
11948 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
11949 }
11950}
11951
11952function getMaskedContext(workInProgress, unmaskedContext) {
11953 if (disableLegacyContext) {
11954 return emptyContextObject;
11955 } else {
11956 var type = workInProgress.type;
11957 var contextTypes = type.contextTypes;
11958
11959 if (!contextTypes) {
11960 return emptyContextObject;
11961 } // Avoid recreating masked context unless unmasked context has changed.
11962 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
11963 // This may trigger infinite loops if componentWillReceiveProps calls setState.
11964
11965
11966 var instance = workInProgress.stateNode;
11967
11968 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
11969 return instance.__reactInternalMemoizedMaskedChildContext;
11970 }
11971
11972 var context = {};
11973
11974 for (var key in contextTypes) {
11975 context[key] = unmaskedContext[key];
11976 }
11977
11978 {
11979 var name = getComponentName(type) || 'Unknown';
11980 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
11981 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
11982 // Context is created before the class component is instantiated so check for instance.
11983
11984
11985 if (instance) {
11986 cacheContext(workInProgress, unmaskedContext, context);
11987 }
11988
11989 return context;
11990 }
11991}
11992
11993function hasContextChanged() {
11994 if (disableLegacyContext) {
11995 return false;
11996 } else {
11997 return didPerformWorkStackCursor.current;
11998 }
11999}
12000
12001function isContextProvider(type) {
12002 if (disableLegacyContext) {
12003 return false;
12004 } else {
12005 var childContextTypes = type.childContextTypes;
12006 return childContextTypes !== null && childContextTypes !== undefined;
12007 }
12008}
12009
12010function popContext(fiber) {
12011 if (disableLegacyContext) {
12012 return;
12013 } else {
12014 pop(didPerformWorkStackCursor, fiber);
12015 pop(contextStackCursor, fiber);
12016 }
12017}
12018
12019function popTopLevelContextObject(fiber) {
12020 if (disableLegacyContext) {
12021 return;
12022 } else {
12023 pop(didPerformWorkStackCursor, fiber);
12024 pop(contextStackCursor, fiber);
12025 }
12026}
12027
12028function pushTopLevelContextObject(fiber, context, didChange) {
12029 if (disableLegacyContext) {
12030 return;
12031 } else {
12032 (function () {
12033 if (!(contextStackCursor.current === emptyContextObject)) {
12034 {
12035 throw ReactError(Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue."));
12036 }
12037 }
12038 })();
12039
12040 push(contextStackCursor, context, fiber);
12041 push(didPerformWorkStackCursor, didChange, fiber);
12042 }
12043}
12044
12045function processChildContext(fiber, type, parentContext) {
12046 if (disableLegacyContext) {
12047 return parentContext;
12048 } else {
12049 var instance = fiber.stateNode;
12050 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
12051 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
12052
12053 if (typeof instance.getChildContext !== 'function') {
12054 {
12055 var componentName = getComponentName(type) || 'Unknown';
12056
12057 if (!warnedAboutMissingGetChildContext[componentName]) {
12058 warnedAboutMissingGetChildContext[componentName] = true;
12059 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);
12060 }
12061 }
12062
12063 return parentContext;
12064 }
12065
12066 var childContext;
12067
12068 {
12069 setCurrentPhase('getChildContext');
12070 }
12071
12072 startPhaseTimer(fiber, 'getChildContext');
12073 childContext = instance.getChildContext();
12074 stopPhaseTimer();
12075
12076 {
12077 setCurrentPhase(null);
12078 }
12079
12080 for (var contextKey in childContext) {
12081 (function () {
12082 if (!(contextKey in childContextTypes)) {
12083 {
12084 throw ReactError(Error((getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."));
12085 }
12086 }
12087 })();
12088 }
12089
12090 {
12091 var name = getComponentName(type) || 'Unknown';
12092 checkPropTypes_1(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
12093 // somebody calls unstable_renderSubtreeIntoContainer() and we process
12094 // context from the parent component instance. The stack will be missing
12095 // because it's outside of the reconciliation, and so the pointer has not
12096 // been set. This is rare and doesn't matter. We'll also remove that API.
12097 getCurrentFiberStackInDev);
12098 }
12099
12100 return _assign({}, parentContext, {}, childContext);
12101 }
12102}
12103
12104function pushContextProvider(workInProgress) {
12105 if (disableLegacyContext) {
12106 return false;
12107 } else {
12108 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
12109 // If the instance does not exist yet, we will push null at first,
12110 // and replace it on the stack later when invalidating the context.
12111
12112 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
12113 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
12114
12115 previousContext = contextStackCursor.current;
12116 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
12117 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
12118 return true;
12119 }
12120}
12121
12122function invalidateContextProvider(workInProgress, type, didChange) {
12123 if (disableLegacyContext) {
12124 return;
12125 } else {
12126 var instance = workInProgress.stateNode;
12127
12128 (function () {
12129 if (!instance) {
12130 {
12131 throw ReactError(Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue."));
12132 }
12133 }
12134 })();
12135
12136 if (didChange) {
12137 // Merge parent and own context.
12138 // Skip this if we're not updating due to sCU.
12139 // This avoids unnecessarily recomputing memoized values.
12140 var mergedContext = processChildContext(workInProgress, type, previousContext);
12141 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
12142 // It is important to unwind the context in the reverse order.
12143
12144 pop(didPerformWorkStackCursor, workInProgress);
12145 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
12146
12147 push(contextStackCursor, mergedContext, workInProgress);
12148 push(didPerformWorkStackCursor, didChange, workInProgress);
12149 } else {
12150 pop(didPerformWorkStackCursor, workInProgress);
12151 push(didPerformWorkStackCursor, didChange, workInProgress);
12152 }
12153 }
12154}
12155
12156function findCurrentUnmaskedContext(fiber) {
12157 if (disableLegacyContext) {
12158 return emptyContextObject;
12159 } else {
12160 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
12161 // makes sense elsewhere
12162 (function () {
12163 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
12164 {
12165 throw ReactError(Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue."));
12166 }
12167 }
12168 })();
12169
12170 var node = fiber;
12171
12172 do {
12173 switch (node.tag) {
12174 case HostRoot:
12175 return node.stateNode.context;
12176
12177 case ClassComponent:
12178 {
12179 var Component = node.type;
12180
12181 if (isContextProvider(Component)) {
12182 return node.stateNode.__reactInternalMemoizedMergedChildContext;
12183 }
12184
12185 break;
12186 }
12187 }
12188
12189 node = node.return;
12190 } while (node !== null);
12191
12192 (function () {
12193 {
12194 {
12195 throw ReactError(Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue."));
12196 }
12197 }
12198 })();
12199 }
12200}
12201
12202var LegacyRoot = 0;
12203var BatchedRoot = 1;
12204var ConcurrentRoot = 2;
12205
12206var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
12207var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
12208var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
12209var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
12210var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
12211var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
12212var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
12213var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
12214var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
12215var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
12216var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
12217
12218// Intentionally not named imports because Rollup would use dynamic dispatch for
12219// CommonJS interop named imports.
12220var Scheduler_runWithPriority = unstable_runWithPriority;
12221var Scheduler_scheduleCallback = unstable_scheduleCallback;
12222var Scheduler_cancelCallback = unstable_cancelCallback;
12223var Scheduler_shouldYield = unstable_shouldYield;
12224var Scheduler_requestPaint = unstable_requestPaint;
12225var Scheduler_now = unstable_now;
12226var Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
12227var Scheduler_ImmediatePriority = unstable_ImmediatePriority;
12228var Scheduler_UserBlockingPriority = unstable_UserBlockingPriority;
12229var Scheduler_NormalPriority = unstable_NormalPriority;
12230var Scheduler_LowPriority = unstable_LowPriority;
12231var Scheduler_IdlePriority = unstable_IdlePriority;
12232
12233if (enableSchedulerTracing) {
12234 // Provide explicit error message when production+profiling bundle of e.g.
12235 // react-dom is used with production (non-profiling) bundle of
12236 // scheduler/tracing
12237 (function () {
12238 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
12239 {
12240 throw ReactError(Error("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"));
12241 }
12242 }
12243 })();
12244}
12245
12246var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
12247// ascending numbers so we can compare them like numbers. They start at 90 to
12248// avoid clashing with Scheduler's priorities.
12249
12250var ImmediatePriority = 99;
12251var UserBlockingPriority$2 = 98;
12252var NormalPriority = 97;
12253var LowPriority = 96;
12254var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
12255
12256var NoPriority = 90;
12257var shouldYield = Scheduler_shouldYield;
12258var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
12259Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
12260var syncQueue = null;
12261var immediateQueueCallbackNode = null;
12262var isFlushingSyncQueue = false;
12263var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
12264// This will be the case for modern browsers that support `performance.now`. In
12265// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
12266// timestamp. In that case, subtract the module initialization time to simulate
12267// the behavior of performance.now and keep our times small enough to fit
12268// within 32 bits.
12269// TODO: Consider lifting this into Scheduler.
12270
12271var now = initialTimeMs < 10000 ? Scheduler_now : function () {
12272 return Scheduler_now() - initialTimeMs;
12273};
12274function getCurrentPriorityLevel() {
12275 switch (Scheduler_getCurrentPriorityLevel()) {
12276 case Scheduler_ImmediatePriority:
12277 return ImmediatePriority;
12278
12279 case Scheduler_UserBlockingPriority:
12280 return UserBlockingPriority$2;
12281
12282 case Scheduler_NormalPriority:
12283 return NormalPriority;
12284
12285 case Scheduler_LowPriority:
12286 return LowPriority;
12287
12288 case Scheduler_IdlePriority:
12289 return IdlePriority;
12290
12291 default:
12292 (function () {
12293 {
12294 {
12295 throw ReactError(Error("Unknown priority level."));
12296 }
12297 }
12298 })();
12299
12300 }
12301}
12302
12303function reactPriorityToSchedulerPriority(reactPriorityLevel) {
12304 switch (reactPriorityLevel) {
12305 case ImmediatePriority:
12306 return Scheduler_ImmediatePriority;
12307
12308 case UserBlockingPriority$2:
12309 return Scheduler_UserBlockingPriority;
12310
12311 case NormalPriority:
12312 return Scheduler_NormalPriority;
12313
12314 case LowPriority:
12315 return Scheduler_LowPriority;
12316
12317 case IdlePriority:
12318 return Scheduler_IdlePriority;
12319
12320 default:
12321 (function () {
12322 {
12323 {
12324 throw ReactError(Error("Unknown priority level."));
12325 }
12326 }
12327 })();
12328
12329 }
12330}
12331
12332function runWithPriority$2(reactPriorityLevel, fn) {
12333 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12334 return Scheduler_runWithPriority(priorityLevel, fn);
12335}
12336function scheduleCallback(reactPriorityLevel, callback, options) {
12337 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12338 return Scheduler_scheduleCallback(priorityLevel, callback, options);
12339}
12340function scheduleSyncCallback(callback) {
12341 // Push this callback into an internal queue. We'll flush these either in
12342 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
12343 if (syncQueue === null) {
12344 syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
12345
12346 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
12347 } else {
12348 // Push onto existing queue. Don't need to schedule a callback because
12349 // we already scheduled one when we created the queue.
12350 syncQueue.push(callback);
12351 }
12352
12353 return fakeCallbackNode;
12354}
12355function cancelCallback(callbackNode) {
12356 if (callbackNode !== fakeCallbackNode) {
12357 Scheduler_cancelCallback(callbackNode);
12358 }
12359}
12360function flushSyncCallbackQueue() {
12361 if (immediateQueueCallbackNode !== null) {
12362 var node = immediateQueueCallbackNode;
12363 immediateQueueCallbackNode = null;
12364 Scheduler_cancelCallback(node);
12365 }
12366
12367 flushSyncCallbackQueueImpl();
12368}
12369
12370function flushSyncCallbackQueueImpl() {
12371 if (!isFlushingSyncQueue && syncQueue !== null) {
12372 // Prevent re-entrancy.
12373 isFlushingSyncQueue = true;
12374 var i = 0;
12375
12376 try {
12377 var _isSync = true;
12378 var queue = syncQueue;
12379 runWithPriority$2(ImmediatePriority, function () {
12380 for (; i < queue.length; i++) {
12381 var callback = queue[i];
12382
12383 do {
12384 callback = callback(_isSync);
12385 } while (callback !== null);
12386 }
12387 });
12388 syncQueue = null;
12389 } catch (error) {
12390 // If something throws, leave the remaining callbacks on the queue.
12391 if (syncQueue !== null) {
12392 syncQueue = syncQueue.slice(i + 1);
12393 } // Resume flushing in the next tick
12394
12395
12396 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
12397 throw error;
12398 } finally {
12399 isFlushingSyncQueue = false;
12400 }
12401 }
12402}
12403
12404var NoMode = 0;
12405var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root
12406// tag instead
12407
12408var BatchedMode = 2;
12409var ConcurrentMode = 4;
12410var ProfileMode = 8;
12411
12412// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
12413// Math.pow(2, 30) - 1
12414// 0b111111111111111111111111111111
12415var MAX_SIGNED_31_BIT_INT = 1073741823;
12416
12417var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
12418// Never work can be committed in an inconsistent state without tearing the UI.
12419// The main example is offscreen content, like a hidden subtree. So one possible
12420// name is Offscreen. However, it also includes dehydrated Suspense boundaries,
12421// which are inconsistent in the sense that they haven't finished yet, but
12422// aren't visibly inconsistent because the server rendered HTML matches what the
12423// hydrated tree would look like.
12424
12425var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
12426// order to be consistent.
12427
12428var Idle = 2;
12429var Sync = MAX_SIGNED_31_BIT_INT;
12430var Batched = Sync - 1;
12431var UNIT_SIZE = 10;
12432var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.
12433
12434function msToExpirationTime(ms) {
12435 // Always add an offset so that we don't clash with the magic number for NoWork.
12436 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
12437}
12438function expirationTimeToMs(expirationTime) {
12439 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
12440}
12441
12442function ceiling(num, precision) {
12443 return ((num / precision | 0) + 1) * precision;
12444}
12445
12446function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
12447 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
12448} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
12449// the names to reflect.
12450
12451
12452var LOW_PRIORITY_EXPIRATION = 5000;
12453var LOW_PRIORITY_BATCH_SIZE = 250;
12454function computeAsyncExpiration(currentTime) {
12455 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
12456}
12457function computeSuspenseExpiration(currentTime, timeoutMs) {
12458 // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
12459 return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
12460} // We intentionally set a higher expiration time for interactive updates in
12461// dev than in production.
12462//
12463// If the main thread is being blocked so long that you hit the expiration,
12464// it's a problem that could be solved with better scheduling.
12465//
12466// People will be more likely to notice this and fix it with the long
12467// expiration time in development.
12468//
12469// In production we opt for better UX at the risk of masking scheduling
12470// problems, by expiring fast.
12471
12472var HIGH_PRIORITY_EXPIRATION = 500;
12473var HIGH_PRIORITY_BATCH_SIZE = 100;
12474function computeInteractiveExpiration(currentTime) {
12475 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
12476}
12477function inferPriorityFromExpirationTime(currentTime, expirationTime) {
12478 if (expirationTime === Sync) {
12479 return ImmediatePriority;
12480 }
12481
12482 if (expirationTime === Never || expirationTime === Idle) {
12483 return IdlePriority;
12484 }
12485
12486 var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);
12487
12488 if (msUntil <= 0) {
12489 return ImmediatePriority;
12490 }
12491
12492 if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
12493 return UserBlockingPriority$2;
12494 }
12495
12496 if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
12497 return NormalPriority;
12498 } // TODO: Handle LowPriority
12499 // Assume anything lower has idle priority
12500
12501
12502 return IdlePriority;
12503}
12504
12505/**
12506 * Forked from fbjs/warning:
12507 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
12508 *
12509 * Only change is we use console.warn instead of console.error,
12510 * and do nothing when 'console' is not supported.
12511 * This really simplifies the code.
12512 * ---
12513 * Similar to invariant but only logs a warning if the condition is not met.
12514 * This can be used to log issues in development environments in critical
12515 * paths. Removing the logging code for production environments will keep the
12516 * same logic and follow the same code paths.
12517 */
12518var lowPriorityWarningWithoutStack = function () {};
12519
12520{
12521 var printWarning$1 = function (format) {
12522 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
12523 args[_key - 1] = arguments[_key];
12524 }
12525
12526 var argIndex = 0;
12527 var message = 'Warning: ' + format.replace(/%s/g, function () {
12528 return args[argIndex++];
12529 });
12530
12531 if (typeof console !== 'undefined') {
12532 console.warn(message);
12533 }
12534
12535 try {
12536 // --- Welcome to debugging React ---
12537 // This error was thrown as a convenience so that you can use this stack
12538 // to find the callsite that caused this warning to fire.
12539 throw new Error(message);
12540 } catch (x) {}
12541 };
12542
12543 lowPriorityWarningWithoutStack = function (condition, format) {
12544 if (format === undefined) {
12545 throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
12546 }
12547
12548 if (!condition) {
12549 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
12550 args[_key2 - 2] = arguments[_key2];
12551 }
12552
12553 printWarning$1.apply(void 0, [format].concat(args));
12554 }
12555 };
12556}
12557
12558var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
12559
12560var ReactStrictModeWarnings = {
12561 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
12562 flushPendingUnsafeLifecycleWarnings: function () {},
12563 recordLegacyContextWarning: function (fiber, instance) {},
12564 flushLegacyContextWarning: function () {},
12565 discardPendingWarnings: function () {}
12566};
12567
12568{
12569 var findStrictRoot = function (fiber) {
12570 var maybeStrictRoot = null;
12571 var node = fiber;
12572
12573 while (node !== null) {
12574 if (node.mode & StrictMode) {
12575 maybeStrictRoot = node;
12576 }
12577
12578 node = node.return;
12579 }
12580
12581 return maybeStrictRoot;
12582 };
12583
12584 var setToSortedString = function (set) {
12585 var array = [];
12586 set.forEach(function (value) {
12587 array.push(value);
12588 });
12589 return array.sort().join(', ');
12590 };
12591
12592 var pendingComponentWillMountWarnings = [];
12593 var pendingUNSAFE_ComponentWillMountWarnings = [];
12594 var pendingComponentWillReceivePropsWarnings = [];
12595 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12596 var pendingComponentWillUpdateWarnings = [];
12597 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
12598
12599 var didWarnAboutUnsafeLifecycles = new Set();
12600
12601 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
12602 // Dedup strategy: Warn once per component.
12603 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
12604 return;
12605 }
12606
12607 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
12608 instance.componentWillMount.__suppressDeprecationWarning !== true) {
12609 pendingComponentWillMountWarnings.push(fiber);
12610 }
12611
12612 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
12613 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
12614 }
12615
12616 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12617 pendingComponentWillReceivePropsWarnings.push(fiber);
12618 }
12619
12620 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12621 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
12622 }
12623
12624 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12625 pendingComponentWillUpdateWarnings.push(fiber);
12626 }
12627
12628 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
12629 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
12630 }
12631 };
12632
12633 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
12634 // We do an initial pass to gather component names
12635 var componentWillMountUniqueNames = new Set();
12636
12637 if (pendingComponentWillMountWarnings.length > 0) {
12638 pendingComponentWillMountWarnings.forEach(function (fiber) {
12639 componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12640 didWarnAboutUnsafeLifecycles.add(fiber.type);
12641 });
12642 pendingComponentWillMountWarnings = [];
12643 }
12644
12645 var UNSAFE_componentWillMountUniqueNames = new Set();
12646
12647 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
12648 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
12649 UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12650 didWarnAboutUnsafeLifecycles.add(fiber.type);
12651 });
12652 pendingUNSAFE_ComponentWillMountWarnings = [];
12653 }
12654
12655 var componentWillReceivePropsUniqueNames = new Set();
12656
12657 if (pendingComponentWillReceivePropsWarnings.length > 0) {
12658 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
12659 componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12660 didWarnAboutUnsafeLifecycles.add(fiber.type);
12661 });
12662 pendingComponentWillReceivePropsWarnings = [];
12663 }
12664
12665 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
12666
12667 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
12668 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
12669 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12670 didWarnAboutUnsafeLifecycles.add(fiber.type);
12671 });
12672 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12673 }
12674
12675 var componentWillUpdateUniqueNames = new Set();
12676
12677 if (pendingComponentWillUpdateWarnings.length > 0) {
12678 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
12679 componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12680 didWarnAboutUnsafeLifecycles.add(fiber.type);
12681 });
12682 pendingComponentWillUpdateWarnings = [];
12683 }
12684
12685 var UNSAFE_componentWillUpdateUniqueNames = new Set();
12686
12687 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
12688 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
12689 UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12690 didWarnAboutUnsafeLifecycles.add(fiber.type);
12691 });
12692 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12693 } // Finally, we flush all the warnings
12694 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
12695
12696
12697 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
12698 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
12699 warningWithoutStack$1(false, 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
12700 }
12701
12702 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
12703 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
12704
12705 warningWithoutStack$1(false, 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
12706 }
12707
12708 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
12709 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
12710
12711 warningWithoutStack$1(false, 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
12712 }
12713
12714 if (componentWillMountUniqueNames.size > 0) {
12715 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
12716
12717 lowPriorityWarningWithoutStack$1(false, 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
12718 }
12719
12720 if (componentWillReceivePropsUniqueNames.size > 0) {
12721 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
12722
12723 lowPriorityWarningWithoutStack$1(false, 'componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
12724 }
12725
12726 if (componentWillUpdateUniqueNames.size > 0) {
12727 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
12728
12729 lowPriorityWarningWithoutStack$1(false, 'componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
12730 }
12731 };
12732
12733 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
12734
12735 var didWarnAboutLegacyContext = new Set();
12736
12737 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
12738 var strictRoot = findStrictRoot(fiber);
12739
12740 if (strictRoot === null) {
12741 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.');
12742 return;
12743 } // Dedup strategy: Warn once per component.
12744
12745
12746 if (didWarnAboutLegacyContext.has(fiber.type)) {
12747 return;
12748 }
12749
12750 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
12751
12752 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
12753 if (warningsForRoot === undefined) {
12754 warningsForRoot = [];
12755 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
12756 }
12757
12758 warningsForRoot.push(fiber);
12759 }
12760 };
12761
12762 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
12763 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
12764 var uniqueNames = new Set();
12765 fiberArray.forEach(function (fiber) {
12766 uniqueNames.add(getComponentName(fiber.type) || 'Component');
12767 didWarnAboutLegacyContext.add(fiber.type);
12768 });
12769 var sortedNames = setToSortedString(uniqueNames);
12770 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
12771 warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, strictRootComponentStack);
12772 });
12773 };
12774
12775 ReactStrictModeWarnings.discardPendingWarnings = function () {
12776 pendingComponentWillMountWarnings = [];
12777 pendingUNSAFE_ComponentWillMountWarnings = [];
12778 pendingComponentWillReceivePropsWarnings = [];
12779 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12780 pendingComponentWillUpdateWarnings = [];
12781 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12782 pendingLegacyContextWarning = new Map();
12783 };
12784}
12785
12786var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
12787
12788var failedBoundaries = null;
12789var setRefreshHandler = function (handler) {
12790 {
12791 resolveFamily = handler;
12792 }
12793};
12794function resolveFunctionForHotReloading(type) {
12795 {
12796 if (resolveFamily === null) {
12797 // Hot reloading is disabled.
12798 return type;
12799 }
12800
12801 var family = resolveFamily(type);
12802
12803 if (family === undefined) {
12804 return type;
12805 } // Use the latest known implementation.
12806
12807
12808 return family.current;
12809 }
12810}
12811function resolveClassForHotReloading(type) {
12812 // No implementation differences.
12813 return resolveFunctionForHotReloading(type);
12814}
12815function resolveForwardRefForHotReloading(type) {
12816 {
12817 if (resolveFamily === null) {
12818 // Hot reloading is disabled.
12819 return type;
12820 }
12821
12822 var family = resolveFamily(type);
12823
12824 if (family === undefined) {
12825 // Check if we're dealing with a real forwardRef. Don't want to crash early.
12826 if (type !== null && type !== undefined && typeof type.render === 'function') {
12827 // ForwardRef is special because its resolved .type is an object,
12828 // but it's possible that we only have its inner render function in the map.
12829 // If that inner render function is different, we'll build a new forwardRef type.
12830 var currentRender = resolveFunctionForHotReloading(type.render);
12831
12832 if (type.render !== currentRender) {
12833 var syntheticType = {
12834 $$typeof: REACT_FORWARD_REF_TYPE,
12835 render: currentRender
12836 };
12837
12838 if (type.displayName !== undefined) {
12839 syntheticType.displayName = type.displayName;
12840 }
12841
12842 return syntheticType;
12843 }
12844 }
12845
12846 return type;
12847 } // Use the latest known implementation.
12848
12849
12850 return family.current;
12851 }
12852}
12853function isCompatibleFamilyForHotReloading(fiber, element) {
12854 {
12855 if (resolveFamily === null) {
12856 // Hot reloading is disabled.
12857 return false;
12858 }
12859
12860 var prevType = fiber.elementType;
12861 var nextType = element.type; // If we got here, we know types aren't === equal.
12862
12863 var needsCompareFamilies = false;
12864 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
12865
12866 switch (fiber.tag) {
12867 case ClassComponent:
12868 {
12869 if (typeof nextType === 'function') {
12870 needsCompareFamilies = true;
12871 }
12872
12873 break;
12874 }
12875
12876 case FunctionComponent:
12877 {
12878 if (typeof nextType === 'function') {
12879 needsCompareFamilies = true;
12880 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12881 // We don't know the inner type yet.
12882 // We're going to assume that the lazy inner type is stable,
12883 // and so it is sufficient to avoid reconciling it away.
12884 // We're not going to unwrap or actually use the new lazy type.
12885 needsCompareFamilies = true;
12886 }
12887
12888 break;
12889 }
12890
12891 case ForwardRef:
12892 {
12893 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
12894 needsCompareFamilies = true;
12895 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12896 needsCompareFamilies = true;
12897 }
12898
12899 break;
12900 }
12901
12902 case MemoComponent:
12903 case SimpleMemoComponent:
12904 {
12905 if ($$typeofNextType === REACT_MEMO_TYPE) {
12906 // TODO: if it was but can no longer be simple,
12907 // we shouldn't set this.
12908 needsCompareFamilies = true;
12909 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12910 needsCompareFamilies = true;
12911 }
12912
12913 break;
12914 }
12915
12916 default:
12917 return false;
12918 } // Check if both types have a family and it's the same one.
12919
12920
12921 if (needsCompareFamilies) {
12922 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
12923 // This means both of them need to be registered to preserve state.
12924 // If we unwrapped and compared the inner types for wrappers instead,
12925 // then we would risk falsely saying two separate memo(Foo)
12926 // calls are equivalent because they wrap the same Foo function.
12927 var prevFamily = resolveFamily(prevType);
12928
12929 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
12930 return true;
12931 }
12932 }
12933
12934 return false;
12935 }
12936}
12937function markFailedErrorBoundaryForHotReloading(fiber) {
12938 {
12939 if (resolveFamily === null) {
12940 // Hot reloading is disabled.
12941 return;
12942 }
12943
12944 if (typeof WeakSet !== 'function') {
12945 return;
12946 }
12947
12948 if (failedBoundaries === null) {
12949 failedBoundaries = new WeakSet();
12950 }
12951
12952 failedBoundaries.add(fiber);
12953 }
12954}
12955var scheduleRefresh = function (root, update) {
12956 {
12957 if (resolveFamily === null) {
12958 // Hot reloading is disabled.
12959 return;
12960 }
12961
12962 var staleFamilies = update.staleFamilies,
12963 updatedFamilies = update.updatedFamilies;
12964 flushPassiveEffects();
12965 flushSync(function () {
12966 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
12967 });
12968 }
12969};
12970var scheduleRoot = function (root, element) {
12971 {
12972 if (root.context !== emptyContextObject) {
12973 // Super edge case: root has a legacy _renderSubtree context
12974 // but we don't know the parentComponent so we can't pass it.
12975 // Just ignore. We'll delete this with _renderSubtree code path later.
12976 return;
12977 }
12978
12979 flushPassiveEffects();
12980 updateContainerAtExpirationTime(element, root, null, Sync, null);
12981 }
12982};
12983
12984function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
12985 {
12986 var alternate = fiber.alternate,
12987 child = fiber.child,
12988 sibling = fiber.sibling,
12989 tag = fiber.tag,
12990 type = fiber.type;
12991 var candidateType = null;
12992
12993 switch (tag) {
12994 case FunctionComponent:
12995 case SimpleMemoComponent:
12996 case ClassComponent:
12997 candidateType = type;
12998 break;
12999
13000 case ForwardRef:
13001 candidateType = type.render;
13002 break;
13003
13004 default:
13005 break;
13006 }
13007
13008 if (resolveFamily === null) {
13009 throw new Error('Expected resolveFamily to be set during hot reload.');
13010 }
13011
13012 var needsRender = false;
13013 var needsRemount = false;
13014
13015 if (candidateType !== null) {
13016 var family = resolveFamily(candidateType);
13017
13018 if (family !== undefined) {
13019 if (staleFamilies.has(family)) {
13020 needsRemount = true;
13021 } else if (updatedFamilies.has(family)) {
13022 if (tag === ClassComponent) {
13023 needsRemount = true;
13024 } else {
13025 needsRender = true;
13026 }
13027 }
13028 }
13029 }
13030
13031 if (failedBoundaries !== null) {
13032 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
13033 needsRemount = true;
13034 }
13035 }
13036
13037 if (needsRemount) {
13038 fiber._debugNeedsRemount = true;
13039 }
13040
13041 if (needsRemount || needsRender) {
13042 scheduleWork(fiber, Sync);
13043 }
13044
13045 if (child !== null && !needsRemount) {
13046 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
13047 }
13048
13049 if (sibling !== null) {
13050 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
13051 }
13052 }
13053}
13054
13055var findHostInstancesForRefresh = function (root, families) {
13056 {
13057 var hostInstances = new Set();
13058 var types = new Set(families.map(function (family) {
13059 return family.current;
13060 }));
13061 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
13062 return hostInstances;
13063 }
13064};
13065
13066function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
13067 {
13068 var child = fiber.child,
13069 sibling = fiber.sibling,
13070 tag = fiber.tag,
13071 type = fiber.type;
13072 var candidateType = null;
13073
13074 switch (tag) {
13075 case FunctionComponent:
13076 case SimpleMemoComponent:
13077 case ClassComponent:
13078 candidateType = type;
13079 break;
13080
13081 case ForwardRef:
13082 candidateType = type.render;
13083 break;
13084
13085 default:
13086 break;
13087 }
13088
13089 var didMatch = false;
13090
13091 if (candidateType !== null) {
13092 if (types.has(candidateType)) {
13093 didMatch = true;
13094 }
13095 }
13096
13097 if (didMatch) {
13098 // We have a match. This only drills down to the closest host components.
13099 // There's no need to search deeper because for the purpose of giving
13100 // visual feedback, "flashing" outermost parent rectangles is sufficient.
13101 findHostInstancesForFiberShallowly(fiber, hostInstances);
13102 } else {
13103 // If there's no match, maybe there will be one further down in the child tree.
13104 if (child !== null) {
13105 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
13106 }
13107 }
13108
13109 if (sibling !== null) {
13110 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
13111 }
13112 }
13113}
13114
13115function findHostInstancesForFiberShallowly(fiber, hostInstances) {
13116 {
13117 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
13118
13119 if (foundHostInstances) {
13120 return;
13121 } // If we didn't find any host children, fallback to closest host parent.
13122
13123
13124 var node = fiber;
13125
13126 while (true) {
13127 switch (node.tag) {
13128 case HostComponent:
13129 hostInstances.add(node.stateNode);
13130 return;
13131
13132 case HostPortal:
13133 hostInstances.add(node.stateNode.containerInfo);
13134 return;
13135
13136 case HostRoot:
13137 hostInstances.add(node.stateNode.containerInfo);
13138 return;
13139 }
13140
13141 if (node.return === null) {
13142 throw new Error('Expected to reach root first.');
13143 }
13144
13145 node = node.return;
13146 }
13147 }
13148}
13149
13150function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
13151 {
13152 var node = fiber;
13153 var foundHostInstances = false;
13154
13155 while (true) {
13156 if (node.tag === HostComponent) {
13157 // We got a match.
13158 foundHostInstances = true;
13159 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
13160 } else if (node.child !== null) {
13161 node.child.return = node;
13162 node = node.child;
13163 continue;
13164 }
13165
13166 if (node === fiber) {
13167 return foundHostInstances;
13168 }
13169
13170 while (node.sibling === null) {
13171 if (node.return === null || node.return === fiber) {
13172 return foundHostInstances;
13173 }
13174
13175 node = node.return;
13176 }
13177
13178 node.sibling.return = node.return;
13179 node = node.sibling;
13180 }
13181 }
13182
13183 return false;
13184}
13185
13186function resolveDefaultProps(Component, baseProps) {
13187 if (Component && Component.defaultProps) {
13188 // Resolve default props. Taken from ReactElement
13189 var props = _assign({}, baseProps);
13190
13191 var defaultProps = Component.defaultProps;
13192
13193 for (var propName in defaultProps) {
13194 if (props[propName] === undefined) {
13195 props[propName] = defaultProps[propName];
13196 }
13197 }
13198
13199 return props;
13200 }
13201
13202 return baseProps;
13203}
13204function readLazyComponentType(lazyComponent) {
13205 initializeLazyComponentType(lazyComponent);
13206
13207 if (lazyComponent._status !== Resolved) {
13208 throw lazyComponent._result;
13209 }
13210
13211 return lazyComponent._result;
13212}
13213
13214var valueCursor = createCursor(null);
13215var rendererSigil;
13216
13217{
13218 // Use this to detect multiple renderers using the same context
13219 rendererSigil = {};
13220}
13221
13222var currentlyRenderingFiber = null;
13223var lastContextDependency = null;
13224var lastContextWithAllBitsObserved = null;
13225var isDisallowedContextReadInDEV = false;
13226function resetContextDependencies() {
13227 // This is called right before React yields execution, to ensure `readContext`
13228 // cannot be called outside the render phase.
13229 currentlyRenderingFiber = null;
13230 lastContextDependency = null;
13231 lastContextWithAllBitsObserved = null;
13232
13233 {
13234 isDisallowedContextReadInDEV = false;
13235 }
13236}
13237function enterDisallowedContextReadInDEV() {
13238 {
13239 isDisallowedContextReadInDEV = true;
13240 }
13241}
13242function exitDisallowedContextReadInDEV() {
13243 {
13244 isDisallowedContextReadInDEV = false;
13245 }
13246}
13247function pushProvider(providerFiber, nextValue) {
13248 var context = providerFiber.type._context;
13249
13250 if (isPrimaryRenderer) {
13251 push(valueCursor, context._currentValue, providerFiber);
13252 context._currentValue = nextValue;
13253
13254 {
13255 !(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;
13256 context._currentRenderer = rendererSigil;
13257 }
13258 } else {
13259 push(valueCursor, context._currentValue2, providerFiber);
13260 context._currentValue2 = nextValue;
13261
13262 {
13263 !(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;
13264 context._currentRenderer2 = rendererSigil;
13265 }
13266 }
13267}
13268function popProvider(providerFiber) {
13269 var currentValue = valueCursor.current;
13270 pop(valueCursor, providerFiber);
13271 var context = providerFiber.type._context;
13272
13273 if (isPrimaryRenderer) {
13274 context._currentValue = currentValue;
13275 } else {
13276 context._currentValue2 = currentValue;
13277 }
13278}
13279function calculateChangedBits(context, newValue, oldValue) {
13280 if (is$1(oldValue, newValue)) {
13281 // No change
13282 return 0;
13283 } else {
13284 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
13285
13286 {
13287 !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
13288 }
13289
13290 return changedBits | 0;
13291 }
13292}
13293function scheduleWorkOnParentPath(parent, renderExpirationTime) {
13294 // Update the child expiration time of all the ancestors, including
13295 // the alternates.
13296 var node = parent;
13297
13298 while (node !== null) {
13299 var alternate = node.alternate;
13300
13301 if (node.childExpirationTime < renderExpirationTime) {
13302 node.childExpirationTime = renderExpirationTime;
13303
13304 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13305 alternate.childExpirationTime = renderExpirationTime;
13306 }
13307 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13308 alternate.childExpirationTime = renderExpirationTime;
13309 } else {
13310 // Neither alternate was updated, which means the rest of the
13311 // ancestor path already has sufficient priority.
13312 break;
13313 }
13314
13315 node = node.return;
13316 }
13317}
13318function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
13319 var fiber = workInProgress.child;
13320
13321 if (fiber !== null) {
13322 // Set the return pointer of the child to the work-in-progress fiber.
13323 fiber.return = workInProgress;
13324 }
13325
13326 while (fiber !== null) {
13327 var nextFiber = void 0; // Visit this fiber.
13328
13329 var list = fiber.dependencies;
13330
13331 if (list !== null) {
13332 nextFiber = fiber.child;
13333 var dependency = list.firstContext;
13334
13335 while (dependency !== null) {
13336 // Check if the context matches.
13337 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
13338 // Match! Schedule an update on this fiber.
13339 if (fiber.tag === ClassComponent) {
13340 // Schedule a force update on the work-in-progress.
13341 var update = createUpdate(renderExpirationTime, null);
13342 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
13343 // update to the current fiber, too, which means it will persist even if
13344 // this render is thrown away. Since it's a race condition, not sure it's
13345 // worth fixing.
13346
13347 enqueueUpdate(fiber, update);
13348 }
13349
13350 if (fiber.expirationTime < renderExpirationTime) {
13351 fiber.expirationTime = renderExpirationTime;
13352 }
13353
13354 var alternate = fiber.alternate;
13355
13356 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
13357 alternate.expirationTime = renderExpirationTime;
13358 }
13359
13360 scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.
13361
13362 if (list.expirationTime < renderExpirationTime) {
13363 list.expirationTime = renderExpirationTime;
13364 } // Since we already found a match, we can stop traversing the
13365 // dependency list.
13366
13367
13368 break;
13369 }
13370
13371 dependency = dependency.next;
13372 }
13373 } else if (fiber.tag === ContextProvider) {
13374 // Don't scan deeper if this is a matching provider
13375 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
13376 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedFragment) {
13377 // If a dehydrated suspense bounudary is in this subtree, we don't know
13378 // if it will have any context consumers in it. The best we can do is
13379 // mark it as having updates.
13380 var parentSuspense = fiber.return;
13381
13382 (function () {
13383 if (!(parentSuspense !== null)) {
13384 {
13385 throw ReactError(Error("We just came from a parent so we must have had a parent. This is a bug in React."));
13386 }
13387 }
13388 })();
13389
13390 if (parentSuspense.expirationTime < renderExpirationTime) {
13391 parentSuspense.expirationTime = renderExpirationTime;
13392 }
13393
13394 var _alternate = parentSuspense.alternate;
13395
13396 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
13397 _alternate.expirationTime = renderExpirationTime;
13398 } // This is intentionally passing this fiber as the parent
13399 // because we want to schedule this fiber as having work
13400 // on its children. We'll use the childExpirationTime on
13401 // this fiber to indicate that a context has changed.
13402
13403
13404 scheduleWorkOnParentPath(parentSuspense, renderExpirationTime);
13405 nextFiber = fiber.sibling;
13406 } else {
13407 // Traverse down.
13408 nextFiber = fiber.child;
13409 }
13410
13411 if (nextFiber !== null) {
13412 // Set the return pointer of the child to the work-in-progress fiber.
13413 nextFiber.return = fiber;
13414 } else {
13415 // No child. Traverse to next sibling.
13416 nextFiber = fiber;
13417
13418 while (nextFiber !== null) {
13419 if (nextFiber === workInProgress) {
13420 // We're back to the root of this subtree. Exit.
13421 nextFiber = null;
13422 break;
13423 }
13424
13425 var sibling = nextFiber.sibling;
13426
13427 if (sibling !== null) {
13428 // Set the return pointer of the sibling to the work-in-progress fiber.
13429 sibling.return = nextFiber.return;
13430 nextFiber = sibling;
13431 break;
13432 } // No more siblings. Traverse up.
13433
13434
13435 nextFiber = nextFiber.return;
13436 }
13437 }
13438
13439 fiber = nextFiber;
13440 }
13441}
13442function prepareToReadContext(workInProgress, renderExpirationTime) {
13443 currentlyRenderingFiber = workInProgress;
13444 lastContextDependency = null;
13445 lastContextWithAllBitsObserved = null;
13446 var dependencies = workInProgress.dependencies;
13447
13448 if (dependencies !== null) {
13449 var firstContext = dependencies.firstContext;
13450
13451 if (firstContext !== null) {
13452 if (dependencies.expirationTime >= renderExpirationTime) {
13453 // Context list has a pending update. Mark that this fiber performed work.
13454 markWorkInProgressReceivedUpdate();
13455 } // Reset the work-in-progress list
13456
13457
13458 dependencies.firstContext = null;
13459 }
13460 }
13461}
13462function readContext(context, observedBits) {
13463 {
13464 // This warning would fire if you read context inside a Hook like useMemo.
13465 // Unlike the class check below, it's not enforced in production for perf.
13466 !!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;
13467 }
13468
13469 if (lastContextWithAllBitsObserved === context) {// Nothing to do. We already observe everything in this context.
13470 } else if (observedBits === false || observedBits === 0) {// Do not observe any updates.
13471 } else {
13472 var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
13473
13474 if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
13475 // Observe all updates.
13476 lastContextWithAllBitsObserved = context;
13477 resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
13478 } else {
13479 resolvedObservedBits = observedBits;
13480 }
13481
13482 var contextItem = {
13483 context: context,
13484 observedBits: resolvedObservedBits,
13485 next: null
13486 };
13487
13488 if (lastContextDependency === null) {
13489 (function () {
13490 if (!(currentlyRenderingFiber !== null)) {
13491 {
13492 throw ReactError(Error("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()."));
13493 }
13494 }
13495 })(); // This is the first dependency for this component. Create a new list.
13496
13497
13498 lastContextDependency = contextItem;
13499 currentlyRenderingFiber.dependencies = {
13500 expirationTime: NoWork,
13501 firstContext: contextItem,
13502 responders: null
13503 };
13504 } else {
13505 // Append a new context item.
13506 lastContextDependency = lastContextDependency.next = contextItem;
13507 }
13508 }
13509
13510 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
13511}
13512
13513// UpdateQueue is a linked list of prioritized updates.
13514//
13515// Like fibers, update queues come in pairs: a current queue, which represents
13516// the visible state of the screen, and a work-in-progress queue, which can be
13517// mutated and processed asynchronously before it is committed — a form of
13518// double buffering. If a work-in-progress render is discarded before finishing,
13519// we create a new work-in-progress by cloning the current queue.
13520//
13521// Both queues share a persistent, singly-linked list structure. To schedule an
13522// update, we append it to the end of both queues. Each queue maintains a
13523// pointer to first update in the persistent list that hasn't been processed.
13524// The work-in-progress pointer always has a position equal to or greater than
13525// the current queue, since we always work on that one. The current queue's
13526// pointer is only updated during the commit phase, when we swap in the
13527// work-in-progress.
13528//
13529// For example:
13530//
13531// Current pointer: A - B - C - D - E - F
13532// Work-in-progress pointer: D - E - F
13533// ^
13534// The work-in-progress queue has
13535// processed more updates than current.
13536//
13537// The reason we append to both queues is because otherwise we might drop
13538// updates without ever processing them. For example, if we only add updates to
13539// the work-in-progress queue, some updates could be lost whenever a work-in
13540// -progress render restarts by cloning from current. Similarly, if we only add
13541// updates to the current queue, the updates will be lost whenever an already
13542// in-progress queue commits and swaps with the current queue. However, by
13543// adding to both queues, we guarantee that the update will be part of the next
13544// work-in-progress. (And because the work-in-progress queue becomes the
13545// current queue once it commits, there's no danger of applying the same
13546// update twice.)
13547//
13548// Prioritization
13549// --------------
13550//
13551// Updates are not sorted by priority, but by insertion; new updates are always
13552// appended to the end of the list.
13553//
13554// The priority is still important, though. When processing the update queue
13555// during the render phase, only the updates with sufficient priority are
13556// included in the result. If we skip an update because it has insufficient
13557// priority, it remains in the queue to be processed later, during a lower
13558// priority render. Crucially, all updates subsequent to a skipped update also
13559// remain in the queue *regardless of their priority*. That means high priority
13560// updates are sometimes processed twice, at two separate priorities. We also
13561// keep track of a base state, that represents the state before the first
13562// update in the queue is applied.
13563//
13564// For example:
13565//
13566// Given a base state of '', and the following queue of updates
13567//
13568// A1 - B2 - C1 - D2
13569//
13570// where the number indicates the priority, and the update is applied to the
13571// previous state by appending a letter, React will process these updates as
13572// two separate renders, one per distinct priority level:
13573//
13574// First render, at priority 1:
13575// Base state: ''
13576// Updates: [A1, C1]
13577// Result state: 'AC'
13578//
13579// Second render, at priority 2:
13580// Base state: 'A' <- The base state does not include C1,
13581// because B2 was skipped.
13582// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
13583// Result state: 'ABCD'
13584//
13585// Because we process updates in insertion order, and rebase high priority
13586// updates when preceding updates are skipped, the final result is deterministic
13587// regardless of priority. Intermediate state may vary according to system
13588// resources, but the final state is always the same.
13589var UpdateState = 0;
13590var ReplaceState = 1;
13591var ForceUpdate = 2;
13592var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
13593// It should only be read right after calling `processUpdateQueue`, via
13594// `checkHasForceUpdateAfterProcessing`.
13595
13596var hasForceUpdate = false;
13597var didWarnUpdateInsideUpdate;
13598var currentlyProcessingQueue;
13599
13600
13601{
13602 didWarnUpdateInsideUpdate = false;
13603 currentlyProcessingQueue = null;
13604
13605
13606}
13607
13608function createUpdateQueue(baseState) {
13609 var queue = {
13610 baseState: baseState,
13611 firstUpdate: null,
13612 lastUpdate: null,
13613 firstCapturedUpdate: null,
13614 lastCapturedUpdate: null,
13615 firstEffect: null,
13616 lastEffect: null,
13617 firstCapturedEffect: null,
13618 lastCapturedEffect: null
13619 };
13620 return queue;
13621}
13622
13623function cloneUpdateQueue(currentQueue) {
13624 var queue = {
13625 baseState: currentQueue.baseState,
13626 firstUpdate: currentQueue.firstUpdate,
13627 lastUpdate: currentQueue.lastUpdate,
13628 // TODO: With resuming, if we bail out and resuse the child tree, we should
13629 // keep these effects.
13630 firstCapturedUpdate: null,
13631 lastCapturedUpdate: null,
13632 firstEffect: null,
13633 lastEffect: null,
13634 firstCapturedEffect: null,
13635 lastCapturedEffect: null
13636 };
13637 return queue;
13638}
13639
13640function createUpdate(expirationTime, suspenseConfig) {
13641 var update = {
13642 expirationTime: expirationTime,
13643 suspenseConfig: suspenseConfig,
13644 tag: UpdateState,
13645 payload: null,
13646 callback: null,
13647 next: null,
13648 nextEffect: null
13649 };
13650
13651 {
13652 update.priority = getCurrentPriorityLevel();
13653 }
13654
13655 return update;
13656}
13657
13658function appendUpdateToQueue(queue, update) {
13659 // Append the update to the end of the list.
13660 if (queue.lastUpdate === null) {
13661 // Queue is empty
13662 queue.firstUpdate = queue.lastUpdate = update;
13663 } else {
13664 queue.lastUpdate.next = update;
13665 queue.lastUpdate = update;
13666 }
13667}
13668
13669function enqueueUpdate(fiber, update) {
13670 // Update queues are created lazily.
13671 var alternate = fiber.alternate;
13672 var queue1;
13673 var queue2;
13674
13675 if (alternate === null) {
13676 // There's only one fiber.
13677 queue1 = fiber.updateQueue;
13678 queue2 = null;
13679
13680 if (queue1 === null) {
13681 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13682 }
13683 } else {
13684 // There are two owners.
13685 queue1 = fiber.updateQueue;
13686 queue2 = alternate.updateQueue;
13687
13688 if (queue1 === null) {
13689 if (queue2 === null) {
13690 // Neither fiber has an update queue. Create new ones.
13691 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13692 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
13693 } else {
13694 // Only one fiber has an update queue. Clone to create a new one.
13695 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
13696 }
13697 } else {
13698 if (queue2 === null) {
13699 // Only one fiber has an update queue. Clone to create a new one.
13700 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
13701 } else {// Both owners have an update queue.
13702 }
13703 }
13704 }
13705
13706 if (queue2 === null || queue1 === queue2) {
13707 // There's only a single queue.
13708 appendUpdateToQueue(queue1, update);
13709 } else {
13710 // There are two queues. We need to append the update to both queues,
13711 // while accounting for the persistent structure of the list — we don't
13712 // want the same update to be added multiple times.
13713 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
13714 // One of the queues is not empty. We must add the update to both queues.
13715 appendUpdateToQueue(queue1, update);
13716 appendUpdateToQueue(queue2, update);
13717 } else {
13718 // Both queues are non-empty. The last update is the same in both lists,
13719 // because of structural sharing. So, only append to one of the lists.
13720 appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2.
13721
13722 queue2.lastUpdate = update;
13723 }
13724 }
13725
13726 {
13727 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
13728 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.');
13729 didWarnUpdateInsideUpdate = true;
13730 }
13731 }
13732}
13733function enqueueCapturedUpdate(workInProgress, update) {
13734 // Captured updates go into a separate list, and only on the work-in-
13735 // progress queue.
13736 var workInProgressQueue = workInProgress.updateQueue;
13737
13738 if (workInProgressQueue === null) {
13739 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
13740 } else {
13741 // TODO: I put this here rather than createWorkInProgress so that we don't
13742 // clone the queue unnecessarily. There's probably a better way to
13743 // structure this.
13744 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
13745 } // Append the update to the end of the list.
13746
13747
13748 if (workInProgressQueue.lastCapturedUpdate === null) {
13749 // This is the first render phase update
13750 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
13751 } else {
13752 workInProgressQueue.lastCapturedUpdate.next = update;
13753 workInProgressQueue.lastCapturedUpdate = update;
13754 }
13755}
13756
13757function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
13758 var current = workInProgress.alternate;
13759
13760 if (current !== null) {
13761 // If the work-in-progress queue is equal to the current queue,
13762 // we need to clone it first.
13763 if (queue === current.updateQueue) {
13764 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
13765 }
13766 }
13767
13768 return queue;
13769}
13770
13771function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
13772 switch (update.tag) {
13773 case ReplaceState:
13774 {
13775 var payload = update.payload;
13776
13777 if (typeof payload === 'function') {
13778 // Updater function
13779 {
13780 enterDisallowedContextReadInDEV();
13781
13782 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13783 payload.call(instance, prevState, nextProps);
13784 }
13785 }
13786
13787 var nextState = payload.call(instance, prevState, nextProps);
13788
13789 {
13790 exitDisallowedContextReadInDEV();
13791 }
13792
13793 return nextState;
13794 } // State object
13795
13796
13797 return payload;
13798 }
13799
13800 case CaptureUpdate:
13801 {
13802 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
13803 }
13804 // Intentional fallthrough
13805
13806 case UpdateState:
13807 {
13808 var _payload = update.payload;
13809 var partialState;
13810
13811 if (typeof _payload === 'function') {
13812 // Updater function
13813 {
13814 enterDisallowedContextReadInDEV();
13815
13816 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13817 _payload.call(instance, prevState, nextProps);
13818 }
13819 }
13820
13821 partialState = _payload.call(instance, prevState, nextProps);
13822
13823 {
13824 exitDisallowedContextReadInDEV();
13825 }
13826 } else {
13827 // Partial state object
13828 partialState = _payload;
13829 }
13830
13831 if (partialState === null || partialState === undefined) {
13832 // Null and undefined are treated as no-ops.
13833 return prevState;
13834 } // Merge the partial state and the previous state.
13835
13836
13837 return _assign({}, prevState, partialState);
13838 }
13839
13840 case ForceUpdate:
13841 {
13842 hasForceUpdate = true;
13843 return prevState;
13844 }
13845 }
13846
13847 return prevState;
13848}
13849
13850function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
13851 hasForceUpdate = false;
13852 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
13853
13854 {
13855 currentlyProcessingQueue = queue;
13856 } // These values may change as we process the queue.
13857
13858
13859 var newBaseState = queue.baseState;
13860 var newFirstUpdate = null;
13861 var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result.
13862
13863 var update = queue.firstUpdate;
13864 var resultState = newBaseState;
13865
13866 while (update !== null) {
13867 var updateExpirationTime = update.expirationTime;
13868
13869 if (updateExpirationTime < renderExpirationTime) {
13870 // This update does not have sufficient priority. Skip it.
13871 if (newFirstUpdate === null) {
13872 // This is the first skipped update. It will be the first update in
13873 // the new list.
13874 newFirstUpdate = update; // Since this is the first update that was skipped, the current result
13875 // is the new base state.
13876
13877 newBaseState = resultState;
13878 } // Since this update will remain in the list, update the remaining
13879 // expiration time.
13880
13881
13882 if (newExpirationTime < updateExpirationTime) {
13883 newExpirationTime = updateExpirationTime;
13884 }
13885 } else {
13886 // This update does have sufficient priority.
13887 // Mark the event time of this update as relevant to this render pass.
13888 // TODO: This should ideally use the true event time of this update rather than
13889 // its priority which is a derived and not reverseable value.
13890 // TODO: We should skip this update if it was already committed but currently
13891 // we have no way of detecting the difference between a committed and suspended
13892 // update here.
13893 markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result.
13894
13895 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13896 var callback = update.callback;
13897
13898 if (callback !== null) {
13899 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13900
13901 update.nextEffect = null;
13902
13903 if (queue.lastEffect === null) {
13904 queue.firstEffect = queue.lastEffect = update;
13905 } else {
13906 queue.lastEffect.nextEffect = update;
13907 queue.lastEffect = update;
13908 }
13909 }
13910 } // Continue to the next update.
13911
13912
13913 update = update.next;
13914 } // Separately, iterate though the list of captured updates.
13915
13916
13917 var newFirstCapturedUpdate = null;
13918 update = queue.firstCapturedUpdate;
13919
13920 while (update !== null) {
13921 var _updateExpirationTime = update.expirationTime;
13922
13923 if (_updateExpirationTime < renderExpirationTime) {
13924 // This update does not have sufficient priority. Skip it.
13925 if (newFirstCapturedUpdate === null) {
13926 // This is the first skipped captured update. It will be the first
13927 // update in the new list.
13928 newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is
13929 // the new base state.
13930
13931 if (newFirstUpdate === null) {
13932 newBaseState = resultState;
13933 }
13934 } // Since this update will remain in the list, update the remaining
13935 // expiration time.
13936
13937
13938 if (newExpirationTime < _updateExpirationTime) {
13939 newExpirationTime = _updateExpirationTime;
13940 }
13941 } else {
13942 // This update does have sufficient priority. Process it and compute
13943 // a new result.
13944 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13945 var _callback = update.callback;
13946
13947 if (_callback !== null) {
13948 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13949
13950 update.nextEffect = null;
13951
13952 if (queue.lastCapturedEffect === null) {
13953 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
13954 } else {
13955 queue.lastCapturedEffect.nextEffect = update;
13956 queue.lastCapturedEffect = update;
13957 }
13958 }
13959 }
13960
13961 update = update.next;
13962 }
13963
13964 if (newFirstUpdate === null) {
13965 queue.lastUpdate = null;
13966 }
13967
13968 if (newFirstCapturedUpdate === null) {
13969 queue.lastCapturedUpdate = null;
13970 } else {
13971 workInProgress.effectTag |= Callback;
13972 }
13973
13974 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
13975 // We processed every update, without skipping. That means the new base
13976 // state is the same as the result state.
13977 newBaseState = resultState;
13978 }
13979
13980 queue.baseState = newBaseState;
13981 queue.firstUpdate = newFirstUpdate;
13982 queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
13983 // This should be fine because the only two other things that contribute to
13984 // expiration time are props and context. We're already in the middle of the
13985 // begin phase by the time we start processing the queue, so we've already
13986 // dealt with the props. Context in components that specify
13987 // shouldComponentUpdate is tricky; but we'll have to account for
13988 // that regardless.
13989
13990 markUnprocessedUpdateTime(newExpirationTime);
13991 workInProgress.expirationTime = newExpirationTime;
13992 workInProgress.memoizedState = resultState;
13993
13994 {
13995 currentlyProcessingQueue = null;
13996 }
13997}
13998
13999function callCallback(callback, context) {
14000 (function () {
14001 if (!(typeof callback === 'function')) {
14002 {
14003 throw ReactError(Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback));
14004 }
14005 }
14006 })();
14007
14008 callback.call(context);
14009}
14010
14011function resetHasForceUpdateBeforeProcessing() {
14012 hasForceUpdate = false;
14013}
14014function checkHasForceUpdateAfterProcessing() {
14015 return hasForceUpdate;
14016}
14017function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
14018 // If the finished render included captured updates, and there are still
14019 // lower priority updates left over, we need to keep the captured updates
14020 // in the queue so that they are rebased and not dropped once we process the
14021 // queue again at the lower priority.
14022 if (finishedQueue.firstCapturedUpdate !== null) {
14023 // Join the captured update list to the end of the normal list.
14024 if (finishedQueue.lastUpdate !== null) {
14025 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
14026 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
14027 } // Clear the list of captured updates.
14028
14029
14030 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
14031 } // Commit the effects
14032
14033
14034 commitUpdateEffects(finishedQueue.firstEffect, instance);
14035 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
14036 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
14037 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
14038}
14039
14040function commitUpdateEffects(effect, instance) {
14041 while (effect !== null) {
14042 var callback = effect.callback;
14043
14044 if (callback !== null) {
14045 effect.callback = null;
14046 callCallback(callback, instance);
14047 }
14048
14049 effect = effect.nextEffect;
14050 }
14051}
14052
14053var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
14054function requestCurrentSuspenseConfig() {
14055 return ReactCurrentBatchConfig.suspense;
14056}
14057
14058var fakeInternalInstance = {};
14059var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default.
14060// We'll use it to determine whether we need to initialize legacy refs.
14061
14062var emptyRefsObject = new React.Component().refs;
14063var didWarnAboutStateAssignmentForComponent;
14064var didWarnAboutUninitializedState;
14065var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
14066var didWarnAboutLegacyLifecyclesAndDerivedState;
14067var didWarnAboutUndefinedDerivedState;
14068var warnOnUndefinedDerivedState;
14069var warnOnInvalidCallback$1;
14070var didWarnAboutDirectlyAssigningPropsToState;
14071var didWarnAboutContextTypeAndContextTypes;
14072var didWarnAboutInvalidateContextType;
14073
14074{
14075 didWarnAboutStateAssignmentForComponent = new Set();
14076 didWarnAboutUninitializedState = new Set();
14077 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
14078 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
14079 didWarnAboutDirectlyAssigningPropsToState = new Set();
14080 didWarnAboutUndefinedDerivedState = new Set();
14081 didWarnAboutContextTypeAndContextTypes = new Set();
14082 didWarnAboutInvalidateContextType = new Set();
14083 var didWarnOnInvalidCallback = new Set();
14084
14085 warnOnInvalidCallback$1 = function (callback, callerName) {
14086 if (callback === null || typeof callback === 'function') {
14087 return;
14088 }
14089
14090 var key = callerName + "_" + callback;
14091
14092 if (!didWarnOnInvalidCallback.has(key)) {
14093 didWarnOnInvalidCallback.add(key);
14094 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
14095 }
14096 };
14097
14098 warnOnUndefinedDerivedState = function (type, partialState) {
14099 if (partialState === undefined) {
14100 var componentName = getComponentName(type) || 'Component';
14101
14102 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
14103 didWarnAboutUndefinedDerivedState.add(componentName);
14104 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
14105 }
14106 }
14107 }; // This is so gross but it's at least non-critical and can be removed if
14108 // it causes problems. This is meant to give a nicer error message for
14109 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
14110 // ...)) which otherwise throws a "_processChildContext is not a function"
14111 // exception.
14112
14113
14114 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
14115 enumerable: false,
14116 value: function () {
14117 (function () {
14118 {
14119 {
14120 throw ReactError(Error("_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)."));
14121 }
14122 }
14123 })();
14124 }
14125 });
14126 Object.freeze(fakeInternalInstance);
14127}
14128
14129function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
14130 var prevState = workInProgress.memoizedState;
14131
14132 {
14133 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14134 // Invoke the function an extra time to help detect side-effects.
14135 getDerivedStateFromProps(nextProps, prevState);
14136 }
14137 }
14138
14139 var partialState = getDerivedStateFromProps(nextProps, prevState);
14140
14141 {
14142 warnOnUndefinedDerivedState(ctor, partialState);
14143 } // Merge the partial state and the previous state.
14144
14145
14146 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
14147 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
14148 // base state.
14149
14150 var updateQueue = workInProgress.updateQueue;
14151
14152 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
14153 updateQueue.baseState = memoizedState;
14154 }
14155}
14156var classComponentUpdater = {
14157 isMounted: isMounted,
14158 enqueueSetState: function (inst, payload, callback) {
14159 var fiber = get(inst);
14160 var currentTime = requestCurrentTime();
14161 var suspenseConfig = requestCurrentSuspenseConfig();
14162 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14163 var update = createUpdate(expirationTime, suspenseConfig);
14164 update.payload = payload;
14165
14166 if (callback !== undefined && callback !== null) {
14167 {
14168 warnOnInvalidCallback$1(callback, 'setState');
14169 }
14170
14171 update.callback = callback;
14172 }
14173
14174 enqueueUpdate(fiber, update);
14175 scheduleWork(fiber, expirationTime);
14176 },
14177 enqueueReplaceState: function (inst, payload, callback) {
14178 var fiber = get(inst);
14179 var currentTime = requestCurrentTime();
14180 var suspenseConfig = requestCurrentSuspenseConfig();
14181 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14182 var update = createUpdate(expirationTime, suspenseConfig);
14183 update.tag = ReplaceState;
14184 update.payload = payload;
14185
14186 if (callback !== undefined && callback !== null) {
14187 {
14188 warnOnInvalidCallback$1(callback, 'replaceState');
14189 }
14190
14191 update.callback = callback;
14192 }
14193
14194 enqueueUpdate(fiber, update);
14195 scheduleWork(fiber, expirationTime);
14196 },
14197 enqueueForceUpdate: function (inst, callback) {
14198 var fiber = get(inst);
14199 var currentTime = requestCurrentTime();
14200 var suspenseConfig = requestCurrentSuspenseConfig();
14201 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14202 var update = createUpdate(expirationTime, suspenseConfig);
14203 update.tag = ForceUpdate;
14204
14205 if (callback !== undefined && callback !== null) {
14206 {
14207 warnOnInvalidCallback$1(callback, 'forceUpdate');
14208 }
14209
14210 update.callback = callback;
14211 }
14212
14213 enqueueUpdate(fiber, update);
14214 scheduleWork(fiber, expirationTime);
14215 }
14216};
14217
14218function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
14219 var instance = workInProgress.stateNode;
14220
14221 if (typeof instance.shouldComponentUpdate === 'function') {
14222 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
14223 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
14224 stopPhaseTimer();
14225
14226 {
14227 !(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;
14228 }
14229
14230 return shouldUpdate;
14231 }
14232
14233 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
14234 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
14235 }
14236
14237 return true;
14238}
14239
14240function checkClassInstance(workInProgress, ctor, newProps) {
14241 var instance = workInProgress.stateNode;
14242
14243 {
14244 var name = getComponentName(ctor) || 'Component';
14245 var renderPresent = instance.render;
14246
14247 if (!renderPresent) {
14248 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
14249 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
14250 } else {
14251 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
14252 }
14253 }
14254
14255 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
14256 !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;
14257 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
14258 !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;
14259 var noInstancePropTypes = !instance.propTypes;
14260 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
14261 var noInstanceContextType = !instance.contextType;
14262 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
14263
14264 if (disableLegacyContext) {
14265 if (ctor.childContextTypes) {
14266 warningWithoutStack$1(false, '%s uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', name);
14267 }
14268
14269 if (ctor.contextTypes) {
14270 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', name);
14271 }
14272 } else {
14273 var noInstanceContextTypes = !instance.contextTypes;
14274 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
14275
14276 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
14277 didWarnAboutContextTypeAndContextTypes.add(ctor);
14278 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
14279 }
14280 }
14281
14282 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
14283 !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;
14284
14285 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
14286 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');
14287 }
14288
14289 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
14290 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
14291 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
14292 !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;
14293 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
14294 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
14295 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
14296 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
14297 var hasMutatedProps = instance.props !== newProps;
14298 !(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;
14299 var noInstanceDefaultProps = !instance.defaultProps;
14300 !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;
14301
14302 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
14303 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
14304 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
14305 }
14306
14307 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
14308 !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;
14309 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
14310 !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;
14311 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
14312 !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;
14313 var _state = instance.state;
14314
14315 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
14316 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
14317 }
14318
14319 if (typeof instance.getChildContext === 'function') {
14320 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
14321 }
14322 }
14323}
14324
14325function adoptClassInstance(workInProgress, instance) {
14326 instance.updater = classComponentUpdater;
14327 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
14328
14329 set(instance, workInProgress);
14330
14331 {
14332 instance._reactInternalInstance = fakeInternalInstance;
14333 }
14334}
14335
14336function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
14337 var isLegacyContextConsumer = false;
14338 var unmaskedContext = emptyContextObject;
14339 var context = emptyContextObject;
14340 var contextType = ctor.contextType;
14341
14342 {
14343 if ('contextType' in ctor) {
14344 var isValid = // Allow null for conditional declaration
14345 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
14346
14347 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
14348 didWarnAboutInvalidateContextType.add(ctor);
14349 var addendum = '';
14350
14351 if (contextType === undefined) {
14352 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.';
14353 } else if (typeof contextType !== 'object') {
14354 addendum = ' However, it is set to a ' + typeof contextType + '.';
14355 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
14356 addendum = ' Did you accidentally pass the Context.Provider instead?';
14357 } else if (contextType._context !== undefined) {
14358 // <Context.Consumer>
14359 addendum = ' Did you accidentally pass the Context.Consumer instead?';
14360 } else {
14361 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
14362 }
14363
14364 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
14365 }
14366 }
14367 }
14368
14369 if (typeof contextType === 'object' && contextType !== null) {
14370 context = readContext(contextType);
14371 } else if (!disableLegacyContext) {
14372 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14373 var contextTypes = ctor.contextTypes;
14374 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
14375 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
14376 } // Instantiate twice to help detect side-effects.
14377
14378
14379 {
14380 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14381 new ctor(props, context); // eslint-disable-line no-new
14382 }
14383 }
14384
14385 var instance = new ctor(props, context);
14386 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
14387 adoptClassInstance(workInProgress, instance);
14388
14389 {
14390 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
14391 var componentName = getComponentName(ctor) || 'Component';
14392
14393 if (!didWarnAboutUninitializedState.has(componentName)) {
14394 didWarnAboutUninitializedState.add(componentName);
14395 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);
14396 }
14397 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
14398 // Warn about these lifecycles if they are present.
14399 // Don't warn about react-lifecycles-compat polyfilled methods though.
14400
14401
14402 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
14403 var foundWillMountName = null;
14404 var foundWillReceivePropsName = null;
14405 var foundWillUpdateName = null;
14406
14407 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
14408 foundWillMountName = 'componentWillMount';
14409 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
14410 foundWillMountName = 'UNSAFE_componentWillMount';
14411 }
14412
14413 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
14414 foundWillReceivePropsName = 'componentWillReceiveProps';
14415 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14416 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
14417 }
14418
14419 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
14420 foundWillUpdateName = 'componentWillUpdate';
14421 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14422 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
14423 }
14424
14425 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
14426 var _componentName = getComponentName(ctor) || 'Component';
14427
14428 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
14429
14430 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
14431 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
14432 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-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
14433 }
14434 }
14435 }
14436 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
14437 // ReactFiberContext usually updates this cache but can't for newly-created instances.
14438
14439
14440 if (isLegacyContextConsumer) {
14441 cacheContext(workInProgress, unmaskedContext, context);
14442 }
14443
14444 return instance;
14445}
14446
14447function callComponentWillMount(workInProgress, instance) {
14448 startPhaseTimer(workInProgress, 'componentWillMount');
14449 var oldState = instance.state;
14450
14451 if (typeof instance.componentWillMount === 'function') {
14452 instance.componentWillMount();
14453 }
14454
14455 if (typeof instance.UNSAFE_componentWillMount === 'function') {
14456 instance.UNSAFE_componentWillMount();
14457 }
14458
14459 stopPhaseTimer();
14460
14461 if (oldState !== instance.state) {
14462 {
14463 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');
14464 }
14465
14466 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14467 }
14468}
14469
14470function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
14471 var oldState = instance.state;
14472 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
14473
14474 if (typeof instance.componentWillReceiveProps === 'function') {
14475 instance.componentWillReceiveProps(newProps, nextContext);
14476 }
14477
14478 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14479 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
14480 }
14481
14482 stopPhaseTimer();
14483
14484 if (instance.state !== oldState) {
14485 {
14486 var componentName = getComponentName(workInProgress.type) || 'Component';
14487
14488 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
14489 didWarnAboutStateAssignmentForComponent.add(componentName);
14490 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
14491 }
14492 }
14493
14494 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14495 }
14496} // Invokes the mount life-cycles on a previously never rendered instance.
14497
14498
14499function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14500 {
14501 checkClassInstance(workInProgress, ctor, newProps);
14502 }
14503
14504 var instance = workInProgress.stateNode;
14505 instance.props = newProps;
14506 instance.state = workInProgress.memoizedState;
14507 instance.refs = emptyRefsObject;
14508 var contextType = ctor.contextType;
14509
14510 if (typeof contextType === 'object' && contextType !== null) {
14511 instance.context = readContext(contextType);
14512 } else if (disableLegacyContext) {
14513 instance.context = emptyContextObject;
14514 } else {
14515 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14516 instance.context = getMaskedContext(workInProgress, unmaskedContext);
14517 }
14518
14519 {
14520 if (instance.state === newProps) {
14521 var componentName = getComponentName(ctor) || 'Component';
14522
14523 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
14524 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
14525 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);
14526 }
14527 }
14528
14529 if (workInProgress.mode & StrictMode) {
14530 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
14531 }
14532
14533 if (warnAboutDeprecatedLifecycles) {
14534 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
14535 }
14536 }
14537
14538 var updateQueue = workInProgress.updateQueue;
14539
14540 if (updateQueue !== null) {
14541 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14542 instance.state = workInProgress.memoizedState;
14543 }
14544
14545 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14546
14547 if (typeof getDerivedStateFromProps === 'function') {
14548 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14549 instance.state = workInProgress.memoizedState;
14550 } // In order to support react-lifecycles-compat polyfilled components,
14551 // Unsafe lifecycles should not be invoked for components using the new APIs.
14552
14553
14554 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14555 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
14556 // process them now.
14557
14558 updateQueue = workInProgress.updateQueue;
14559
14560 if (updateQueue !== null) {
14561 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14562 instance.state = workInProgress.memoizedState;
14563 }
14564 }
14565
14566 if (typeof instance.componentDidMount === 'function') {
14567 workInProgress.effectTag |= Update;
14568 }
14569}
14570
14571function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14572 var instance = workInProgress.stateNode;
14573 var oldProps = workInProgress.memoizedProps;
14574 instance.props = oldProps;
14575 var oldContext = instance.context;
14576 var contextType = ctor.contextType;
14577 var nextContext = emptyContextObject;
14578
14579 if (typeof contextType === 'object' && contextType !== null) {
14580 nextContext = readContext(contextType);
14581 } else if (!disableLegacyContext) {
14582 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14583 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
14584 }
14585
14586 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14587 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14588 // ever the previously attempted to render - not the "current". However,
14589 // during componentDidUpdate we pass the "current" props.
14590 // In order to support react-lifecycles-compat polyfilled components,
14591 // Unsafe lifecycles should not be invoked for components using the new APIs.
14592
14593 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14594 if (oldProps !== newProps || oldContext !== nextContext) {
14595 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14596 }
14597 }
14598
14599 resetHasForceUpdateBeforeProcessing();
14600 var oldState = workInProgress.memoizedState;
14601 var newState = instance.state = oldState;
14602 var updateQueue = workInProgress.updateQueue;
14603
14604 if (updateQueue !== null) {
14605 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14606 newState = workInProgress.memoizedState;
14607 }
14608
14609 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14610 // If an update was already in progress, we should schedule an Update
14611 // effect even though we're bailing out, so that cWU/cDU are called.
14612 if (typeof instance.componentDidMount === 'function') {
14613 workInProgress.effectTag |= Update;
14614 }
14615
14616 return false;
14617 }
14618
14619 if (typeof getDerivedStateFromProps === 'function') {
14620 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14621 newState = workInProgress.memoizedState;
14622 }
14623
14624 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14625
14626 if (shouldUpdate) {
14627 // In order to support react-lifecycles-compat polyfilled components,
14628 // Unsafe lifecycles should not be invoked for components using the new APIs.
14629 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14630 startPhaseTimer(workInProgress, 'componentWillMount');
14631
14632 if (typeof instance.componentWillMount === 'function') {
14633 instance.componentWillMount();
14634 }
14635
14636 if (typeof instance.UNSAFE_componentWillMount === 'function') {
14637 instance.UNSAFE_componentWillMount();
14638 }
14639
14640 stopPhaseTimer();
14641 }
14642
14643 if (typeof instance.componentDidMount === 'function') {
14644 workInProgress.effectTag |= Update;
14645 }
14646 } else {
14647 // If an update was already in progress, we should schedule an Update
14648 // effect even though we're bailing out, so that cWU/cDU are called.
14649 if (typeof instance.componentDidMount === 'function') {
14650 workInProgress.effectTag |= Update;
14651 } // If shouldComponentUpdate returned false, we should still update the
14652 // memoized state to indicate that this work can be reused.
14653
14654
14655 workInProgress.memoizedProps = newProps;
14656 workInProgress.memoizedState = newState;
14657 } // Update the existing instance's state, props, and context pointers even
14658 // if shouldComponentUpdate returns false.
14659
14660
14661 instance.props = newProps;
14662 instance.state = newState;
14663 instance.context = nextContext;
14664 return shouldUpdate;
14665} // Invokes the update life-cycles and returns false if it shouldn't rerender.
14666
14667
14668function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
14669 var instance = workInProgress.stateNode;
14670 var oldProps = workInProgress.memoizedProps;
14671 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
14672 var oldContext = instance.context;
14673 var contextType = ctor.contextType;
14674 var nextContext = emptyContextObject;
14675
14676 if (typeof contextType === 'object' && contextType !== null) {
14677 nextContext = readContext(contextType);
14678 } else if (!disableLegacyContext) {
14679 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14680 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
14681 }
14682
14683 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14684 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14685 // ever the previously attempted to render - not the "current". However,
14686 // during componentDidUpdate we pass the "current" props.
14687 // In order to support react-lifecycles-compat polyfilled components,
14688 // Unsafe lifecycles should not be invoked for components using the new APIs.
14689
14690 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14691 if (oldProps !== newProps || oldContext !== nextContext) {
14692 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14693 }
14694 }
14695
14696 resetHasForceUpdateBeforeProcessing();
14697 var oldState = workInProgress.memoizedState;
14698 var newState = instance.state = oldState;
14699 var updateQueue = workInProgress.updateQueue;
14700
14701 if (updateQueue !== null) {
14702 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14703 newState = workInProgress.memoizedState;
14704 }
14705
14706 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14707 // If an update was already in progress, we should schedule an Update
14708 // effect even though we're bailing out, so that cWU/cDU are called.
14709 if (typeof instance.componentDidUpdate === 'function') {
14710 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14711 workInProgress.effectTag |= Update;
14712 }
14713 }
14714
14715 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14716 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14717 workInProgress.effectTag |= Snapshot;
14718 }
14719 }
14720
14721 return false;
14722 }
14723
14724 if (typeof getDerivedStateFromProps === 'function') {
14725 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14726 newState = workInProgress.memoizedState;
14727 }
14728
14729 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14730
14731 if (shouldUpdate) {
14732 // In order to support react-lifecycles-compat polyfilled components,
14733 // Unsafe lifecycles should not be invoked for components using the new APIs.
14734 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
14735 startPhaseTimer(workInProgress, 'componentWillUpdate');
14736
14737 if (typeof instance.componentWillUpdate === 'function') {
14738 instance.componentWillUpdate(newProps, newState, nextContext);
14739 }
14740
14741 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14742 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
14743 }
14744
14745 stopPhaseTimer();
14746 }
14747
14748 if (typeof instance.componentDidUpdate === 'function') {
14749 workInProgress.effectTag |= Update;
14750 }
14751
14752 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14753 workInProgress.effectTag |= Snapshot;
14754 }
14755 } else {
14756 // If an update was already in progress, we should schedule an Update
14757 // effect even though we're bailing out, so that cWU/cDU are called.
14758 if (typeof instance.componentDidUpdate === 'function') {
14759 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14760 workInProgress.effectTag |= Update;
14761 }
14762 }
14763
14764 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14765 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14766 workInProgress.effectTag |= Snapshot;
14767 }
14768 } // If shouldComponentUpdate returned false, we should still update the
14769 // memoized props/state to indicate that this work can be reused.
14770
14771
14772 workInProgress.memoizedProps = newProps;
14773 workInProgress.memoizedState = newState;
14774 } // Update the existing instance's state, props, and context pointers even
14775 // if shouldComponentUpdate returns false.
14776
14777
14778 instance.props = newProps;
14779 instance.state = newState;
14780 instance.context = nextContext;
14781 return shouldUpdate;
14782}
14783
14784var didWarnAboutMaps;
14785var didWarnAboutGenerators;
14786var didWarnAboutStringRefs;
14787var ownerHasKeyUseWarning;
14788var ownerHasFunctionTypeWarning;
14789
14790var warnForMissingKey = function (child) {};
14791
14792{
14793 didWarnAboutMaps = false;
14794 didWarnAboutGenerators = false;
14795 didWarnAboutStringRefs = {};
14796 /**
14797 * Warn if there's no key explicitly set on dynamic arrays of children or
14798 * object keys are not valid. This allows us to keep track of children between
14799 * updates.
14800 */
14801
14802 ownerHasKeyUseWarning = {};
14803 ownerHasFunctionTypeWarning = {};
14804
14805 warnForMissingKey = function (child) {
14806 if (child === null || typeof child !== 'object') {
14807 return;
14808 }
14809
14810 if (!child._store || child._store.validated || child.key != null) {
14811 return;
14812 }
14813
14814 (function () {
14815 if (!(typeof child._store === 'object')) {
14816 {
14817 throw ReactError(Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."));
14818 }
14819 }
14820 })();
14821
14822 child._store.validated = true;
14823 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
14824
14825 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
14826 return;
14827 }
14828
14829 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
14830 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
14831 };
14832}
14833
14834var isArray = Array.isArray;
14835
14836function coerceRef(returnFiber, current$$1, element) {
14837 var mixedRef = element.ref;
14838
14839 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
14840 {
14841 // TODO: Clean this up once we turn on the string ref warning for
14842 // everyone, because the strict mode case will no longer be relevant
14843 if (returnFiber.mode & StrictMode || warnAboutStringRefs) {
14844 var componentName = getComponentName(returnFiber.type) || 'Component';
14845
14846 if (!didWarnAboutStringRefs[componentName]) {
14847 if (warnAboutStringRefs) {
14848 warningWithoutStack$1(false, 'Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber));
14849 } else {
14850 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 useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));
14851 }
14852
14853 didWarnAboutStringRefs[componentName] = true;
14854 }
14855 }
14856 }
14857
14858 if (element._owner) {
14859 var owner = element._owner;
14860 var inst;
14861
14862 if (owner) {
14863 var ownerFiber = owner;
14864
14865 (function () {
14866 if (!(ownerFiber.tag === ClassComponent)) {
14867 {
14868 throw ReactError(Error("Function components cannot have refs. Did you mean to use React.forwardRef()?"));
14869 }
14870 }
14871 })();
14872
14873 inst = ownerFiber.stateNode;
14874 }
14875
14876 (function () {
14877 if (!inst) {
14878 {
14879 throw ReactError(Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue."));
14880 }
14881 }
14882 })();
14883
14884 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
14885
14886 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
14887 return current$$1.ref;
14888 }
14889
14890 var ref = function (value) {
14891 var refs = inst.refs;
14892
14893 if (refs === emptyRefsObject) {
14894 // This is a lazy pooled frozen object, so we need to initialize.
14895 refs = inst.refs = {};
14896 }
14897
14898 if (value === null) {
14899 delete refs[stringRef];
14900 } else {
14901 refs[stringRef] = value;
14902 }
14903 };
14904
14905 ref._stringRef = stringRef;
14906 return ref;
14907 } else {
14908 (function () {
14909 if (!(typeof mixedRef === 'string')) {
14910 {
14911 throw ReactError(Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null."));
14912 }
14913 }
14914 })();
14915
14916 (function () {
14917 if (!element._owner) {
14918 {
14919 throw ReactError(Error("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."));
14920 }
14921 }
14922 })();
14923 }
14924 }
14925
14926 return mixedRef;
14927}
14928
14929function throwOnInvalidObjectType(returnFiber, newChild) {
14930 if (returnFiber.type !== 'textarea') {
14931 var addendum = '';
14932
14933 {
14934 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
14935 }
14936
14937 (function () {
14938 {
14939 {
14940 throw ReactError(Error("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));
14941 }
14942 }
14943 })();
14944 }
14945}
14946
14947function warnOnFunctionType() {
14948 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();
14949
14950 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
14951 return;
14952 }
14953
14954 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
14955 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.');
14956} // This wrapper function exists because I expect to clone the code in each path
14957// to be able to optimize each path individually by branching early. This needs
14958// a compiler or we can do it manually. Helpers that don't need this branching
14959// live outside of this function.
14960
14961
14962function ChildReconciler(shouldTrackSideEffects) {
14963 function deleteChild(returnFiber, childToDelete) {
14964 if (!shouldTrackSideEffects) {
14965 // Noop.
14966 return;
14967 } // Deletions are added in reversed order so we add it to the front.
14968 // At this point, the return fiber's effect list is empty except for
14969 // deletions, so we can just append the deletion to the list. The remaining
14970 // effects aren't added until the complete phase. Once we implement
14971 // resuming, this may not be true.
14972
14973
14974 var last = returnFiber.lastEffect;
14975
14976 if (last !== null) {
14977 last.nextEffect = childToDelete;
14978 returnFiber.lastEffect = childToDelete;
14979 } else {
14980 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14981 }
14982
14983 childToDelete.nextEffect = null;
14984 childToDelete.effectTag = Deletion;
14985 }
14986
14987 function deleteRemainingChildren(returnFiber, currentFirstChild) {
14988 if (!shouldTrackSideEffects) {
14989 // Noop.
14990 return null;
14991 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
14992 // assuming that after the first child we've already added everything.
14993
14994
14995 var childToDelete = currentFirstChild;
14996
14997 while (childToDelete !== null) {
14998 deleteChild(returnFiber, childToDelete);
14999 childToDelete = childToDelete.sibling;
15000 }
15001
15002 return null;
15003 }
15004
15005 function mapRemainingChildren(returnFiber, currentFirstChild) {
15006 // Add the remaining children to a temporary map so that we can find them by
15007 // keys quickly. Implicit (null) keys get added to this set with their index
15008 // instead.
15009 var existingChildren = new Map();
15010 var existingChild = currentFirstChild;
15011
15012 while (existingChild !== null) {
15013 if (existingChild.key !== null) {
15014 existingChildren.set(existingChild.key, existingChild);
15015 } else {
15016 existingChildren.set(existingChild.index, existingChild);
15017 }
15018
15019 existingChild = existingChild.sibling;
15020 }
15021
15022 return existingChildren;
15023 }
15024
15025 function useFiber(fiber, pendingProps, expirationTime) {
15026 // We currently set sibling to null and index to 0 here because it is easy
15027 // to forget to do before returning it. E.g. for the single child case.
15028 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
15029 clone.index = 0;
15030 clone.sibling = null;
15031 return clone;
15032 }
15033
15034 function placeChild(newFiber, lastPlacedIndex, newIndex) {
15035 newFiber.index = newIndex;
15036
15037 if (!shouldTrackSideEffects) {
15038 // Noop.
15039 return lastPlacedIndex;
15040 }
15041
15042 var current$$1 = newFiber.alternate;
15043
15044 if (current$$1 !== null) {
15045 var oldIndex = current$$1.index;
15046
15047 if (oldIndex < lastPlacedIndex) {
15048 // This is a move.
15049 newFiber.effectTag = Placement;
15050 return lastPlacedIndex;
15051 } else {
15052 // This item can stay in place.
15053 return oldIndex;
15054 }
15055 } else {
15056 // This is an insertion.
15057 newFiber.effectTag = Placement;
15058 return lastPlacedIndex;
15059 }
15060 }
15061
15062 function placeSingleChild(newFiber) {
15063 // This is simpler for the single child case. We only need to do a
15064 // placement for inserting new children.
15065 if (shouldTrackSideEffects && newFiber.alternate === null) {
15066 newFiber.effectTag = Placement;
15067 }
15068
15069 return newFiber;
15070 }
15071
15072 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
15073 if (current$$1 === null || current$$1.tag !== HostText) {
15074 // Insert
15075 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15076 created.return = returnFiber;
15077 return created;
15078 } else {
15079 // Update
15080 var existing = useFiber(current$$1, textContent, expirationTime);
15081 existing.return = returnFiber;
15082 return existing;
15083 }
15084 }
15085
15086 function updateElement(returnFiber, current$$1, element, expirationTime) {
15087 if (current$$1 !== null && (current$$1.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
15088 isCompatibleFamilyForHotReloading(current$$1, element)))) {
15089 // Move based on index
15090 var existing = useFiber(current$$1, element.props, expirationTime);
15091 existing.ref = coerceRef(returnFiber, current$$1, element);
15092 existing.return = returnFiber;
15093
15094 {
15095 existing._debugSource = element._source;
15096 existing._debugOwner = element._owner;
15097 }
15098
15099 return existing;
15100 } else {
15101 // Insert
15102 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
15103 created.ref = coerceRef(returnFiber, current$$1, element);
15104 created.return = returnFiber;
15105 return created;
15106 }
15107 }
15108
15109 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
15110 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
15111 // Insert
15112 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15113 created.return = returnFiber;
15114 return created;
15115 } else {
15116 // Update
15117 var existing = useFiber(current$$1, portal.children || [], expirationTime);
15118 existing.return = returnFiber;
15119 return existing;
15120 }
15121 }
15122
15123 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
15124 if (current$$1 === null || current$$1.tag !== Fragment) {
15125 // Insert
15126 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
15127 created.return = returnFiber;
15128 return created;
15129 } else {
15130 // Update
15131 var existing = useFiber(current$$1, fragment, expirationTime);
15132 existing.return = returnFiber;
15133 return existing;
15134 }
15135 }
15136
15137 function createChild(returnFiber, newChild, expirationTime) {
15138 if (typeof newChild === 'string' || typeof newChild === 'number') {
15139 // Text nodes don't have keys. If the previous node is implicitly keyed
15140 // we can continue to replace it without aborting even if it is not a text
15141 // node.
15142 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
15143 created.return = returnFiber;
15144 return created;
15145 }
15146
15147 if (typeof newChild === 'object' && newChild !== null) {
15148 switch (newChild.$$typeof) {
15149 case REACT_ELEMENT_TYPE:
15150 {
15151 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
15152
15153 _created.ref = coerceRef(returnFiber, null, newChild);
15154 _created.return = returnFiber;
15155 return _created;
15156 }
15157
15158 case REACT_PORTAL_TYPE:
15159 {
15160 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
15161
15162 _created2.return = returnFiber;
15163 return _created2;
15164 }
15165 }
15166
15167 if (isArray(newChild) || getIteratorFn(newChild)) {
15168 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
15169
15170 _created3.return = returnFiber;
15171 return _created3;
15172 }
15173
15174 throwOnInvalidObjectType(returnFiber, newChild);
15175 }
15176
15177 {
15178 if (typeof newChild === 'function') {
15179 warnOnFunctionType();
15180 }
15181 }
15182
15183 return null;
15184 }
15185
15186 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
15187 // Update the fiber if the keys match, otherwise return null.
15188 var key = oldFiber !== null ? oldFiber.key : null;
15189
15190 if (typeof newChild === 'string' || typeof newChild === 'number') {
15191 // Text nodes don't have keys. If the previous node is implicitly keyed
15192 // we can continue to replace it without aborting even if it is not a text
15193 // node.
15194 if (key !== null) {
15195 return null;
15196 }
15197
15198 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
15199 }
15200
15201 if (typeof newChild === 'object' && newChild !== null) {
15202 switch (newChild.$$typeof) {
15203 case REACT_ELEMENT_TYPE:
15204 {
15205 if (newChild.key === key) {
15206 if (newChild.type === REACT_FRAGMENT_TYPE) {
15207 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
15208 }
15209
15210 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
15211 } else {
15212 return null;
15213 }
15214 }
15215
15216 case REACT_PORTAL_TYPE:
15217 {
15218 if (newChild.key === key) {
15219 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
15220 } else {
15221 return null;
15222 }
15223 }
15224 }
15225
15226 if (isArray(newChild) || getIteratorFn(newChild)) {
15227 if (key !== null) {
15228 return null;
15229 }
15230
15231 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
15232 }
15233
15234 throwOnInvalidObjectType(returnFiber, newChild);
15235 }
15236
15237 {
15238 if (typeof newChild === 'function') {
15239 warnOnFunctionType();
15240 }
15241 }
15242
15243 return null;
15244 }
15245
15246 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
15247 if (typeof newChild === 'string' || typeof newChild === 'number') {
15248 // Text nodes don't have keys, so we neither have to check the old nor
15249 // new node for the key. If both are text nodes, they match.
15250 var matchedFiber = existingChildren.get(newIdx) || null;
15251 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
15252 }
15253
15254 if (typeof newChild === 'object' && newChild !== null) {
15255 switch (newChild.$$typeof) {
15256 case REACT_ELEMENT_TYPE:
15257 {
15258 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15259
15260 if (newChild.type === REACT_FRAGMENT_TYPE) {
15261 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
15262 }
15263
15264 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
15265 }
15266
15267 case REACT_PORTAL_TYPE:
15268 {
15269 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15270
15271 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
15272 }
15273 }
15274
15275 if (isArray(newChild) || getIteratorFn(newChild)) {
15276 var _matchedFiber3 = existingChildren.get(newIdx) || null;
15277
15278 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
15279 }
15280
15281 throwOnInvalidObjectType(returnFiber, newChild);
15282 }
15283
15284 {
15285 if (typeof newChild === 'function') {
15286 warnOnFunctionType();
15287 }
15288 }
15289
15290 return null;
15291 }
15292 /**
15293 * Warns if there is a duplicate or missing key
15294 */
15295
15296
15297 function warnOnInvalidKey(child, knownKeys) {
15298 {
15299 if (typeof child !== 'object' || child === null) {
15300 return knownKeys;
15301 }
15302
15303 switch (child.$$typeof) {
15304 case REACT_ELEMENT_TYPE:
15305 case REACT_PORTAL_TYPE:
15306 warnForMissingKey(child);
15307 var key = child.key;
15308
15309 if (typeof key !== 'string') {
15310 break;
15311 }
15312
15313 if (knownKeys === null) {
15314 knownKeys = new Set();
15315 knownKeys.add(key);
15316 break;
15317 }
15318
15319 if (!knownKeys.has(key)) {
15320 knownKeys.add(key);
15321 break;
15322 }
15323
15324 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);
15325 break;
15326
15327 default:
15328 break;
15329 }
15330 }
15331
15332 return knownKeys;
15333 }
15334
15335 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
15336 // This algorithm can't optimize by searching from both ends since we
15337 // don't have backpointers on fibers. I'm trying to see how far we can get
15338 // with that model. If it ends up not being worth the tradeoffs, we can
15339 // add it later.
15340 // Even with a two ended optimization, we'd want to optimize for the case
15341 // where there are few changes and brute force the comparison instead of
15342 // going for the Map. It'd like to explore hitting that path first in
15343 // forward-only mode and only go for the Map once we notice that we need
15344 // lots of look ahead. This doesn't handle reversal as well as two ended
15345 // search but that's unusual. Besides, for the two ended optimization to
15346 // work on Iterables, we'd need to copy the whole set.
15347 // In this first iteration, we'll just live with hitting the bad case
15348 // (adding everything to a Map) in for every insert/move.
15349 // If you change this code, also update reconcileChildrenIterator() which
15350 // uses the same algorithm.
15351 {
15352 // First, validate keys.
15353 var knownKeys = null;
15354
15355 for (var i = 0; i < newChildren.length; i++) {
15356 var child = newChildren[i];
15357 knownKeys = warnOnInvalidKey(child, knownKeys);
15358 }
15359 }
15360
15361 var resultingFirstChild = null;
15362 var previousNewFiber = null;
15363 var oldFiber = currentFirstChild;
15364 var lastPlacedIndex = 0;
15365 var newIdx = 0;
15366 var nextOldFiber = null;
15367
15368 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
15369 if (oldFiber.index > newIdx) {
15370 nextOldFiber = oldFiber;
15371 oldFiber = null;
15372 } else {
15373 nextOldFiber = oldFiber.sibling;
15374 }
15375
15376 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
15377
15378 if (newFiber === null) {
15379 // TODO: This breaks on empty slots like null children. That's
15380 // unfortunate because it triggers the slow path all the time. We need
15381 // a better way to communicate whether this was a miss or null,
15382 // boolean, undefined, etc.
15383 if (oldFiber === null) {
15384 oldFiber = nextOldFiber;
15385 }
15386
15387 break;
15388 }
15389
15390 if (shouldTrackSideEffects) {
15391 if (oldFiber && newFiber.alternate === null) {
15392 // We matched the slot, but we didn't reuse the existing fiber, so we
15393 // need to delete the existing child.
15394 deleteChild(returnFiber, oldFiber);
15395 }
15396 }
15397
15398 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15399
15400 if (previousNewFiber === null) {
15401 // TODO: Move out of the loop. This only happens for the first run.
15402 resultingFirstChild = newFiber;
15403 } else {
15404 // TODO: Defer siblings if we're not at the right index for this slot.
15405 // I.e. if we had null values before, then we want to defer this
15406 // for each null value. However, we also don't want to call updateSlot
15407 // with the previous one.
15408 previousNewFiber.sibling = newFiber;
15409 }
15410
15411 previousNewFiber = newFiber;
15412 oldFiber = nextOldFiber;
15413 }
15414
15415 if (newIdx === newChildren.length) {
15416 // We've reached the end of the new children. We can delete the rest.
15417 deleteRemainingChildren(returnFiber, oldFiber);
15418 return resultingFirstChild;
15419 }
15420
15421 if (oldFiber === null) {
15422 // If we don't have any more existing children we can choose a fast path
15423 // since the rest will all be insertions.
15424 for (; newIdx < newChildren.length; newIdx++) {
15425 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
15426
15427 if (_newFiber === null) {
15428 continue;
15429 }
15430
15431 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
15432
15433 if (previousNewFiber === null) {
15434 // TODO: Move out of the loop. This only happens for the first run.
15435 resultingFirstChild = _newFiber;
15436 } else {
15437 previousNewFiber.sibling = _newFiber;
15438 }
15439
15440 previousNewFiber = _newFiber;
15441 }
15442
15443 return resultingFirstChild;
15444 } // Add all children to a key map for quick lookups.
15445
15446
15447 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15448
15449 for (; newIdx < newChildren.length; newIdx++) {
15450 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
15451
15452 if (_newFiber2 !== null) {
15453 if (shouldTrackSideEffects) {
15454 if (_newFiber2.alternate !== null) {
15455 // The new fiber is a work in progress, but if there exists a
15456 // current, that means that we reused the fiber. We need to delete
15457 // it from the child list so that we don't add it to the deletion
15458 // list.
15459 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
15460 }
15461 }
15462
15463 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
15464
15465 if (previousNewFiber === null) {
15466 resultingFirstChild = _newFiber2;
15467 } else {
15468 previousNewFiber.sibling = _newFiber2;
15469 }
15470
15471 previousNewFiber = _newFiber2;
15472 }
15473 }
15474
15475 if (shouldTrackSideEffects) {
15476 // Any existing children that weren't consumed above were deleted. We need
15477 // to add them to the deletion list.
15478 existingChildren.forEach(function (child) {
15479 return deleteChild(returnFiber, child);
15480 });
15481 }
15482
15483 return resultingFirstChild;
15484 }
15485
15486 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
15487 // This is the same implementation as reconcileChildrenArray(),
15488 // but using the iterator instead.
15489 var iteratorFn = getIteratorFn(newChildrenIterable);
15490
15491 (function () {
15492 if (!(typeof iteratorFn === 'function')) {
15493 {
15494 throw ReactError(Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."));
15495 }
15496 }
15497 })();
15498
15499 {
15500 // We don't support rendering Generators because it's a mutation.
15501 // See https://github.com/facebook/react/issues/12995
15502 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
15503 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
15504 !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;
15505 didWarnAboutGenerators = true;
15506 } // Warn about using Maps as children
15507
15508
15509 if (newChildrenIterable.entries === iteratorFn) {
15510 !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;
15511 didWarnAboutMaps = true;
15512 } // First, validate keys.
15513 // We'll get a different iterator later for the main pass.
15514
15515
15516 var _newChildren = iteratorFn.call(newChildrenIterable);
15517
15518 if (_newChildren) {
15519 var knownKeys = null;
15520
15521 var _step = _newChildren.next();
15522
15523 for (; !_step.done; _step = _newChildren.next()) {
15524 var child = _step.value;
15525 knownKeys = warnOnInvalidKey(child, knownKeys);
15526 }
15527 }
15528 }
15529
15530 var newChildren = iteratorFn.call(newChildrenIterable);
15531
15532 (function () {
15533 if (!(newChildren != null)) {
15534 {
15535 throw ReactError(Error("An iterable object provided no iterator."));
15536 }
15537 }
15538 })();
15539
15540 var resultingFirstChild = null;
15541 var previousNewFiber = null;
15542 var oldFiber = currentFirstChild;
15543 var lastPlacedIndex = 0;
15544 var newIdx = 0;
15545 var nextOldFiber = null;
15546 var step = newChildren.next();
15547
15548 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
15549 if (oldFiber.index > newIdx) {
15550 nextOldFiber = oldFiber;
15551 oldFiber = null;
15552 } else {
15553 nextOldFiber = oldFiber.sibling;
15554 }
15555
15556 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
15557
15558 if (newFiber === null) {
15559 // TODO: This breaks on empty slots like null children. That's
15560 // unfortunate because it triggers the slow path all the time. We need
15561 // a better way to communicate whether this was a miss or null,
15562 // boolean, undefined, etc.
15563 if (oldFiber === null) {
15564 oldFiber = nextOldFiber;
15565 }
15566
15567 break;
15568 }
15569
15570 if (shouldTrackSideEffects) {
15571 if (oldFiber && newFiber.alternate === null) {
15572 // We matched the slot, but we didn't reuse the existing fiber, so we
15573 // need to delete the existing child.
15574 deleteChild(returnFiber, oldFiber);
15575 }
15576 }
15577
15578 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15579
15580 if (previousNewFiber === null) {
15581 // TODO: Move out of the loop. This only happens for the first run.
15582 resultingFirstChild = newFiber;
15583 } else {
15584 // TODO: Defer siblings if we're not at the right index for this slot.
15585 // I.e. if we had null values before, then we want to defer this
15586 // for each null value. However, we also don't want to call updateSlot
15587 // with the previous one.
15588 previousNewFiber.sibling = newFiber;
15589 }
15590
15591 previousNewFiber = newFiber;
15592 oldFiber = nextOldFiber;
15593 }
15594
15595 if (step.done) {
15596 // We've reached the end of the new children. We can delete the rest.
15597 deleteRemainingChildren(returnFiber, oldFiber);
15598 return resultingFirstChild;
15599 }
15600
15601 if (oldFiber === null) {
15602 // If we don't have any more existing children we can choose a fast path
15603 // since the rest will all be insertions.
15604 for (; !step.done; newIdx++, step = newChildren.next()) {
15605 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
15606
15607 if (_newFiber3 === null) {
15608 continue;
15609 }
15610
15611 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
15612
15613 if (previousNewFiber === null) {
15614 // TODO: Move out of the loop. This only happens for the first run.
15615 resultingFirstChild = _newFiber3;
15616 } else {
15617 previousNewFiber.sibling = _newFiber3;
15618 }
15619
15620 previousNewFiber = _newFiber3;
15621 }
15622
15623 return resultingFirstChild;
15624 } // Add all children to a key map for quick lookups.
15625
15626
15627 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15628
15629 for (; !step.done; newIdx++, step = newChildren.next()) {
15630 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
15631
15632 if (_newFiber4 !== null) {
15633 if (shouldTrackSideEffects) {
15634 if (_newFiber4.alternate !== null) {
15635 // The new fiber is a work in progress, but if there exists a
15636 // current, that means that we reused the fiber. We need to delete
15637 // it from the child list so that we don't add it to the deletion
15638 // list.
15639 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
15640 }
15641 }
15642
15643 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
15644
15645 if (previousNewFiber === null) {
15646 resultingFirstChild = _newFiber4;
15647 } else {
15648 previousNewFiber.sibling = _newFiber4;
15649 }
15650
15651 previousNewFiber = _newFiber4;
15652 }
15653 }
15654
15655 if (shouldTrackSideEffects) {
15656 // Any existing children that weren't consumed above were deleted. We need
15657 // to add them to the deletion list.
15658 existingChildren.forEach(function (child) {
15659 return deleteChild(returnFiber, child);
15660 });
15661 }
15662
15663 return resultingFirstChild;
15664 }
15665
15666 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
15667 // There's no need to check for keys on text nodes since we don't have a
15668 // way to define them.
15669 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
15670 // We already have an existing node so let's just update it and delete
15671 // the rest.
15672 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
15673 var existing = useFiber(currentFirstChild, textContent, expirationTime);
15674 existing.return = returnFiber;
15675 return existing;
15676 } // The existing first child is not a text node so we need to create one
15677 // and delete the existing ones.
15678
15679
15680 deleteRemainingChildren(returnFiber, currentFirstChild);
15681 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15682 created.return = returnFiber;
15683 return created;
15684 }
15685
15686 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
15687 var key = element.key;
15688 var child = currentFirstChild;
15689
15690 while (child !== null) {
15691 // TODO: If key === null and child.key === null, then this only applies to
15692 // the first item in the list.
15693 if (child.key === key) {
15694 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
15695 isCompatibleFamilyForHotReloading(child, element))) {
15696 deleteRemainingChildren(returnFiber, child.sibling);
15697 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
15698 existing.ref = coerceRef(returnFiber, child, element);
15699 existing.return = returnFiber;
15700
15701 {
15702 existing._debugSource = element._source;
15703 existing._debugOwner = element._owner;
15704 }
15705
15706 return existing;
15707 } else {
15708 deleteRemainingChildren(returnFiber, child);
15709 break;
15710 }
15711 } else {
15712 deleteChild(returnFiber, child);
15713 }
15714
15715 child = child.sibling;
15716 }
15717
15718 if (element.type === REACT_FRAGMENT_TYPE) {
15719 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
15720 created.return = returnFiber;
15721 return created;
15722 } else {
15723 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
15724
15725 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
15726 _created4.return = returnFiber;
15727 return _created4;
15728 }
15729 }
15730
15731 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
15732 var key = portal.key;
15733 var child = currentFirstChild;
15734
15735 while (child !== null) {
15736 // TODO: If key === null and child.key === null, then this only applies to
15737 // the first item in the list.
15738 if (child.key === key) {
15739 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
15740 deleteRemainingChildren(returnFiber, child.sibling);
15741 var existing = useFiber(child, portal.children || [], expirationTime);
15742 existing.return = returnFiber;
15743 return existing;
15744 } else {
15745 deleteRemainingChildren(returnFiber, child);
15746 break;
15747 }
15748 } else {
15749 deleteChild(returnFiber, child);
15750 }
15751
15752 child = child.sibling;
15753 }
15754
15755 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15756 created.return = returnFiber;
15757 return created;
15758 } // This API will tag the children with the side-effect of the reconciliation
15759 // itself. They will be added to the side-effect list as we pass through the
15760 // children and the parent.
15761
15762
15763 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
15764 // This function is not recursive.
15765 // If the top level item is an array, we treat it as a set of children,
15766 // not as a fragment. Nested arrays on the other hand will be treated as
15767 // fragment nodes. Recursion happens at the normal flow.
15768 // Handle top level unkeyed fragments as if they were arrays.
15769 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
15770 // We treat the ambiguous cases above the same.
15771 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
15772
15773 if (isUnkeyedTopLevelFragment) {
15774 newChild = newChild.props.children;
15775 } // Handle object types
15776
15777
15778 var isObject = typeof newChild === 'object' && newChild !== null;
15779
15780 if (isObject) {
15781 switch (newChild.$$typeof) {
15782 case REACT_ELEMENT_TYPE:
15783 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
15784
15785 case REACT_PORTAL_TYPE:
15786 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
15787 }
15788 }
15789
15790 if (typeof newChild === 'string' || typeof newChild === 'number') {
15791 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
15792 }
15793
15794 if (isArray(newChild)) {
15795 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
15796 }
15797
15798 if (getIteratorFn(newChild)) {
15799 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
15800 }
15801
15802 if (isObject) {
15803 throwOnInvalidObjectType(returnFiber, newChild);
15804 }
15805
15806 {
15807 if (typeof newChild === 'function') {
15808 warnOnFunctionType();
15809 }
15810 }
15811
15812 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
15813 // If the new child is undefined, and the return fiber is a composite
15814 // component, throw an error. If Fiber return types are disabled,
15815 // we already threw above.
15816 switch (returnFiber.tag) {
15817 case ClassComponent:
15818 {
15819 {
15820 var instance = returnFiber.stateNode;
15821
15822 if (instance.render._isMockFunction) {
15823 // We allow auto-mocks to proceed as if they're returning null.
15824 break;
15825 }
15826 }
15827 }
15828 // Intentionally fall through to the next case, which handles both
15829 // functions and classes
15830 // eslint-disable-next-lined no-fallthrough
15831
15832 case FunctionComponent:
15833 {
15834 var Component = returnFiber.type;
15835
15836 (function () {
15837 {
15838 {
15839 throw ReactError(Error((Component.displayName || Component.name || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."));
15840 }
15841 }
15842 })();
15843 }
15844 }
15845 } // Remaining cases are all treated as empty.
15846
15847
15848 return deleteRemainingChildren(returnFiber, currentFirstChild);
15849 }
15850
15851 return reconcileChildFibers;
15852}
15853
15854var reconcileChildFibers = ChildReconciler(true);
15855var mountChildFibers = ChildReconciler(false);
15856function cloneChildFibers(current$$1, workInProgress) {
15857 (function () {
15858 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
15859 {
15860 throw ReactError(Error("Resuming work not yet implemented."));
15861 }
15862 }
15863 })();
15864
15865 if (workInProgress.child === null) {
15866 return;
15867 }
15868
15869 var currentChild = workInProgress.child;
15870 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15871 workInProgress.child = newChild;
15872 newChild.return = workInProgress;
15873
15874 while (currentChild.sibling !== null) {
15875 currentChild = currentChild.sibling;
15876 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15877 newChild.return = workInProgress;
15878 }
15879
15880 newChild.sibling = null;
15881} // Reset a workInProgress child set to prepare it for a second pass.
15882
15883function resetChildFibers(workInProgress, renderExpirationTime) {
15884 var child = workInProgress.child;
15885
15886 while (child !== null) {
15887 resetWorkInProgress(child, renderExpirationTime);
15888 child = child.sibling;
15889 }
15890}
15891
15892var NO_CONTEXT = {};
15893var contextStackCursor$1 = createCursor(NO_CONTEXT);
15894var contextFiberStackCursor = createCursor(NO_CONTEXT);
15895var rootInstanceStackCursor = createCursor(NO_CONTEXT);
15896
15897function requiredContext(c) {
15898 (function () {
15899 if (!(c !== NO_CONTEXT)) {
15900 {
15901 throw ReactError(Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."));
15902 }
15903 }
15904 })();
15905
15906 return c;
15907}
15908
15909function getRootHostContainer() {
15910 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15911 return rootInstance;
15912}
15913
15914function pushHostContainer(fiber, nextRootInstance) {
15915 // Push current root instance onto the stack;
15916 // This allows us to reset root when portals are popped.
15917 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
15918 // This enables us to pop only Fibers that provide unique contexts.
15919
15920 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
15921 // However, we can't just call getRootHostContext() and push it because
15922 // we'd have a different number of entries on the stack depending on
15923 // whether getRootHostContext() throws somewhere in renderer code or not.
15924 // So we push an empty value first. This lets us safely unwind on errors.
15925
15926 push(contextStackCursor$1, NO_CONTEXT, fiber);
15927 var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
15928
15929 pop(contextStackCursor$1, fiber);
15930 push(contextStackCursor$1, nextRootContext, fiber);
15931}
15932
15933function popHostContainer(fiber) {
15934 pop(contextStackCursor$1, fiber);
15935 pop(contextFiberStackCursor, fiber);
15936 pop(rootInstanceStackCursor, fiber);
15937}
15938
15939function getHostContext() {
15940 var context = requiredContext(contextStackCursor$1.current);
15941 return context;
15942}
15943
15944function pushHostContext(fiber) {
15945 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15946 var context = requiredContext(contextStackCursor$1.current);
15947 var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique.
15948
15949 if (context === nextContext) {
15950 return;
15951 } // Track the context and the Fiber that provided it.
15952 // This enables us to pop only Fibers that provide unique contexts.
15953
15954
15955 push(contextFiberStackCursor, fiber, fiber);
15956 push(contextStackCursor$1, nextContext, fiber);
15957}
15958
15959function popHostContext(fiber) {
15960 // Do not pop unless this Fiber provided the current context.
15961 // pushHostContext() only pushes Fibers that provide unique contexts.
15962 if (contextFiberStackCursor.current !== fiber) {
15963 return;
15964 }
15965
15966 pop(contextStackCursor$1, fiber);
15967 pop(contextFiberStackCursor, fiber);
15968}
15969
15970var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
15971// inherited deeply down the subtree. The upper bits only affect
15972// this immediate suspense boundary and gets reset each new
15973// boundary or suspense list.
15974
15975var SubtreeSuspenseContextMask = 1; // Subtree Flags:
15976// InvisibleParentSuspenseContext indicates that one of our parent Suspense
15977// boundaries is not currently showing visible main content.
15978// Either because it is already showing a fallback or is not mounted at all.
15979// We can use this to determine if it is desirable to trigger a fallback at
15980// the parent. If not, then we might need to trigger undesirable boundaries
15981// and/or suspend the commit to avoid hiding the parent content.
15982
15983var InvisibleParentSuspenseContext = 1; // Shallow Flags:
15984// ForceSuspenseFallback can be used by SuspenseList to force newly added
15985// items into their fallback state during one of the render passes.
15986
15987var ForceSuspenseFallback = 2;
15988var suspenseStackCursor = createCursor(DefaultSuspenseContext);
15989function hasSuspenseContext(parentContext, flag) {
15990 return (parentContext & flag) !== 0;
15991}
15992function setDefaultShallowSuspenseContext(parentContext) {
15993 return parentContext & SubtreeSuspenseContextMask;
15994}
15995function setShallowSuspenseContext(parentContext, shallowContext) {
15996 return parentContext & SubtreeSuspenseContextMask | shallowContext;
15997}
15998function addSubtreeSuspenseContext(parentContext, subtreeContext) {
15999 return parentContext | subtreeContext;
16000}
16001function pushSuspenseContext(fiber, newContext) {
16002 push(suspenseStackCursor, newContext, fiber);
16003}
16004function popSuspenseContext(fiber) {
16005 pop(suspenseStackCursor, fiber);
16006}
16007
16008function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
16009 // If it was the primary children that just suspended, capture and render the
16010 // fallback. Otherwise, don't capture and bubble to the next boundary.
16011 var nextState = workInProgress.memoizedState;
16012
16013 if (nextState !== null) {
16014 if (nextState.dehydrated !== null) {
16015 // A dehydrated boundary always captures.
16016 return true;
16017 }
16018
16019 return false;
16020 }
16021
16022 var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
16023
16024 if (props.fallback === undefined) {
16025 return false;
16026 } // Regular boundaries always capture.
16027
16028
16029 if (props.unstable_avoidThisFallback !== true) {
16030 return true;
16031 } // If it's a boundary we should avoid, then we prefer to bubble up to the
16032 // parent boundary if it is currently invisible.
16033
16034
16035 if (hasInvisibleParent) {
16036 return false;
16037 } // If the parent is not able to handle it, we must handle it.
16038
16039
16040 return true;
16041}
16042function findFirstSuspended(row) {
16043 var node = row;
16044
16045 while (node !== null) {
16046 if (node.tag === SuspenseComponent) {
16047 var state = node.memoizedState;
16048
16049 if (state !== null) {
16050 var dehydrated = state.dehydrated;
16051
16052 if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
16053 return node;
16054 }
16055 }
16056 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
16057 // keep track of whether it suspended or not.
16058 node.memoizedProps.revealOrder !== undefined) {
16059 var didSuspend = (node.effectTag & DidCapture) !== NoEffect;
16060
16061 if (didSuspend) {
16062 return node;
16063 }
16064 } else if (node.child !== null) {
16065 node.child.return = node;
16066 node = node.child;
16067 continue;
16068 }
16069
16070 if (node === row) {
16071 return null;
16072 }
16073
16074 while (node.sibling === null) {
16075 if (node.return === null || node.return === row) {
16076 return null;
16077 }
16078
16079 node = node.return;
16080 }
16081
16082 node.sibling.return = node.return;
16083 node = node.sibling;
16084 }
16085
16086 return null;
16087}
16088
16089var emptyObject = {};
16090var isArray$2 = Array.isArray;
16091function createResponderInstance(responder, responderProps, responderState, fiber) {
16092 return {
16093 fiber: fiber,
16094 props: responderProps,
16095 responder: responder,
16096 rootEventTypes: null,
16097 state: responderState
16098 };
16099}
16100
16101function mountEventResponder$1(responder, responderProps, fiber, respondersMap, rootContainerInstance) {
16102 var responderState = emptyObject;
16103 var getInitialState = responder.getInitialState;
16104
16105 if (getInitialState !== null) {
16106 responderState = getInitialState(responderProps);
16107 }
16108
16109 var responderInstance = createResponderInstance(responder, responderProps, responderState, fiber);
16110
16111 if (!rootContainerInstance) {
16112 var node = fiber;
16113
16114 while (node !== null) {
16115 var tag = node.tag;
16116
16117 if (tag === HostComponent) {
16118 rootContainerInstance = node.stateNode;
16119 break;
16120 } else if (tag === HostRoot) {
16121 rootContainerInstance = node.stateNode.containerInfo;
16122 break;
16123 }
16124
16125 node = node.return;
16126 }
16127 }
16128
16129 mountResponderInstance(responder, responderInstance, responderProps, responderState, rootContainerInstance);
16130 respondersMap.set(responder, responderInstance);
16131}
16132
16133function updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance) {
16134 var responder;
16135 var props;
16136
16137 if (listener) {
16138 responder = listener.responder;
16139 props = listener.props;
16140 }
16141
16142 (function () {
16143 if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) {
16144 {
16145 throw ReactError(Error("An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()."));
16146 }
16147 }
16148 })();
16149
16150 var listenerProps = props;
16151
16152 if (visistedResponders.has(responder)) {
16153 // show warning
16154 {
16155 warning$1(false, 'Duplicate event responder "%s" found in event listeners. ' + 'Event listeners passed to elements cannot use the same event responder more than once.', responder.displayName);
16156 }
16157
16158 return;
16159 }
16160
16161 visistedResponders.add(responder);
16162 var responderInstance = respondersMap.get(responder);
16163
16164 if (responderInstance === undefined) {
16165 // Mount (happens in either complete or commit phase)
16166 mountEventResponder$1(responder, listenerProps, fiber, respondersMap, rootContainerInstance);
16167 } else {
16168 // Update (happens during commit phase only)
16169 responderInstance.props = listenerProps;
16170 responderInstance.fiber = fiber;
16171 }
16172}
16173
16174function updateEventListeners(listeners, fiber, rootContainerInstance) {
16175 var visistedResponders = new Set();
16176 var dependencies = fiber.dependencies;
16177
16178 if (listeners != null) {
16179 if (dependencies === null) {
16180 dependencies = fiber.dependencies = {
16181 expirationTime: NoWork,
16182 firstContext: null,
16183 responders: new Map()
16184 };
16185 }
16186
16187 var respondersMap = dependencies.responders;
16188
16189 if (respondersMap === null) {
16190 respondersMap = new Map();
16191 }
16192
16193 if (isArray$2(listeners)) {
16194 for (var i = 0, length = listeners.length; i < length; i++) {
16195 var listener = listeners[i];
16196 updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance);
16197 }
16198 } else {
16199 updateEventListener(listeners, fiber, visistedResponders, respondersMap, rootContainerInstance);
16200 }
16201 }
16202
16203 if (dependencies !== null) {
16204 var _respondersMap = dependencies.responders;
16205
16206 if (_respondersMap !== null) {
16207 // Unmount
16208 var mountedResponders = Array.from(_respondersMap.keys());
16209
16210 for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) {
16211 var mountedResponder = mountedResponders[_i];
16212
16213 if (!visistedResponders.has(mountedResponder)) {
16214 var responderInstance = _respondersMap.get(mountedResponder);
16215
16216 unmountResponderInstance(responderInstance);
16217
16218 _respondersMap.delete(mountedResponder);
16219 }
16220 }
16221 }
16222 }
16223}
16224function createResponderListener(responder, props) {
16225 var eventResponderListener = {
16226 responder: responder,
16227 props: props
16228 };
16229
16230 {
16231 Object.freeze(eventResponderListener);
16232 }
16233
16234 return eventResponderListener;
16235}
16236
16237var NoEffect$1 =
16238/* */
162390;
16240var UnmountSnapshot =
16241/* */
162422;
16243var UnmountMutation =
16244/* */
162454;
16246var MountMutation =
16247/* */
162488;
16249var UnmountLayout =
16250/* */
1625116;
16252var MountLayout =
16253/* */
1625432;
16255var MountPassive =
16256/* */
1625764;
16258var UnmountPassive =
16259/* */
16260128;
16261
16262var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
16263var didWarnAboutMismatchedHooksForComponent;
16264
16265{
16266 didWarnAboutMismatchedHooksForComponent = new Set();
16267}
16268
16269// These are set right before calling the component.
16270var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
16271// the work-in-progress hook.
16272
16273var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
16274// current hook list is the list that belongs to the current fiber. The
16275// work-in-progress hook list is a new list that will be added to the
16276// work-in-progress fiber.
16277
16278var currentHook = null;
16279var nextCurrentHook = null;
16280var firstWorkInProgressHook = null;
16281var workInProgressHook = null;
16282var nextWorkInProgressHook = null;
16283var remainingExpirationTime = NoWork;
16284var componentUpdateQueue = null;
16285var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the
16286// end of the current pass. We can't store these updates on the normal queue,
16287// because if the work is aborted, they should be discarded. Because this is
16288// a relatively rare case, we also don't want to add an additional field to
16289// either the hook or queue object types. So we store them in a lazily create
16290// map of queue -> render-phase updates, which are discarded once the component
16291// completes without re-rendering.
16292// Whether an update was scheduled during the currently executing render pass.
16293
16294var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates
16295
16296var renderPhaseUpdates = null; // Counter to prevent infinite loops.
16297
16298var numberOfReRenders = 0;
16299var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
16300
16301var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
16302// The list stores the order of hooks used during the initial render (mount).
16303// Subsequent renders (updates) reference this list.
16304
16305var hookTypesDev = null;
16306var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
16307// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
16308// When true, such Hooks will always be "remounted". Only used during hot reload.
16309
16310var ignorePreviousDependencies = false;
16311
16312function mountHookTypesDev() {
16313 {
16314 var hookName = currentHookNameInDev;
16315
16316 if (hookTypesDev === null) {
16317 hookTypesDev = [hookName];
16318 } else {
16319 hookTypesDev.push(hookName);
16320 }
16321 }
16322}
16323
16324function updateHookTypesDev() {
16325 {
16326 var hookName = currentHookNameInDev;
16327
16328 if (hookTypesDev !== null) {
16329 hookTypesUpdateIndexDev++;
16330
16331 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
16332 warnOnHookMismatchInDev(hookName);
16333 }
16334 }
16335 }
16336}
16337
16338function checkDepsAreArrayDev(deps) {
16339 {
16340 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
16341 // Verify deps, but only on mount to avoid extra checks.
16342 // It's unlikely their type would change as usually you define them inline.
16343 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);
16344 }
16345 }
16346}
16347
16348function warnOnHookMismatchInDev(currentHookName) {
16349 {
16350 var componentName = getComponentName(currentlyRenderingFiber$1.type);
16351
16352 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
16353 didWarnAboutMismatchedHooksForComponent.add(componentName);
16354
16355 if (hookTypesDev !== null) {
16356 var table = '';
16357 var secondColumnStart = 30;
16358
16359 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
16360 var oldHookName = hookTypesDev[i];
16361 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
16362 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
16363 // lol @ IE not supporting String#repeat
16364
16365 while (row.length < secondColumnStart) {
16366 row += ' ';
16367 }
16368
16369 row += newHookName + '\n';
16370 table += row;
16371 }
16372
16373 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);
16374 }
16375 }
16376 }
16377}
16378
16379function throwInvalidHookError() {
16380 (function () {
16381 {
16382 {
16383 throw ReactError(Error("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."));
16384 }
16385 }
16386 })();
16387}
16388
16389function areHookInputsEqual(nextDeps, prevDeps) {
16390 {
16391 if (ignorePreviousDependencies) {
16392 // Only true when this component is being hot reloaded.
16393 return false;
16394 }
16395 }
16396
16397 if (prevDeps === null) {
16398 {
16399 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);
16400 }
16401
16402 return false;
16403 }
16404
16405 {
16406 // Don't bother comparing lengths in prod because these arrays should be
16407 // passed inline.
16408 if (nextDeps.length !== prevDeps.length) {
16409 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, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
16410 }
16411 }
16412
16413 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
16414 if (is$1(nextDeps[i], prevDeps[i])) {
16415 continue;
16416 }
16417
16418 return false;
16419 }
16420
16421 return true;
16422}
16423
16424function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
16425 renderExpirationTime$1 = nextRenderExpirationTime;
16426 currentlyRenderingFiber$1 = workInProgress;
16427 nextCurrentHook = current !== null ? current.memoizedState : null;
16428
16429 {
16430 hookTypesDev = current !== null ? current._debugHookTypes : null;
16431 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
16432
16433 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
16434 } // The following should have already been reset
16435 // currentHook = null;
16436 // workInProgressHook = null;
16437 // remainingExpirationTime = NoWork;
16438 // componentUpdateQueue = null;
16439 // didScheduleRenderPhaseUpdate = false;
16440 // renderPhaseUpdates = null;
16441 // numberOfReRenders = 0;
16442 // sideEffectTag = 0;
16443 // TODO Warn if no hooks are used at all during mount, then some are used during update.
16444 // Currently we will identify the update render as a mount because nextCurrentHook === null.
16445 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
16446 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
16447 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
16448 // so nextCurrentHook would be null during updates and mounts.
16449
16450
16451 {
16452 if (nextCurrentHook !== null) {
16453 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16454 } else if (hookTypesDev !== null) {
16455 // This dispatcher handles an edge case where a component is updating,
16456 // but no stateful hooks have been used.
16457 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
16458 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
16459 // This dispatcher does that.
16460 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
16461 } else {
16462 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
16463 }
16464 }
16465
16466 var children = Component(props, refOrContext);
16467
16468 if (didScheduleRenderPhaseUpdate) {
16469 do {
16470 didScheduleRenderPhaseUpdate = false;
16471 numberOfReRenders += 1;
16472
16473 {
16474 // Even when hot reloading, allow dependencies to stabilize
16475 // after first render to prevent infinite render phase updates.
16476 ignorePreviousDependencies = false;
16477 } // Start over from the beginning of the list
16478
16479
16480 nextCurrentHook = current !== null ? current.memoizedState : null;
16481 nextWorkInProgressHook = firstWorkInProgressHook;
16482 currentHook = null;
16483 workInProgressHook = null;
16484 componentUpdateQueue = null;
16485
16486 {
16487 // Also validate hook order for cascading updates.
16488 hookTypesUpdateIndexDev = -1;
16489 }
16490
16491 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16492 children = Component(props, refOrContext);
16493 } while (didScheduleRenderPhaseUpdate);
16494
16495 renderPhaseUpdates = null;
16496 numberOfReRenders = 0;
16497 } // We can assume the previous dispatcher is always this one, since we set it
16498 // at the beginning of the render phase and there's no re-entrancy.
16499
16500
16501 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
16502 var renderedWork = currentlyRenderingFiber$1;
16503 renderedWork.memoizedState = firstWorkInProgressHook;
16504 renderedWork.expirationTime = remainingExpirationTime;
16505 renderedWork.updateQueue = componentUpdateQueue;
16506 renderedWork.effectTag |= sideEffectTag;
16507
16508 {
16509 renderedWork._debugHookTypes = hookTypesDev;
16510 } // This check uses currentHook so that it works the same in DEV and prod bundles.
16511 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
16512
16513
16514 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
16515 renderExpirationTime$1 = NoWork;
16516 currentlyRenderingFiber$1 = null;
16517 currentHook = null;
16518 nextCurrentHook = null;
16519 firstWorkInProgressHook = null;
16520 workInProgressHook = null;
16521 nextWorkInProgressHook = null;
16522
16523 {
16524 currentHookNameInDev = null;
16525 hookTypesDev = null;
16526 hookTypesUpdateIndexDev = -1;
16527 }
16528
16529 remainingExpirationTime = NoWork;
16530 componentUpdateQueue = null;
16531 sideEffectTag = 0; // These were reset above
16532 // didScheduleRenderPhaseUpdate = false;
16533 // renderPhaseUpdates = null;
16534 // numberOfReRenders = 0;
16535
16536 (function () {
16537 if (!!didRenderTooFewHooks) {
16538 {
16539 throw ReactError(Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement."));
16540 }
16541 }
16542 })();
16543
16544 return children;
16545}
16546function bailoutHooks(current, workInProgress, expirationTime) {
16547 workInProgress.updateQueue = current.updateQueue;
16548 workInProgress.effectTag &= ~(Passive | Update);
16549
16550 if (current.expirationTime <= expirationTime) {
16551 current.expirationTime = NoWork;
16552 }
16553}
16554function resetHooks() {
16555 // We can assume the previous dispatcher is always this one, since we set it
16556 // at the beginning of the render phase and there's no re-entrancy.
16557 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws.
16558 // It's also called inside mountIndeterminateComponent if we determine the
16559 // component is a module-style component.
16560
16561 renderExpirationTime$1 = NoWork;
16562 currentlyRenderingFiber$1 = null;
16563 currentHook = null;
16564 nextCurrentHook = null;
16565 firstWorkInProgressHook = null;
16566 workInProgressHook = null;
16567 nextWorkInProgressHook = null;
16568
16569 {
16570 hookTypesDev = null;
16571 hookTypesUpdateIndexDev = -1;
16572 currentHookNameInDev = null;
16573 }
16574
16575 remainingExpirationTime = NoWork;
16576 componentUpdateQueue = null;
16577 sideEffectTag = 0;
16578 didScheduleRenderPhaseUpdate = false;
16579 renderPhaseUpdates = null;
16580 numberOfReRenders = 0;
16581}
16582
16583function mountWorkInProgressHook() {
16584 var hook = {
16585 memoizedState: null,
16586 baseState: null,
16587 queue: null,
16588 baseUpdate: null,
16589 next: null
16590 };
16591
16592 if (workInProgressHook === null) {
16593 // This is the first hook in the list
16594 firstWorkInProgressHook = workInProgressHook = hook;
16595 } else {
16596 // Append to the end of the list
16597 workInProgressHook = workInProgressHook.next = hook;
16598 }
16599
16600 return workInProgressHook;
16601}
16602
16603function updateWorkInProgressHook() {
16604 // This function is used both for updates and for re-renders triggered by a
16605 // render phase update. It assumes there is either a current hook we can
16606 // clone, or a work-in-progress hook from a previous render pass that we can
16607 // use as a base. When we reach the end of the base list, we must switch to
16608 // the dispatcher used for mounts.
16609 if (nextWorkInProgressHook !== null) {
16610 // There's already a work-in-progress. Reuse it.
16611 workInProgressHook = nextWorkInProgressHook;
16612 nextWorkInProgressHook = workInProgressHook.next;
16613 currentHook = nextCurrentHook;
16614 nextCurrentHook = currentHook !== null ? currentHook.next : null;
16615 } else {
16616 // Clone from the current hook.
16617 (function () {
16618 if (!(nextCurrentHook !== null)) {
16619 {
16620 throw ReactError(Error("Rendered more hooks than during the previous render."));
16621 }
16622 }
16623 })();
16624
16625 currentHook = nextCurrentHook;
16626 var newHook = {
16627 memoizedState: currentHook.memoizedState,
16628 baseState: currentHook.baseState,
16629 queue: currentHook.queue,
16630 baseUpdate: currentHook.baseUpdate,
16631 next: null
16632 };
16633
16634 if (workInProgressHook === null) {
16635 // This is the first hook in the list.
16636 workInProgressHook = firstWorkInProgressHook = newHook;
16637 } else {
16638 // Append to the end of the list.
16639 workInProgressHook = workInProgressHook.next = newHook;
16640 }
16641
16642 nextCurrentHook = currentHook.next;
16643 }
16644
16645 return workInProgressHook;
16646}
16647
16648function createFunctionComponentUpdateQueue() {
16649 return {
16650 lastEffect: null
16651 };
16652}
16653
16654function basicStateReducer(state, action) {
16655 return typeof action === 'function' ? action(state) : action;
16656}
16657
16658function mountReducer(reducer, initialArg, init) {
16659 var hook = mountWorkInProgressHook();
16660 var initialState;
16661
16662 if (init !== undefined) {
16663 initialState = init(initialArg);
16664 } else {
16665 initialState = initialArg;
16666 }
16667
16668 hook.memoizedState = hook.baseState = initialState;
16669 var queue = hook.queue = {
16670 last: null,
16671 dispatch: null,
16672 lastRenderedReducer: reducer,
16673 lastRenderedState: initialState
16674 };
16675 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16676 currentlyRenderingFiber$1, queue);
16677 return [hook.memoizedState, dispatch];
16678}
16679
16680function updateReducer(reducer, initialArg, init) {
16681 var hook = updateWorkInProgressHook();
16682 var queue = hook.queue;
16683
16684 (function () {
16685 if (!(queue !== null)) {
16686 {
16687 throw ReactError(Error("Should have a queue. This is likely a bug in React. Please file an issue."));
16688 }
16689 }
16690 })();
16691
16692 queue.lastRenderedReducer = reducer;
16693
16694 if (numberOfReRenders > 0) {
16695 // This is a re-render. Apply the new render phase updates to the previous
16696 // work-in-progress hook.
16697 var _dispatch = queue.dispatch;
16698
16699 if (renderPhaseUpdates !== null) {
16700 // Render phase updates are stored in a map of queue -> linked list
16701 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16702
16703 if (firstRenderPhaseUpdate !== undefined) {
16704 renderPhaseUpdates.delete(queue);
16705 var newState = hook.memoizedState;
16706 var update = firstRenderPhaseUpdate;
16707
16708 do {
16709 // Process this render phase update. We don't have to check the
16710 // priority because it will always be the same as the current
16711 // render's.
16712 var action = update.action;
16713 newState = reducer(newState, action);
16714 update = update.next;
16715 } while (update !== null); // Mark that the fiber performed work, but only if the new state is
16716 // different from the current state.
16717
16718
16719 if (!is$1(newState, hook.memoizedState)) {
16720 markWorkInProgressReceivedUpdate();
16721 }
16722
16723 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
16724 // the base state unless the queue is empty.
16725 // TODO: Not sure if this is the desired semantics, but it's what we
16726 // do for gDSFP. I can't remember why.
16727
16728 if (hook.baseUpdate === queue.last) {
16729 hook.baseState = newState;
16730 }
16731
16732 queue.lastRenderedState = newState;
16733 return [newState, _dispatch];
16734 }
16735 }
16736
16737 return [hook.memoizedState, _dispatch];
16738 } // The last update in the entire queue
16739
16740
16741 var last = queue.last; // The last update that is part of the base state.
16742
16743 var baseUpdate = hook.baseUpdate;
16744 var baseState = hook.baseState; // Find the first unprocessed update.
16745
16746 var first;
16747
16748 if (baseUpdate !== null) {
16749 if (last !== null) {
16750 // For the first update, the queue is a circular linked list where
16751 // `queue.last.next = queue.first`. Once the first update commits, and
16752 // the `baseUpdate` is no longer empty, we can unravel the list.
16753 last.next = null;
16754 }
16755
16756 first = baseUpdate.next;
16757 } else {
16758 first = last !== null ? last.next : null;
16759 }
16760
16761 if (first !== null) {
16762 var _newState = baseState;
16763 var newBaseState = null;
16764 var newBaseUpdate = null;
16765 var prevUpdate = baseUpdate;
16766 var _update = first;
16767 var didSkip = false;
16768
16769 do {
16770 var updateExpirationTime = _update.expirationTime;
16771
16772 if (updateExpirationTime < renderExpirationTime$1) {
16773 // Priority is insufficient. Skip this update. If this is the first
16774 // skipped update, the previous update/state is the new base
16775 // update/state.
16776 if (!didSkip) {
16777 didSkip = true;
16778 newBaseUpdate = prevUpdate;
16779 newBaseState = _newState;
16780 } // Update the remaining priority in the queue.
16781
16782
16783 if (updateExpirationTime > remainingExpirationTime) {
16784 remainingExpirationTime = updateExpirationTime;
16785 markUnprocessedUpdateTime(remainingExpirationTime);
16786 }
16787 } else {
16788 // This update does have sufficient priority.
16789 // Mark the event time of this update as relevant to this render pass.
16790 // TODO: This should ideally use the true event time of this update rather than
16791 // its priority which is a derived and not reverseable value.
16792 // TODO: We should skip this update if it was already committed but currently
16793 // we have no way of detecting the difference between a committed and suspended
16794 // update here.
16795 markRenderEventTimeAndConfig(updateExpirationTime, _update.suspenseConfig); // Process this update.
16796
16797 if (_update.eagerReducer === reducer) {
16798 // If this update was processed eagerly, and its reducer matches the
16799 // current reducer, we can use the eagerly computed state.
16800 _newState = _update.eagerState;
16801 } else {
16802 var _action = _update.action;
16803 _newState = reducer(_newState, _action);
16804 }
16805 }
16806
16807 prevUpdate = _update;
16808 _update = _update.next;
16809 } while (_update !== null && _update !== first);
16810
16811 if (!didSkip) {
16812 newBaseUpdate = prevUpdate;
16813 newBaseState = _newState;
16814 } // Mark that the fiber performed work, but only if the new state is
16815 // different from the current state.
16816
16817
16818 if (!is$1(_newState, hook.memoizedState)) {
16819 markWorkInProgressReceivedUpdate();
16820 }
16821
16822 hook.memoizedState = _newState;
16823 hook.baseUpdate = newBaseUpdate;
16824 hook.baseState = newBaseState;
16825 queue.lastRenderedState = _newState;
16826 }
16827
16828 var dispatch = queue.dispatch;
16829 return [hook.memoizedState, dispatch];
16830}
16831
16832function mountState(initialState) {
16833 var hook = mountWorkInProgressHook();
16834
16835 if (typeof initialState === 'function') {
16836 initialState = initialState();
16837 }
16838
16839 hook.memoizedState = hook.baseState = initialState;
16840 var queue = hook.queue = {
16841 last: null,
16842 dispatch: null,
16843 lastRenderedReducer: basicStateReducer,
16844 lastRenderedState: initialState
16845 };
16846 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16847 currentlyRenderingFiber$1, queue);
16848 return [hook.memoizedState, dispatch];
16849}
16850
16851function updateState(initialState) {
16852 return updateReducer(basicStateReducer, initialState);
16853}
16854
16855function pushEffect(tag, create, destroy, deps) {
16856 var effect = {
16857 tag: tag,
16858 create: create,
16859 destroy: destroy,
16860 deps: deps,
16861 // Circular
16862 next: null
16863 };
16864
16865 if (componentUpdateQueue === null) {
16866 componentUpdateQueue = createFunctionComponentUpdateQueue();
16867 componentUpdateQueue.lastEffect = effect.next = effect;
16868 } else {
16869 var lastEffect = componentUpdateQueue.lastEffect;
16870
16871 if (lastEffect === null) {
16872 componentUpdateQueue.lastEffect = effect.next = effect;
16873 } else {
16874 var firstEffect = lastEffect.next;
16875 lastEffect.next = effect;
16876 effect.next = firstEffect;
16877 componentUpdateQueue.lastEffect = effect;
16878 }
16879 }
16880
16881 return effect;
16882}
16883
16884function mountRef(initialValue) {
16885 var hook = mountWorkInProgressHook();
16886 var ref = {
16887 current: initialValue
16888 };
16889
16890 {
16891 Object.seal(ref);
16892 }
16893
16894 hook.memoizedState = ref;
16895 return ref;
16896}
16897
16898function updateRef(initialValue) {
16899 var hook = updateWorkInProgressHook();
16900 return hook.memoizedState;
16901}
16902
16903function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16904 var hook = mountWorkInProgressHook();
16905 var nextDeps = deps === undefined ? null : deps;
16906 sideEffectTag |= fiberEffectTag;
16907 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
16908}
16909
16910function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16911 var hook = updateWorkInProgressHook();
16912 var nextDeps = deps === undefined ? null : deps;
16913 var destroy = undefined;
16914
16915 if (currentHook !== null) {
16916 var prevEffect = currentHook.memoizedState;
16917 destroy = prevEffect.destroy;
16918
16919 if (nextDeps !== null) {
16920 var prevDeps = prevEffect.deps;
16921
16922 if (areHookInputsEqual(nextDeps, prevDeps)) {
16923 pushEffect(NoEffect$1, create, destroy, nextDeps);
16924 return;
16925 }
16926 }
16927 }
16928
16929 sideEffectTag |= fiberEffectTag;
16930 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
16931}
16932
16933function mountEffect(create, deps) {
16934 {
16935 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16936 if ('undefined' !== typeof jest) {
16937 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16938 }
16939 }
16940
16941 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16942}
16943
16944function updateEffect(create, deps) {
16945 {
16946 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16947 if ('undefined' !== typeof jest) {
16948 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16949 }
16950 }
16951
16952 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16953}
16954
16955function mountLayoutEffect(create, deps) {
16956 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16957}
16958
16959function updateLayoutEffect(create, deps) {
16960 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16961}
16962
16963function imperativeHandleEffect(create, ref) {
16964 if (typeof ref === 'function') {
16965 var refCallback = ref;
16966
16967 var _inst = create();
16968
16969 refCallback(_inst);
16970 return function () {
16971 refCallback(null);
16972 };
16973 } else if (ref !== null && ref !== undefined) {
16974 var refObject = ref;
16975
16976 {
16977 !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;
16978 }
16979
16980 var _inst2 = create();
16981
16982 refObject.current = _inst2;
16983 return function () {
16984 refObject.current = null;
16985 };
16986 }
16987}
16988
16989function mountImperativeHandle(ref, create, deps) {
16990 {
16991 !(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;
16992 } // TODO: If deps are provided, should we skip comparing the ref itself?
16993
16994
16995 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16996 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16997}
16998
16999function updateImperativeHandle(ref, create, deps) {
17000 {
17001 !(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;
17002 } // TODO: If deps are provided, should we skip comparing the ref itself?
17003
17004
17005 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
17006 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
17007}
17008
17009function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
17010 // The react-debug-hooks package injects its own implementation
17011 // so that e.g. DevTools can display custom hook values.
17012}
17013
17014var updateDebugValue = mountDebugValue;
17015
17016function mountCallback(callback, deps) {
17017 var hook = mountWorkInProgressHook();
17018 var nextDeps = deps === undefined ? null : deps;
17019 hook.memoizedState = [callback, nextDeps];
17020 return callback;
17021}
17022
17023function updateCallback(callback, deps) {
17024 var hook = updateWorkInProgressHook();
17025 var nextDeps = deps === undefined ? null : deps;
17026 var prevState = hook.memoizedState;
17027
17028 if (prevState !== null) {
17029 if (nextDeps !== null) {
17030 var prevDeps = prevState[1];
17031
17032 if (areHookInputsEqual(nextDeps, prevDeps)) {
17033 return prevState[0];
17034 }
17035 }
17036 }
17037
17038 hook.memoizedState = [callback, nextDeps];
17039 return callback;
17040}
17041
17042function mountMemo(nextCreate, deps) {
17043 var hook = mountWorkInProgressHook();
17044 var nextDeps = deps === undefined ? null : deps;
17045 var nextValue = nextCreate();
17046 hook.memoizedState = [nextValue, nextDeps];
17047 return nextValue;
17048}
17049
17050function updateMemo(nextCreate, deps) {
17051 var hook = updateWorkInProgressHook();
17052 var nextDeps = deps === undefined ? null : deps;
17053 var prevState = hook.memoizedState;
17054
17055 if (prevState !== null) {
17056 // Assume these are defined. If they're not, areHookInputsEqual will warn.
17057 if (nextDeps !== null) {
17058 var prevDeps = prevState[1];
17059
17060 if (areHookInputsEqual(nextDeps, prevDeps)) {
17061 return prevState[0];
17062 }
17063 }
17064 }
17065
17066 var nextValue = nextCreate();
17067 hook.memoizedState = [nextValue, nextDeps];
17068 return nextValue;
17069}
17070
17071function dispatchAction(fiber, queue, action) {
17072 (function () {
17073 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
17074 {
17075 throw ReactError(Error("Too many re-renders. React limits the number of renders to prevent an infinite loop."));
17076 }
17077 }
17078 })();
17079
17080 {
17081 !(typeof arguments[3] !== 'function') ? 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;
17082 }
17083
17084 var alternate = fiber.alternate;
17085
17086 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
17087 // This is a render phase update. Stash it in a lazily-created map of
17088 // queue -> linked list of updates. After this render pass, we'll restart
17089 // and apply the stashed updates on top of the work-in-progress hook.
17090 didScheduleRenderPhaseUpdate = true;
17091 var update = {
17092 expirationTime: renderExpirationTime$1,
17093 suspenseConfig: null,
17094 action: action,
17095 eagerReducer: null,
17096 eagerState: null,
17097 next: null
17098 };
17099
17100 {
17101 update.priority = getCurrentPriorityLevel();
17102 }
17103
17104 if (renderPhaseUpdates === null) {
17105 renderPhaseUpdates = new Map();
17106 }
17107
17108 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
17109
17110 if (firstRenderPhaseUpdate === undefined) {
17111 renderPhaseUpdates.set(queue, update);
17112 } else {
17113 // Append the update to the end of the list.
17114 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
17115
17116 while (lastRenderPhaseUpdate.next !== null) {
17117 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
17118 }
17119
17120 lastRenderPhaseUpdate.next = update;
17121 }
17122 } else {
17123 var currentTime = requestCurrentTime();
17124 var suspenseConfig = requestCurrentSuspenseConfig();
17125 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
17126 var _update2 = {
17127 expirationTime: expirationTime,
17128 suspenseConfig: suspenseConfig,
17129 action: action,
17130 eagerReducer: null,
17131 eagerState: null,
17132 next: null
17133 };
17134
17135 {
17136 _update2.priority = getCurrentPriorityLevel();
17137 } // Append the update to the end of the list.
17138
17139
17140 var last = queue.last;
17141
17142 if (last === null) {
17143 // This is the first update. Create a circular list.
17144 _update2.next = _update2;
17145 } else {
17146 var first = last.next;
17147
17148 if (first !== null) {
17149 // Still circular.
17150 _update2.next = first;
17151 }
17152
17153 last.next = _update2;
17154 }
17155
17156 queue.last = _update2;
17157
17158 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
17159 // The queue is currently empty, which means we can eagerly compute the
17160 // next state before entering the render phase. If the new state is the
17161 // same as the current state, we may be able to bail out entirely.
17162 var lastRenderedReducer = queue.lastRenderedReducer;
17163
17164 if (lastRenderedReducer !== null) {
17165 var prevDispatcher;
17166
17167 {
17168 prevDispatcher = ReactCurrentDispatcher$1.current;
17169 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17170 }
17171
17172 try {
17173 var currentState = queue.lastRenderedState;
17174 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
17175 // it, on the update object. If the reducer hasn't changed by the
17176 // time we enter the render phase, then the eager state can be used
17177 // without calling the reducer again.
17178
17179 _update2.eagerReducer = lastRenderedReducer;
17180 _update2.eagerState = eagerState;
17181
17182 if (is$1(eagerState, currentState)) {
17183 // Fast path. We can bail out without scheduling React to re-render.
17184 // It's still possible that we'll need to rebase this update later,
17185 // if the component re-renders for a different reason and by that
17186 // time the reducer has changed.
17187 return;
17188 }
17189 } catch (error) {// Suppress the error. It will throw again in the render phase.
17190 } finally {
17191 {
17192 ReactCurrentDispatcher$1.current = prevDispatcher;
17193 }
17194 }
17195 }
17196 }
17197
17198 {
17199 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
17200 if ('undefined' !== typeof jest) {
17201 warnIfNotScopedWithMatchingAct(fiber);
17202 warnIfNotCurrentlyActingUpdatesInDev(fiber);
17203 }
17204 }
17205
17206 scheduleWork(fiber, expirationTime);
17207 }
17208}
17209
17210var ContextOnlyDispatcher = {
17211 readContext: readContext,
17212 useCallback: throwInvalidHookError,
17213 useContext: throwInvalidHookError,
17214 useEffect: throwInvalidHookError,
17215 useImperativeHandle: throwInvalidHookError,
17216 useLayoutEffect: throwInvalidHookError,
17217 useMemo: throwInvalidHookError,
17218 useReducer: throwInvalidHookError,
17219 useRef: throwInvalidHookError,
17220 useState: throwInvalidHookError,
17221 useDebugValue: throwInvalidHookError,
17222 useResponder: throwInvalidHookError
17223};
17224var HooksDispatcherOnMountInDEV = null;
17225var HooksDispatcherOnMountWithHookTypesInDEV = null;
17226var HooksDispatcherOnUpdateInDEV = null;
17227var InvalidNestedHooksDispatcherOnMountInDEV = null;
17228var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
17229
17230{
17231 var warnInvalidContextAccess = function () {
17232 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().');
17233 };
17234
17235 var warnInvalidHookAccess = function () {
17236 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');
17237 };
17238
17239 HooksDispatcherOnMountInDEV = {
17240 readContext: function (context, observedBits) {
17241 return readContext(context, observedBits);
17242 },
17243 useCallback: function (callback, deps) {
17244 currentHookNameInDev = 'useCallback';
17245 mountHookTypesDev();
17246 checkDepsAreArrayDev(deps);
17247 return mountCallback(callback, deps);
17248 },
17249 useContext: function (context, observedBits) {
17250 currentHookNameInDev = 'useContext';
17251 mountHookTypesDev();
17252 return readContext(context, observedBits);
17253 },
17254 useEffect: function (create, deps) {
17255 currentHookNameInDev = 'useEffect';
17256 mountHookTypesDev();
17257 checkDepsAreArrayDev(deps);
17258 return mountEffect(create, deps);
17259 },
17260 useImperativeHandle: function (ref, create, deps) {
17261 currentHookNameInDev = 'useImperativeHandle';
17262 mountHookTypesDev();
17263 checkDepsAreArrayDev(deps);
17264 return mountImperativeHandle(ref, create, deps);
17265 },
17266 useLayoutEffect: function (create, deps) {
17267 currentHookNameInDev = 'useLayoutEffect';
17268 mountHookTypesDev();
17269 checkDepsAreArrayDev(deps);
17270 return mountLayoutEffect(create, deps);
17271 },
17272 useMemo: function (create, deps) {
17273 currentHookNameInDev = 'useMemo';
17274 mountHookTypesDev();
17275 checkDepsAreArrayDev(deps);
17276 var prevDispatcher = ReactCurrentDispatcher$1.current;
17277 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17278
17279 try {
17280 return mountMemo(create, deps);
17281 } finally {
17282 ReactCurrentDispatcher$1.current = prevDispatcher;
17283 }
17284 },
17285 useReducer: function (reducer, initialArg, init) {
17286 currentHookNameInDev = 'useReducer';
17287 mountHookTypesDev();
17288 var prevDispatcher = ReactCurrentDispatcher$1.current;
17289 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17290
17291 try {
17292 return mountReducer(reducer, initialArg, init);
17293 } finally {
17294 ReactCurrentDispatcher$1.current = prevDispatcher;
17295 }
17296 },
17297 useRef: function (initialValue) {
17298 currentHookNameInDev = 'useRef';
17299 mountHookTypesDev();
17300 return mountRef(initialValue);
17301 },
17302 useState: function (initialState) {
17303 currentHookNameInDev = 'useState';
17304 mountHookTypesDev();
17305 var prevDispatcher = ReactCurrentDispatcher$1.current;
17306 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17307
17308 try {
17309 return mountState(initialState);
17310 } finally {
17311 ReactCurrentDispatcher$1.current = prevDispatcher;
17312 }
17313 },
17314 useDebugValue: function (value, formatterFn) {
17315 currentHookNameInDev = 'useDebugValue';
17316 mountHookTypesDev();
17317 return mountDebugValue(value, formatterFn);
17318 },
17319 useResponder: function (responder, props) {
17320 currentHookNameInDev = 'useResponder';
17321 mountHookTypesDev();
17322 return createResponderListener(responder, props);
17323 }
17324 };
17325 HooksDispatcherOnMountWithHookTypesInDEV = {
17326 readContext: function (context, observedBits) {
17327 return readContext(context, observedBits);
17328 },
17329 useCallback: function (callback, deps) {
17330 currentHookNameInDev = 'useCallback';
17331 updateHookTypesDev();
17332 return mountCallback(callback, deps);
17333 },
17334 useContext: function (context, observedBits) {
17335 currentHookNameInDev = 'useContext';
17336 updateHookTypesDev();
17337 return readContext(context, observedBits);
17338 },
17339 useEffect: function (create, deps) {
17340 currentHookNameInDev = 'useEffect';
17341 updateHookTypesDev();
17342 return mountEffect(create, deps);
17343 },
17344 useImperativeHandle: function (ref, create, deps) {
17345 currentHookNameInDev = 'useImperativeHandle';
17346 updateHookTypesDev();
17347 return mountImperativeHandle(ref, create, deps);
17348 },
17349 useLayoutEffect: function (create, deps) {
17350 currentHookNameInDev = 'useLayoutEffect';
17351 updateHookTypesDev();
17352 return mountLayoutEffect(create, deps);
17353 },
17354 useMemo: function (create, deps) {
17355 currentHookNameInDev = 'useMemo';
17356 updateHookTypesDev();
17357 var prevDispatcher = ReactCurrentDispatcher$1.current;
17358 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17359
17360 try {
17361 return mountMemo(create, deps);
17362 } finally {
17363 ReactCurrentDispatcher$1.current = prevDispatcher;
17364 }
17365 },
17366 useReducer: function (reducer, initialArg, init) {
17367 currentHookNameInDev = 'useReducer';
17368 updateHookTypesDev();
17369 var prevDispatcher = ReactCurrentDispatcher$1.current;
17370 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17371
17372 try {
17373 return mountReducer(reducer, initialArg, init);
17374 } finally {
17375 ReactCurrentDispatcher$1.current = prevDispatcher;
17376 }
17377 },
17378 useRef: function (initialValue) {
17379 currentHookNameInDev = 'useRef';
17380 updateHookTypesDev();
17381 return mountRef(initialValue);
17382 },
17383 useState: function (initialState) {
17384 currentHookNameInDev = 'useState';
17385 updateHookTypesDev();
17386 var prevDispatcher = ReactCurrentDispatcher$1.current;
17387 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17388
17389 try {
17390 return mountState(initialState);
17391 } finally {
17392 ReactCurrentDispatcher$1.current = prevDispatcher;
17393 }
17394 },
17395 useDebugValue: function (value, formatterFn) {
17396 currentHookNameInDev = 'useDebugValue';
17397 updateHookTypesDev();
17398 return mountDebugValue(value, formatterFn);
17399 },
17400 useResponder: function (responder, props) {
17401 currentHookNameInDev = 'useResponder';
17402 updateHookTypesDev();
17403 return createResponderListener(responder, props);
17404 }
17405 };
17406 HooksDispatcherOnUpdateInDEV = {
17407 readContext: function (context, observedBits) {
17408 return readContext(context, observedBits);
17409 },
17410 useCallback: function (callback, deps) {
17411 currentHookNameInDev = 'useCallback';
17412 updateHookTypesDev();
17413 return updateCallback(callback, deps);
17414 },
17415 useContext: function (context, observedBits) {
17416 currentHookNameInDev = 'useContext';
17417 updateHookTypesDev();
17418 return readContext(context, observedBits);
17419 },
17420 useEffect: function (create, deps) {
17421 currentHookNameInDev = 'useEffect';
17422 updateHookTypesDev();
17423 return updateEffect(create, deps);
17424 },
17425 useImperativeHandle: function (ref, create, deps) {
17426 currentHookNameInDev = 'useImperativeHandle';
17427 updateHookTypesDev();
17428 return updateImperativeHandle(ref, create, deps);
17429 },
17430 useLayoutEffect: function (create, deps) {
17431 currentHookNameInDev = 'useLayoutEffect';
17432 updateHookTypesDev();
17433 return updateLayoutEffect(create, deps);
17434 },
17435 useMemo: function (create, deps) {
17436 currentHookNameInDev = 'useMemo';
17437 updateHookTypesDev();
17438 var prevDispatcher = ReactCurrentDispatcher$1.current;
17439 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17440
17441 try {
17442 return updateMemo(create, deps);
17443 } finally {
17444 ReactCurrentDispatcher$1.current = prevDispatcher;
17445 }
17446 },
17447 useReducer: function (reducer, initialArg, init) {
17448 currentHookNameInDev = 'useReducer';
17449 updateHookTypesDev();
17450 var prevDispatcher = ReactCurrentDispatcher$1.current;
17451 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17452
17453 try {
17454 return updateReducer(reducer, initialArg, init);
17455 } finally {
17456 ReactCurrentDispatcher$1.current = prevDispatcher;
17457 }
17458 },
17459 useRef: function (initialValue) {
17460 currentHookNameInDev = 'useRef';
17461 updateHookTypesDev();
17462 return updateRef(initialValue);
17463 },
17464 useState: function (initialState) {
17465 currentHookNameInDev = 'useState';
17466 updateHookTypesDev();
17467 var prevDispatcher = ReactCurrentDispatcher$1.current;
17468 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17469
17470 try {
17471 return updateState(initialState);
17472 } finally {
17473 ReactCurrentDispatcher$1.current = prevDispatcher;
17474 }
17475 },
17476 useDebugValue: function (value, formatterFn) {
17477 currentHookNameInDev = 'useDebugValue';
17478 updateHookTypesDev();
17479 return updateDebugValue(value, formatterFn);
17480 },
17481 useResponder: function (responder, props) {
17482 currentHookNameInDev = 'useResponder';
17483 updateHookTypesDev();
17484 return createResponderListener(responder, props);
17485 }
17486 };
17487 InvalidNestedHooksDispatcherOnMountInDEV = {
17488 readContext: function (context, observedBits) {
17489 warnInvalidContextAccess();
17490 return readContext(context, observedBits);
17491 },
17492 useCallback: function (callback, deps) {
17493 currentHookNameInDev = 'useCallback';
17494 warnInvalidHookAccess();
17495 mountHookTypesDev();
17496 return mountCallback(callback, deps);
17497 },
17498 useContext: function (context, observedBits) {
17499 currentHookNameInDev = 'useContext';
17500 warnInvalidHookAccess();
17501 mountHookTypesDev();
17502 return readContext(context, observedBits);
17503 },
17504 useEffect: function (create, deps) {
17505 currentHookNameInDev = 'useEffect';
17506 warnInvalidHookAccess();
17507 mountHookTypesDev();
17508 return mountEffect(create, deps);
17509 },
17510 useImperativeHandle: function (ref, create, deps) {
17511 currentHookNameInDev = 'useImperativeHandle';
17512 warnInvalidHookAccess();
17513 mountHookTypesDev();
17514 return mountImperativeHandle(ref, create, deps);
17515 },
17516 useLayoutEffect: function (create, deps) {
17517 currentHookNameInDev = 'useLayoutEffect';
17518 warnInvalidHookAccess();
17519 mountHookTypesDev();
17520 return mountLayoutEffect(create, deps);
17521 },
17522 useMemo: function (create, deps) {
17523 currentHookNameInDev = 'useMemo';
17524 warnInvalidHookAccess();
17525 mountHookTypesDev();
17526 var prevDispatcher = ReactCurrentDispatcher$1.current;
17527 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17528
17529 try {
17530 return mountMemo(create, deps);
17531 } finally {
17532 ReactCurrentDispatcher$1.current = prevDispatcher;
17533 }
17534 },
17535 useReducer: function (reducer, initialArg, init) {
17536 currentHookNameInDev = 'useReducer';
17537 warnInvalidHookAccess();
17538 mountHookTypesDev();
17539 var prevDispatcher = ReactCurrentDispatcher$1.current;
17540 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17541
17542 try {
17543 return mountReducer(reducer, initialArg, init);
17544 } finally {
17545 ReactCurrentDispatcher$1.current = prevDispatcher;
17546 }
17547 },
17548 useRef: function (initialValue) {
17549 currentHookNameInDev = 'useRef';
17550 warnInvalidHookAccess();
17551 mountHookTypesDev();
17552 return mountRef(initialValue);
17553 },
17554 useState: function (initialState) {
17555 currentHookNameInDev = 'useState';
17556 warnInvalidHookAccess();
17557 mountHookTypesDev();
17558 var prevDispatcher = ReactCurrentDispatcher$1.current;
17559 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17560
17561 try {
17562 return mountState(initialState);
17563 } finally {
17564 ReactCurrentDispatcher$1.current = prevDispatcher;
17565 }
17566 },
17567 useDebugValue: function (value, formatterFn) {
17568 currentHookNameInDev = 'useDebugValue';
17569 warnInvalidHookAccess();
17570 mountHookTypesDev();
17571 return mountDebugValue(value, formatterFn);
17572 },
17573 useResponder: function (responder, props) {
17574 currentHookNameInDev = 'useResponder';
17575 warnInvalidHookAccess();
17576 mountHookTypesDev();
17577 return createResponderListener(responder, props);
17578 }
17579 };
17580 InvalidNestedHooksDispatcherOnUpdateInDEV = {
17581 readContext: function (context, observedBits) {
17582 warnInvalidContextAccess();
17583 return readContext(context, observedBits);
17584 },
17585 useCallback: function (callback, deps) {
17586 currentHookNameInDev = 'useCallback';
17587 warnInvalidHookAccess();
17588 updateHookTypesDev();
17589 return updateCallback(callback, deps);
17590 },
17591 useContext: function (context, observedBits) {
17592 currentHookNameInDev = 'useContext';
17593 warnInvalidHookAccess();
17594 updateHookTypesDev();
17595 return readContext(context, observedBits);
17596 },
17597 useEffect: function (create, deps) {
17598 currentHookNameInDev = 'useEffect';
17599 warnInvalidHookAccess();
17600 updateHookTypesDev();
17601 return updateEffect(create, deps);
17602 },
17603 useImperativeHandle: function (ref, create, deps) {
17604 currentHookNameInDev = 'useImperativeHandle';
17605 warnInvalidHookAccess();
17606 updateHookTypesDev();
17607 return updateImperativeHandle(ref, create, deps);
17608 },
17609 useLayoutEffect: function (create, deps) {
17610 currentHookNameInDev = 'useLayoutEffect';
17611 warnInvalidHookAccess();
17612 updateHookTypesDev();
17613 return updateLayoutEffect(create, deps);
17614 },
17615 useMemo: function (create, deps) {
17616 currentHookNameInDev = 'useMemo';
17617 warnInvalidHookAccess();
17618 updateHookTypesDev();
17619 var prevDispatcher = ReactCurrentDispatcher$1.current;
17620 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17621
17622 try {
17623 return updateMemo(create, deps);
17624 } finally {
17625 ReactCurrentDispatcher$1.current = prevDispatcher;
17626 }
17627 },
17628 useReducer: function (reducer, initialArg, init) {
17629 currentHookNameInDev = 'useReducer';
17630 warnInvalidHookAccess();
17631 updateHookTypesDev();
17632 var prevDispatcher = ReactCurrentDispatcher$1.current;
17633 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17634
17635 try {
17636 return updateReducer(reducer, initialArg, init);
17637 } finally {
17638 ReactCurrentDispatcher$1.current = prevDispatcher;
17639 }
17640 },
17641 useRef: function (initialValue) {
17642 currentHookNameInDev = 'useRef';
17643 warnInvalidHookAccess();
17644 updateHookTypesDev();
17645 return updateRef(initialValue);
17646 },
17647 useState: function (initialState) {
17648 currentHookNameInDev = 'useState';
17649 warnInvalidHookAccess();
17650 updateHookTypesDev();
17651 var prevDispatcher = ReactCurrentDispatcher$1.current;
17652 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17653
17654 try {
17655 return updateState(initialState);
17656 } finally {
17657 ReactCurrentDispatcher$1.current = prevDispatcher;
17658 }
17659 },
17660 useDebugValue: function (value, formatterFn) {
17661 currentHookNameInDev = 'useDebugValue';
17662 warnInvalidHookAccess();
17663 updateHookTypesDev();
17664 return updateDebugValue(value, formatterFn);
17665 },
17666 useResponder: function (responder, props) {
17667 currentHookNameInDev = 'useResponder';
17668 warnInvalidHookAccess();
17669 updateHookTypesDev();
17670 return createResponderListener(responder, props);
17671 }
17672 };
17673}
17674
17675// CommonJS interop named imports.
17676
17677var now$1 = unstable_now;
17678var commitTime = 0;
17679var profilerStartTime = -1;
17680
17681function getCommitTime() {
17682 return commitTime;
17683}
17684
17685function recordCommitTime() {
17686 if (!enableProfilerTimer) {
17687 return;
17688 }
17689
17690 commitTime = now$1();
17691}
17692
17693function startProfilerTimer(fiber) {
17694 if (!enableProfilerTimer) {
17695 return;
17696 }
17697
17698 profilerStartTime = now$1();
17699
17700 if (fiber.actualStartTime < 0) {
17701 fiber.actualStartTime = now$1();
17702 }
17703}
17704
17705function stopProfilerTimerIfRunning(fiber) {
17706 if (!enableProfilerTimer) {
17707 return;
17708 }
17709
17710 profilerStartTime = -1;
17711}
17712
17713function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
17714 if (!enableProfilerTimer) {
17715 return;
17716 }
17717
17718 if (profilerStartTime >= 0) {
17719 var elapsedTime = now$1() - profilerStartTime;
17720 fiber.actualDuration += elapsedTime;
17721
17722 if (overrideBaseTime) {
17723 fiber.selfBaseDuration = elapsedTime;
17724 }
17725
17726 profilerStartTime = -1;
17727 }
17728}
17729
17730// This may have been an insertion or a hydration.
17731
17732var hydrationParentFiber = null;
17733var nextHydratableInstance = null;
17734var isHydrating = false;
17735
17736function warnIfHydrating() {
17737 {
17738 !!isHydrating ? warning$1(false, 'We should not be hydrating here. This is a bug in React. Please file a bug.') : void 0;
17739 }
17740}
17741
17742function enterHydrationState(fiber) {
17743 if (!supportsHydration) {
17744 return false;
17745 }
17746
17747 var parentInstance = fiber.stateNode.containerInfo;
17748 nextHydratableInstance = getFirstHydratableChild(parentInstance);
17749 hydrationParentFiber = fiber;
17750 isHydrating = true;
17751 return true;
17752}
17753
17754function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance) {
17755 if (!supportsHydration) {
17756 return false;
17757 }
17758
17759 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
17760 popToNextHostParent(fiber);
17761 isHydrating = true;
17762 return true;
17763}
17764
17765function deleteHydratableInstance(returnFiber, instance) {
17766 {
17767 switch (returnFiber.tag) {
17768 case HostRoot:
17769 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
17770 break;
17771
17772 case HostComponent:
17773 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
17774 break;
17775 }
17776 }
17777
17778 var childToDelete = createFiberFromHostInstanceForDeletion();
17779 childToDelete.stateNode = instance;
17780 childToDelete.return = returnFiber;
17781 childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
17782 // these children are not part of the reconciliation list of children.
17783 // Even if we abort and rereconcile the children, that will try to hydrate
17784 // again and the nodes are still in the host tree so these will be
17785 // recreated.
17786
17787 if (returnFiber.lastEffect !== null) {
17788 returnFiber.lastEffect.nextEffect = childToDelete;
17789 returnFiber.lastEffect = childToDelete;
17790 } else {
17791 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
17792 }
17793}
17794
17795function insertNonHydratedInstance(returnFiber, fiber) {
17796 fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
17797
17798 {
17799 switch (returnFiber.tag) {
17800 case HostRoot:
17801 {
17802 var parentContainer = returnFiber.stateNode.containerInfo;
17803
17804 switch (fiber.tag) {
17805 case HostComponent:
17806 var type = fiber.type;
17807 var props = fiber.pendingProps;
17808 didNotFindHydratableContainerInstance(parentContainer, type, props);
17809 break;
17810
17811 case HostText:
17812 var text = fiber.pendingProps;
17813 didNotFindHydratableContainerTextInstance(parentContainer, text);
17814 break;
17815
17816 case SuspenseComponent:
17817
17818 break;
17819 }
17820
17821 break;
17822 }
17823
17824 case HostComponent:
17825 {
17826 var parentType = returnFiber.type;
17827 var parentProps = returnFiber.memoizedProps;
17828 var parentInstance = returnFiber.stateNode;
17829
17830 switch (fiber.tag) {
17831 case HostComponent:
17832 var _type = fiber.type;
17833 var _props = fiber.pendingProps;
17834 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
17835 break;
17836
17837 case HostText:
17838 var _text = fiber.pendingProps;
17839 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
17840 break;
17841
17842 case SuspenseComponent:
17843 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
17844 break;
17845 }
17846
17847 break;
17848 }
17849
17850 default:
17851 return;
17852 }
17853 }
17854}
17855
17856function tryHydrate(fiber, nextInstance) {
17857 switch (fiber.tag) {
17858 case HostComponent:
17859 {
17860 var type = fiber.type;
17861 var props = fiber.pendingProps;
17862 var instance = canHydrateInstance(nextInstance, type, props);
17863
17864 if (instance !== null) {
17865 fiber.stateNode = instance;
17866 return true;
17867 }
17868
17869 return false;
17870 }
17871
17872 case HostText:
17873 {
17874 var text = fiber.pendingProps;
17875 var textInstance = canHydrateTextInstance(nextInstance, text);
17876
17877 if (textInstance !== null) {
17878 fiber.stateNode = textInstance;
17879 return true;
17880 }
17881
17882 return false;
17883 }
17884
17885 case SuspenseComponent:
17886 {
17887 if (enableSuspenseServerRenderer) {
17888 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
17889
17890 if (suspenseInstance !== null) {
17891 var suspenseState = {
17892 dehydrated: suspenseInstance,
17893 retryTime: Never
17894 };
17895 fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
17896 // This simplifies the code for getHostSibling and deleting nodes,
17897 // since it doesn't have to consider all Suspense boundaries and
17898 // check if they're dehydrated ones or not.
17899
17900 var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
17901 dehydratedFragment.return = fiber;
17902 fiber.child = dehydratedFragment;
17903 return true;
17904 }
17905 }
17906
17907 return false;
17908 }
17909
17910 default:
17911 return false;
17912 }
17913}
17914
17915function tryToClaimNextHydratableInstance(fiber) {
17916 if (!isHydrating) {
17917 return;
17918 }
17919
17920 var nextInstance = nextHydratableInstance;
17921
17922 if (!nextInstance) {
17923 // Nothing to hydrate. Make it an insertion.
17924 insertNonHydratedInstance(hydrationParentFiber, fiber);
17925 isHydrating = false;
17926 hydrationParentFiber = fiber;
17927 return;
17928 }
17929
17930 var firstAttemptedInstance = nextInstance;
17931
17932 if (!tryHydrate(fiber, nextInstance)) {
17933 // If we can't hydrate this instance let's try the next one.
17934 // We use this as a heuristic. It's based on intuition and not data so it
17935 // might be flawed or unnecessary.
17936 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
17937
17938 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
17939 // Nothing to hydrate. Make it an insertion.
17940 insertNonHydratedInstance(hydrationParentFiber, fiber);
17941 isHydrating = false;
17942 hydrationParentFiber = fiber;
17943 return;
17944 } // We matched the next one, we'll now assume that the first one was
17945 // superfluous and we'll delete it. Since we can't eagerly delete it
17946 // we'll have to schedule a deletion. To do that, this node needs a dummy
17947 // fiber associated with it.
17948
17949
17950 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
17951 }
17952
17953 hydrationParentFiber = fiber;
17954 nextHydratableInstance = getFirstHydratableChild(nextInstance);
17955}
17956
17957function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
17958 if (!supportsHydration) {
17959 (function () {
17960 {
17961 {
17962 throw ReactError(Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17963 }
17964 }
17965 })();
17966 }
17967
17968 var instance = fiber.stateNode;
17969 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.
17970
17971 fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
17972 // is a new ref we mark this as an update.
17973
17974 if (updatePayload !== null) {
17975 return true;
17976 }
17977
17978 return false;
17979}
17980
17981function prepareToHydrateHostTextInstance(fiber) {
17982 if (!supportsHydration) {
17983 (function () {
17984 {
17985 {
17986 throw ReactError(Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
17987 }
17988 }
17989 })();
17990 }
17991
17992 var textInstance = fiber.stateNode;
17993 var textContent = fiber.memoizedProps;
17994 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
17995
17996 {
17997 if (shouldUpdate) {
17998 // We assume that prepareToHydrateHostTextInstance is called in a context where the
17999 // hydration parent is the parent host component of this host text.
18000 var returnFiber = hydrationParentFiber;
18001
18002 if (returnFiber !== null) {
18003 switch (returnFiber.tag) {
18004 case HostRoot:
18005 {
18006 var parentContainer = returnFiber.stateNode.containerInfo;
18007 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
18008 break;
18009 }
18010
18011 case HostComponent:
18012 {
18013 var parentType = returnFiber.type;
18014 var parentProps = returnFiber.memoizedProps;
18015 var parentInstance = returnFiber.stateNode;
18016 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
18017 break;
18018 }
18019 }
18020 }
18021 }
18022 }
18023
18024 return shouldUpdate;
18025}
18026
18027function prepareToHydrateHostSuspenseInstance(fiber) {
18028 if (!supportsHydration) {
18029 (function () {
18030 {
18031 {
18032 throw ReactError(Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
18033 }
18034 }
18035 })();
18036 }
18037
18038 var suspenseState = fiber.memoizedState;
18039 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
18040
18041 (function () {
18042 if (!suspenseInstance) {
18043 {
18044 throw ReactError(Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."));
18045 }
18046 }
18047 })();
18048
18049 hydrateSuspenseInstance(suspenseInstance, fiber);
18050}
18051
18052function skipPastDehydratedSuspenseInstance(fiber) {
18053 if (!supportsHydration) {
18054 (function () {
18055 {
18056 {
18057 throw ReactError(Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue."));
18058 }
18059 }
18060 })();
18061 }
18062
18063 var suspenseState = fiber.memoizedState;
18064 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
18065
18066 if (suspenseInstance === null) {
18067 // This Suspense boundary was hydrated without a match.
18068 return nextHydratableInstance;
18069 }
18070
18071 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
18072}
18073
18074function popToNextHostParent(fiber) {
18075 var parent = fiber.return;
18076
18077 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
18078 parent = parent.return;
18079 }
18080
18081 hydrationParentFiber = parent;
18082}
18083
18084function popHydrationState(fiber) {
18085 if (!supportsHydration) {
18086 return false;
18087 }
18088
18089 if (fiber !== hydrationParentFiber) {
18090 // We're deeper than the current hydration context, inside an inserted
18091 // tree.
18092 return false;
18093 }
18094
18095 if (!isHydrating) {
18096 // If we're not currently hydrating but we're in a hydration context, then
18097 // we were an insertion and now need to pop up reenter hydration of our
18098 // siblings.
18099 popToNextHostParent(fiber);
18100 isHydrating = true;
18101 return false;
18102 }
18103
18104 var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
18105 // We only do this deeper than head and body since they tend to have random
18106 // other nodes in them. We also ignore components with pure text content in
18107 // side of them.
18108 // TODO: Better heuristic.
18109
18110 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
18111 var nextInstance = nextHydratableInstance;
18112
18113 while (nextInstance) {
18114 deleteHydratableInstance(fiber, nextInstance);
18115 nextInstance = getNextHydratableSibling(nextInstance);
18116 }
18117 }
18118
18119 popToNextHostParent(fiber);
18120
18121 if (fiber.tag === SuspenseComponent) {
18122 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
18123 } else {
18124 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
18125 }
18126
18127 return true;
18128}
18129
18130function resetHydrationState() {
18131 if (!supportsHydration) {
18132 return;
18133 }
18134
18135 hydrationParentFiber = null;
18136 nextHydratableInstance = null;
18137 isHydrating = false;
18138}
18139
18140var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
18141var didReceiveUpdate = false;
18142var didWarnAboutBadClass;
18143var didWarnAboutModulePatternComponent;
18144var didWarnAboutContextTypeOnFunctionComponent;
18145var didWarnAboutGetDerivedStateOnFunctionComponent;
18146var didWarnAboutFunctionRefs;
18147var didWarnAboutReassigningProps;
18148var didWarnAboutMaxDuration;
18149var didWarnAboutRevealOrder;
18150var didWarnAboutTailOptions;
18151var didWarnAboutDefaultPropsOnFunctionComponent;
18152
18153{
18154 didWarnAboutBadClass = {};
18155 didWarnAboutModulePatternComponent = {};
18156 didWarnAboutContextTypeOnFunctionComponent = {};
18157 didWarnAboutGetDerivedStateOnFunctionComponent = {};
18158 didWarnAboutFunctionRefs = {};
18159 didWarnAboutReassigningProps = false;
18160 didWarnAboutMaxDuration = false;
18161 didWarnAboutRevealOrder = {};
18162 didWarnAboutTailOptions = {};
18163 didWarnAboutDefaultPropsOnFunctionComponent = {};
18164}
18165
18166function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18167 if (current$$1 === null) {
18168 // If this is a fresh new component that hasn't been rendered yet, we
18169 // won't update its child set by applying minimal side-effects. Instead,
18170 // we will add them all to the child before it gets rendered. That means
18171 // we can optimize this reconciliation pass by not tracking side-effects.
18172 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18173 } else {
18174 // If the current child is the same as the work in progress, it means that
18175 // we haven't yet started any work on these children. Therefore, we use
18176 // the clone algorithm to create a copy of all the current children.
18177 // If we had any progressed work already, that is invalid at this point so
18178 // let's throw it out.
18179 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
18180 }
18181}
18182
18183function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18184 // This function is fork of reconcileChildren. It's used in cases where we
18185 // want to reconcile without matching against the existing set. This has the
18186 // effect of all current children being unmounted; even if the type and key
18187 // are the same, the old child is unmounted and a new child is created.
18188 //
18189 // To do this, we're going to go through the reconcile algorithm twice. In
18190 // the first pass, we schedule a deletion for all the current children by
18191 // passing null.
18192 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
18193 // pass null in place of where we usually pass the current child set. This has
18194 // the effect of remounting all children regardless of whether their their
18195 // identity matches.
18196
18197 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18198}
18199
18200function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18201 // TODO: current can be non-null here even if the component
18202 // hasn't yet mounted. This happens after the first render suspends.
18203 // We'll need to figure out if this is fine or can cause issues.
18204 {
18205 if (workInProgress.type !== workInProgress.elementType) {
18206 // Lazy component props can't be validated in createElement
18207 // because they're only guaranteed to be resolved here.
18208 var innerPropTypes = Component.propTypes;
18209
18210 if (innerPropTypes) {
18211 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18212 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18213 }
18214 }
18215 }
18216
18217 var render = Component.render;
18218 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
18219
18220 var nextChildren;
18221 prepareToReadContext(workInProgress, renderExpirationTime);
18222
18223 {
18224 ReactCurrentOwner$3.current = workInProgress;
18225 setCurrentPhase('render');
18226 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18227
18228 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18229 // Only double-render components with Hooks
18230 if (workInProgress.memoizedState !== null) {
18231 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18232 }
18233 }
18234
18235 setCurrentPhase(null);
18236 }
18237
18238 if (current$$1 !== null && !didReceiveUpdate) {
18239 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18240 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18241 } // React DevTools reads this flag.
18242
18243
18244 workInProgress.effectTag |= PerformedWork;
18245 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18246 return workInProgress.child;
18247}
18248
18249function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18250 if (current$$1 === null) {
18251 var type = Component.type;
18252
18253 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
18254 Component.defaultProps === undefined) {
18255 var resolvedType = type;
18256
18257 {
18258 resolvedType = resolveFunctionForHotReloading(type);
18259 } // If this is a plain function component without default props,
18260 // and with only the default shallow comparison, we upgrade it
18261 // to a SimpleMemoComponent to allow fast path updates.
18262
18263
18264 workInProgress.tag = SimpleMemoComponent;
18265 workInProgress.type = resolvedType;
18266
18267 {
18268 validateFunctionComponentInDev(workInProgress, type);
18269 }
18270
18271 return updateSimpleMemoComponent(current$$1, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
18272 }
18273
18274 {
18275 var innerPropTypes = type.propTypes;
18276
18277 if (innerPropTypes) {
18278 // Inner memo component props aren't currently validated in createElement.
18279 // We could move it there, but we'd still need this for lazy code path.
18280 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18281 'prop', getComponentName(type), getCurrentFiberStackInDev);
18282 }
18283 }
18284
18285 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
18286 child.ref = workInProgress.ref;
18287 child.return = workInProgress;
18288 workInProgress.child = child;
18289 return child;
18290 }
18291
18292 {
18293 var _type = Component.type;
18294 var _innerPropTypes = _type.propTypes;
18295
18296 if (_innerPropTypes) {
18297 // Inner memo component props aren't currently validated in createElement.
18298 // We could move it there, but we'd still need this for lazy code path.
18299 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
18300 'prop', getComponentName(_type), getCurrentFiberStackInDev);
18301 }
18302 }
18303
18304 var currentChild = current$$1.child; // This is always exactly one child
18305
18306 if (updateExpirationTime < renderExpirationTime) {
18307 // This will be the props with resolved defaultProps,
18308 // unlike current.memoizedProps which will be the unresolved ones.
18309 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
18310
18311 var compare = Component.compare;
18312 compare = compare !== null ? compare : shallowEqual;
18313
18314 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
18315 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18316 }
18317 } // React DevTools reads this flag.
18318
18319
18320 workInProgress.effectTag |= PerformedWork;
18321 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
18322 newChild.ref = workInProgress.ref;
18323 newChild.return = workInProgress;
18324 workInProgress.child = newChild;
18325 return newChild;
18326}
18327
18328function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18329 // TODO: current can be non-null here even if the component
18330 // hasn't yet mounted. This happens when the inner render suspends.
18331 // We'll need to figure out if this is fine or can cause issues.
18332 {
18333 if (workInProgress.type !== workInProgress.elementType) {
18334 // Lazy component props can't be validated in createElement
18335 // because they're only guaranteed to be resolved here.
18336 var outerMemoType = workInProgress.elementType;
18337
18338 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
18339 // We warn when you define propTypes on lazy()
18340 // so let's just skip over it to find memo() outer wrapper.
18341 // Inner props for memo are validated later.
18342 outerMemoType = refineResolvedLazyComponent(outerMemoType);
18343 }
18344
18345 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
18346
18347 if (outerPropTypes) {
18348 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
18349 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
18350 } // Inner propTypes will be validated in the function component path.
18351
18352 }
18353 }
18354
18355 if (current$$1 !== null) {
18356 var prevProps = current$$1.memoizedProps;
18357
18358 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload:
18359 workInProgress.type === current$$1.type)) {
18360 didReceiveUpdate = false;
18361
18362 if (updateExpirationTime < renderExpirationTime) {
18363 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18364 }
18365 }
18366 }
18367
18368 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18369}
18370
18371function updateFragment(current$$1, workInProgress, renderExpirationTime) {
18372 var nextChildren = workInProgress.pendingProps;
18373 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18374 return workInProgress.child;
18375}
18376
18377function updateMode(current$$1, workInProgress, renderExpirationTime) {
18378 var nextChildren = workInProgress.pendingProps.children;
18379 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18380 return workInProgress.child;
18381}
18382
18383function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
18384 if (enableProfilerTimer) {
18385 workInProgress.effectTag |= Update;
18386 }
18387
18388 var nextProps = workInProgress.pendingProps;
18389 var nextChildren = nextProps.children;
18390 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18391 return workInProgress.child;
18392}
18393
18394function markRef(current$$1, workInProgress) {
18395 var ref = workInProgress.ref;
18396
18397 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
18398 // Schedule a Ref effect
18399 workInProgress.effectTag |= Ref;
18400 }
18401}
18402
18403function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18404 {
18405 if (workInProgress.type !== workInProgress.elementType) {
18406 // Lazy component props can't be validated in createElement
18407 // because they're only guaranteed to be resolved here.
18408 var innerPropTypes = Component.propTypes;
18409
18410 if (innerPropTypes) {
18411 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18412 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18413 }
18414 }
18415 }
18416
18417 var context;
18418
18419 if (!disableLegacyContext) {
18420 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
18421 context = getMaskedContext(workInProgress, unmaskedContext);
18422 }
18423
18424 var nextChildren;
18425 prepareToReadContext(workInProgress, renderExpirationTime);
18426
18427 {
18428 ReactCurrentOwner$3.current = workInProgress;
18429 setCurrentPhase('render');
18430 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18431
18432 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18433 // Only double-render components with Hooks
18434 if (workInProgress.memoizedState !== null) {
18435 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18436 }
18437 }
18438
18439 setCurrentPhase(null);
18440 }
18441
18442 if (current$$1 !== null && !didReceiveUpdate) {
18443 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18444 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18445 } // React DevTools reads this flag.
18446
18447
18448 workInProgress.effectTag |= PerformedWork;
18449 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18450 return workInProgress.child;
18451}
18452
18453function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18454 {
18455 if (workInProgress.type !== workInProgress.elementType) {
18456 // Lazy component props can't be validated in createElement
18457 // because they're only guaranteed to be resolved here.
18458 var innerPropTypes = Component.propTypes;
18459
18460 if (innerPropTypes) {
18461 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18462 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18463 }
18464 }
18465 } // Push context providers early to prevent context stack mismatches.
18466 // During mounting we don't know the child context yet as the instance doesn't exist.
18467 // We will invalidate the child context in finishClassComponent() right after rendering.
18468
18469
18470 var hasContext;
18471
18472 if (isContextProvider(Component)) {
18473 hasContext = true;
18474 pushContextProvider(workInProgress);
18475 } else {
18476 hasContext = false;
18477 }
18478
18479 prepareToReadContext(workInProgress, renderExpirationTime);
18480 var instance = workInProgress.stateNode;
18481 var shouldUpdate;
18482
18483 if (instance === null) {
18484 if (current$$1 !== null) {
18485 // An class component without an instance only mounts if it suspended
18486 // inside a non- concurrent tree, in an inconsistent state. We want to
18487 // tree it like a new mount, even though an empty version of it already
18488 // committed. Disconnect the alternate pointers.
18489 current$$1.alternate = null;
18490 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18491
18492 workInProgress.effectTag |= Placement;
18493 } // In the initial pass we might need to construct the instance.
18494
18495
18496 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18497 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18498 shouldUpdate = true;
18499 } else if (current$$1 === null) {
18500 // In a resume, we'll already have an instance we can reuse.
18501 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18502 } else {
18503 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18504 }
18505
18506 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
18507
18508 {
18509 var inst = workInProgress.stateNode;
18510
18511 if (inst.props !== nextProps) {
18512 !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;
18513 didWarnAboutReassigningProps = true;
18514 }
18515 }
18516
18517 return nextUnitOfWork;
18518}
18519
18520function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
18521 // Refs should update even if shouldComponentUpdate returns false
18522 markRef(current$$1, workInProgress);
18523 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
18524
18525 if (!shouldUpdate && !didCaptureError) {
18526 // Context providers should defer to sCU for rendering
18527 if (hasContext) {
18528 invalidateContextProvider(workInProgress, Component, false);
18529 }
18530
18531 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18532 }
18533
18534 var instance = workInProgress.stateNode; // Rerender
18535
18536 ReactCurrentOwner$3.current = workInProgress;
18537 var nextChildren;
18538
18539 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
18540 // If we captured an error, but getDerivedStateFrom catch is not defined,
18541 // unmount all the children. componentDidCatch will schedule an update to
18542 // re-render a fallback. This is temporary until we migrate everyone to
18543 // the new API.
18544 // TODO: Warn in a future release.
18545 nextChildren = null;
18546
18547 if (enableProfilerTimer) {
18548 stopProfilerTimerIfRunning(workInProgress);
18549 }
18550 } else {
18551 {
18552 setCurrentPhase('render');
18553 nextChildren = instance.render();
18554
18555 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18556 instance.render();
18557 }
18558
18559 setCurrentPhase(null);
18560 }
18561 } // React DevTools reads this flag.
18562
18563
18564 workInProgress.effectTag |= PerformedWork;
18565
18566 if (current$$1 !== null && didCaptureError) {
18567 // If we're recovering from an error, reconcile without reusing any of
18568 // the existing children. Conceptually, the normal children and the children
18569 // that are shown on error are two different sets, so we shouldn't reuse
18570 // normal children even if their identities match.
18571 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
18572 } else {
18573 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18574 } // Memoize state using the values we just used to render.
18575 // TODO: Restructure so we never read values from the instance.
18576
18577
18578 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
18579
18580 if (hasContext) {
18581 invalidateContextProvider(workInProgress, Component, true);
18582 }
18583
18584 return workInProgress.child;
18585}
18586
18587function pushHostRootContext(workInProgress) {
18588 var root = workInProgress.stateNode;
18589
18590 if (root.pendingContext) {
18591 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
18592 } else if (root.context) {
18593 // Should always be set
18594 pushTopLevelContextObject(workInProgress, root.context, false);
18595 }
18596
18597 pushHostContainer(workInProgress, root.containerInfo);
18598}
18599
18600function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
18601 pushHostRootContext(workInProgress);
18602 var updateQueue = workInProgress.updateQueue;
18603
18604 (function () {
18605 if (!(updateQueue !== null)) {
18606 {
18607 throw ReactError(Error("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."));
18608 }
18609 }
18610 })();
18611
18612 var nextProps = workInProgress.pendingProps;
18613 var prevState = workInProgress.memoizedState;
18614 var prevChildren = prevState !== null ? prevState.element : null;
18615 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
18616 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
18617 // being called "element".
18618
18619 var nextChildren = nextState.element;
18620
18621 if (nextChildren === prevChildren) {
18622 // If the state is the same as before, that's a bailout because we had
18623 // no work that expires at this time.
18624 resetHydrationState();
18625 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18626 }
18627
18628 var root = workInProgress.stateNode;
18629
18630 if (root.hydrate && enterHydrationState(workInProgress)) {
18631 // If we don't have any current children this might be the first pass.
18632 // We always try to hydrate. If this isn't a hydration pass there won't
18633 // be any children to hydrate which is effectively the same thing as
18634 // not hydrating.
18635 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18636 workInProgress.child = child;
18637 var node = child;
18638
18639 while (node) {
18640 // Mark each child as hydrating. This is a fast path to know whether this
18641 // tree is part of a hydrating tree. This is used to determine if a child
18642 // node has fully mounted yet, and for scheduling event replaying.
18643 // Conceptually this is similar to Placement in that a new subtree is
18644 // inserted into the React tree here. It just happens to not need DOM
18645 // mutations because it already exists.
18646 node.effectTag = node.effectTag & ~Placement | Hydrating;
18647 node = node.sibling;
18648 }
18649 } else {
18650 // Otherwise reset hydration state in case we aborted and resumed another
18651 // root.
18652 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18653 resetHydrationState();
18654 }
18655
18656 return workInProgress.child;
18657}
18658
18659function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
18660 pushHostContext(workInProgress);
18661
18662 if (current$$1 === null) {
18663 tryToClaimNextHydratableInstance(workInProgress);
18664 }
18665
18666 var type = workInProgress.type;
18667 var nextProps = workInProgress.pendingProps;
18668 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
18669 var nextChildren = nextProps.children;
18670 var isDirectTextChild = shouldSetTextContent(type, nextProps);
18671
18672 if (isDirectTextChild) {
18673 // We special case a direct text child of a host node. This is a common
18674 // case. We won't handle it as a reified child. We will instead handle
18675 // this in the host environment that also have access to this prop. That
18676 // avoids allocating another HostText fiber and traversing it.
18677 nextChildren = null;
18678 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
18679 // If we're switching from a direct text child to a normal child, or to
18680 // empty, we need to schedule the text content to be reset.
18681 workInProgress.effectTag |= ContentReset;
18682 }
18683
18684 markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden.
18685
18686 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
18687 if (enableSchedulerTracing) {
18688 markSpawnedWork(Never);
18689 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
18690
18691
18692 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
18693 return null;
18694 }
18695
18696 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18697 return workInProgress.child;
18698}
18699
18700function updateHostText(current$$1, workInProgress) {
18701 if (current$$1 === null) {
18702 tryToClaimNextHydratableInstance(workInProgress);
18703 } // Nothing to do here. This is terminal. We'll do the completion step
18704 // immediately after.
18705
18706
18707 return null;
18708}
18709
18710function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
18711 if (_current !== null) {
18712 // An lazy component only mounts if it suspended inside a non-
18713 // concurrent tree, in an inconsistent state. We want to treat it like
18714 // a new mount, even though an empty version of it already committed.
18715 // Disconnect the alternate pointers.
18716 _current.alternate = null;
18717 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18718
18719 workInProgress.effectTag |= Placement;
18720 }
18721
18722 var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
18723 // Cancel and resume right after we know the tag.
18724
18725 cancelWorkTimer(workInProgress);
18726 var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
18727
18728 workInProgress.type = Component;
18729 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
18730 startWorkTimer(workInProgress);
18731 var resolvedProps = resolveDefaultProps(Component, props);
18732 var child;
18733
18734 switch (resolvedTag) {
18735 case FunctionComponent:
18736 {
18737 {
18738 validateFunctionComponentInDev(workInProgress, Component);
18739 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
18740 }
18741
18742 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18743 break;
18744 }
18745
18746 case ClassComponent:
18747 {
18748 {
18749 workInProgress.type = Component = resolveClassForHotReloading(Component);
18750 }
18751
18752 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18753 break;
18754 }
18755
18756 case ForwardRef:
18757 {
18758 {
18759 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
18760 }
18761
18762 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18763 break;
18764 }
18765
18766 case MemoComponent:
18767 {
18768 {
18769 if (workInProgress.type !== workInProgress.elementType) {
18770 var outerPropTypes = Component.propTypes;
18771
18772 if (outerPropTypes) {
18773 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
18774 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18775 }
18776 }
18777 }
18778
18779 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
18780 updateExpirationTime, renderExpirationTime);
18781 break;
18782 }
18783
18784 default:
18785 {
18786 var hint = '';
18787
18788 {
18789 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
18790 hint = ' Did you wrap a component in React.lazy() more than once?';
18791 }
18792 } // This message intentionally doesn't mention ForwardRef or MemoComponent
18793 // because the fact that it's a separate type of work is an
18794 // implementation detail.
18795
18796
18797 (function () {
18798 {
18799 {
18800 throw ReactError(Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint));
18801 }
18802 }
18803 })();
18804 }
18805 }
18806
18807 return child;
18808}
18809
18810function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
18811 if (_current !== null) {
18812 // An incomplete component only mounts if it suspended inside a non-
18813 // concurrent tree, in an inconsistent state. We want to treat it like
18814 // a new mount, even though an empty version of it already committed.
18815 // Disconnect the alternate pointers.
18816 _current.alternate = null;
18817 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18818
18819 workInProgress.effectTag |= Placement;
18820 } // Promote the fiber to a class and try rendering again.
18821
18822
18823 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
18824 // Push context providers early to prevent context stack mismatches.
18825 // During mounting we don't know the child context yet as the instance doesn't exist.
18826 // We will invalidate the child context in finishClassComponent() right after rendering.
18827
18828 var hasContext;
18829
18830 if (isContextProvider(Component)) {
18831 hasContext = true;
18832 pushContextProvider(workInProgress);
18833 } else {
18834 hasContext = false;
18835 }
18836
18837 prepareToReadContext(workInProgress, renderExpirationTime);
18838 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18839 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18840 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18841}
18842
18843function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
18844 if (_current !== null) {
18845 // An indeterminate component only mounts if it suspended inside a non-
18846 // concurrent tree, in an inconsistent state. We want to treat it like
18847 // a new mount, even though an empty version of it already committed.
18848 // Disconnect the alternate pointers.
18849 _current.alternate = null;
18850 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18851
18852 workInProgress.effectTag |= Placement;
18853 }
18854
18855 var props = workInProgress.pendingProps;
18856 var context;
18857
18858 if (!disableLegacyContext) {
18859 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
18860 context = getMaskedContext(workInProgress, unmaskedContext);
18861 }
18862
18863 prepareToReadContext(workInProgress, renderExpirationTime);
18864 var value;
18865
18866 {
18867 if (Component.prototype && typeof Component.prototype.render === 'function') {
18868 var componentName = getComponentName(Component) || 'Unknown';
18869
18870 if (!didWarnAboutBadClass[componentName]) {
18871 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);
18872 didWarnAboutBadClass[componentName] = true;
18873 }
18874 }
18875
18876 if (workInProgress.mode & StrictMode) {
18877 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
18878 }
18879
18880 ReactCurrentOwner$3.current = workInProgress;
18881 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18882 } // React DevTools reads this flag.
18883
18884
18885 workInProgress.effectTag |= PerformedWork;
18886
18887 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
18888 {
18889 var _componentName = getComponentName(Component) || 'Unknown';
18890
18891 if (!didWarnAboutModulePatternComponent[_componentName]) {
18892 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);
18893 didWarnAboutModulePatternComponent[_componentName] = true;
18894 }
18895 } // Proceed under the assumption that this is a class instance
18896
18897
18898 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
18899
18900 resetHooks(); // Push context providers early to prevent context stack mismatches.
18901 // During mounting we don't know the child context yet as the instance doesn't exist.
18902 // We will invalidate the child context in finishClassComponent() right after rendering.
18903
18904 var hasContext = false;
18905
18906 if (isContextProvider(Component)) {
18907 hasContext = true;
18908 pushContextProvider(workInProgress);
18909 } else {
18910 hasContext = false;
18911 }
18912
18913 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
18914 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
18915
18916 if (typeof getDerivedStateFromProps === 'function') {
18917 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
18918 }
18919
18920 adoptClassInstance(workInProgress, value);
18921 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
18922 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18923 } else {
18924 // Proceed under the assumption that this is a function component
18925 workInProgress.tag = FunctionComponent;
18926
18927 {
18928 if (disableLegacyContext && Component.contextTypes) {
18929 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentName(Component) || 'Unknown');
18930 }
18931
18932 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18933 // Only double-render components with Hooks
18934 if (workInProgress.memoizedState !== null) {
18935 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18936 }
18937 }
18938 }
18939
18940 reconcileChildren(null, workInProgress, value, renderExpirationTime);
18941
18942 {
18943 validateFunctionComponentInDev(workInProgress, Component);
18944 }
18945
18946 return workInProgress.child;
18947 }
18948}
18949
18950function validateFunctionComponentInDev(workInProgress, Component) {
18951 if (Component) {
18952 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
18953 }
18954
18955 if (workInProgress.ref !== null) {
18956 var info = '';
18957 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
18958
18959 if (ownerName) {
18960 info += '\n\nCheck the render method of `' + ownerName + '`.';
18961 }
18962
18963 var warningKey = ownerName || workInProgress._debugID || '';
18964 var debugSource = workInProgress._debugSource;
18965
18966 if (debugSource) {
18967 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
18968 }
18969
18970 if (!didWarnAboutFunctionRefs[warningKey]) {
18971 didWarnAboutFunctionRefs[warningKey] = true;
18972 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);
18973 }
18974 }
18975
18976 if (warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined) {
18977 var componentName = getComponentName(Component) || 'Unknown';
18978
18979 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
18980 warningWithoutStack$1(false, '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
18981 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
18982 }
18983 }
18984
18985 if (typeof Component.getDerivedStateFromProps === 'function') {
18986 var _componentName2 = getComponentName(Component) || 'Unknown';
18987
18988 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
18989 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', _componentName2);
18990 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
18991 }
18992 }
18993
18994 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
18995 var _componentName3 = getComponentName(Component) || 'Unknown';
18996
18997 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
18998 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName3);
18999 didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
19000 }
19001 }
19002}
19003
19004var SUSPENDED_MARKER = {
19005 dehydrated: null,
19006 retryTime: Never
19007};
19008
19009function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) {
19010 // If the context is telling us that we should show a fallback, and we're not
19011 // already showing content, then we should show the fallback instead.
19012 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current$$1 === null || current$$1.memoizedState !== null);
19013}
19014
19015function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
19016 var mode = workInProgress.mode;
19017 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
19018
19019 {
19020 if (shouldSuspend(workInProgress)) {
19021 workInProgress.effectTag |= DidCapture;
19022 }
19023 }
19024
19025 var suspenseContext = suspenseStackCursor.current;
19026 var nextDidTimeout = false;
19027 var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
19028
19029 if (didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress)) {
19030 // Something in this boundary's subtree already suspended. Switch to
19031 // rendering the fallback children.
19032 nextDidTimeout = true;
19033 workInProgress.effectTag &= ~DidCapture;
19034 } else {
19035 // Attempting the main content
19036 if (current$$1 === null || current$$1.memoizedState !== null) {
19037 // This is a new mount or this boundary is already showing a fallback state.
19038 // Mark this subtree context as having at least one invisible parent that could
19039 // handle the fallback state.
19040 // Boundaries without fallbacks or should be avoided are not considered since
19041 // they cannot handle preferred fallback states.
19042 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
19043 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
19044 }
19045 }
19046 }
19047
19048 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19049 pushSuspenseContext(workInProgress, suspenseContext);
19050
19051 {
19052 if ('maxDuration' in nextProps) {
19053 if (!didWarnAboutMaxDuration) {
19054 didWarnAboutMaxDuration = true;
19055 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
19056 }
19057 }
19058 } // This next part is a bit confusing. If the children timeout, we switch to
19059 // showing the fallback children in place of the "primary" children.
19060 // However, we don't want to delete the primary children because then their
19061 // state will be lost (both the React state and the host state, e.g.
19062 // uncontrolled form inputs). Instead we keep them mounted and hide them.
19063 // Both the fallback children AND the primary children are rendered at the
19064 // same time. Once the primary children are un-suspended, we can delete
19065 // the fallback children — don't need to preserve their state.
19066 //
19067 // The two sets of children are siblings in the host environment, but
19068 // semantically, for purposes of reconciliation, they are two separate sets.
19069 // So we store them using two fragment fibers.
19070 //
19071 // However, we want to avoid allocating extra fibers for every placeholder.
19072 // They're only necessary when the children time out, because that's the
19073 // only time when both sets are mounted.
19074 //
19075 // So, the extra fragment fibers are only used if the children time out.
19076 // Otherwise, we render the primary children directly. This requires some
19077 // custom reconciliation logic to preserve the state of the primary
19078 // children. It's essentially a very basic form of re-parenting.
19079
19080
19081 if (current$$1 === null) {
19082 if (enableSuspenseServerRenderer) {
19083 // If we're currently hydrating, try to hydrate this boundary.
19084 // But only if this has a fallback.
19085 if (nextProps.fallback !== undefined) {
19086 tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
19087
19088 var suspenseState = workInProgress.memoizedState;
19089
19090 if (suspenseState !== null) {
19091 var dehydrated = suspenseState.dehydrated;
19092
19093 if (dehydrated !== null) {
19094 return mountDehydratedSuspenseComponent(workInProgress, dehydrated, renderExpirationTime);
19095 }
19096 }
19097 }
19098 } // This is the initial mount. This branch is pretty simple because there's
19099 // no previous state that needs to be preserved.
19100
19101
19102 if (nextDidTimeout) {
19103 // Mount separate fragments for primary and fallback children.
19104 var nextFallbackChildren = nextProps.fallback;
19105 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
19106 primaryChildFragment.return = workInProgress;
19107
19108 if ((workInProgress.mode & BatchedMode) === NoMode) {
19109 // Outside of batched mode, we commit the effects from the
19110 // partially completed, timed-out tree, too.
19111 var progressedState = workInProgress.memoizedState;
19112 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
19113 primaryChildFragment.child = progressedPrimaryChild;
19114 var progressedChild = progressedPrimaryChild;
19115
19116 while (progressedChild !== null) {
19117 progressedChild.return = primaryChildFragment;
19118 progressedChild = progressedChild.sibling;
19119 }
19120 }
19121
19122 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
19123 fallbackChildFragment.return = workInProgress;
19124 primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
19125 // fallback children.
19126
19127 workInProgress.memoizedState = SUSPENDED_MARKER;
19128 workInProgress.child = primaryChildFragment;
19129 return fallbackChildFragment;
19130 } else {
19131 // Mount the primary children without an intermediate fragment fiber.
19132 var nextPrimaryChildren = nextProps.children;
19133 workInProgress.memoizedState = null;
19134 return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
19135 }
19136 } else {
19137 // This is an update. This branch is more complicated because we need to
19138 // ensure the state of the primary children is preserved.
19139 var prevState = current$$1.memoizedState;
19140
19141 if (prevState !== null) {
19142 if (enableSuspenseServerRenderer) {
19143 var _dehydrated = prevState.dehydrated;
19144
19145 if (_dehydrated !== null) {
19146 if (!didSuspend) {
19147 return updateDehydratedSuspenseComponent(current$$1, workInProgress, _dehydrated, prevState, renderExpirationTime);
19148 } else if (workInProgress.memoizedState !== null) {
19149 // Something suspended and we should still be in dehydrated mode.
19150 // Leave the existing child in place.
19151 workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there
19152 // but the normal suspense pass doesn't.
19153
19154 workInProgress.effectTag |= DidCapture;
19155 return null;
19156 } else {
19157 // Suspended but we should no longer be in dehydrated mode.
19158 // Therefore we now have to render the fallback. Wrap the children
19159 // in a fragment fiber to keep them separate from the fallback
19160 // children.
19161 var _nextFallbackChildren = nextProps.fallback;
19162
19163 var _primaryChildFragment = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19164 // going to render this fragment.
19165 null, mode, NoWork, null);
19166
19167 _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child
19168 // that we're not going to hydrate.
19169
19170 _primaryChildFragment.child = null;
19171
19172 if ((workInProgress.mode & BatchedMode) === NoMode) {
19173 // Outside of batched mode, we commit the effects from the
19174 // partially completed, timed-out tree, too.
19175 var _progressedChild = _primaryChildFragment.child = workInProgress.child;
19176
19177 while (_progressedChild !== null) {
19178 _progressedChild.return = _primaryChildFragment;
19179 _progressedChild = _progressedChild.sibling;
19180 }
19181 } else {
19182 // We will have dropped the effect list which contains the deletion.
19183 // We need to reconcile to delete the current child.
19184 reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
19185 } // Because primaryChildFragment is a new fiber that we're inserting as the
19186 // parent of a new tree, we need to set its treeBaseDuration.
19187
19188
19189 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19190 // treeBaseDuration is the sum of all the child tree base durations.
19191 var treeBaseDuration = 0;
19192 var hiddenChild = _primaryChildFragment.child;
19193
19194 while (hiddenChild !== null) {
19195 treeBaseDuration += hiddenChild.treeBaseDuration;
19196 hiddenChild = hiddenChild.sibling;
19197 }
19198
19199 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
19200 } // Create a fragment from the fallback children, too.
19201
19202
19203 var _fallbackChildFragment = createFiberFromFragment(_nextFallbackChildren, mode, renderExpirationTime, null);
19204
19205 _fallbackChildFragment.return = workInProgress;
19206 _primaryChildFragment.sibling = _fallbackChildFragment;
19207 _fallbackChildFragment.effectTag |= Placement;
19208 _primaryChildFragment.childExpirationTime = NoWork;
19209 workInProgress.memoizedState = SUSPENDED_MARKER;
19210 workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the
19211 // fallback children.
19212
19213 return _fallbackChildFragment;
19214 }
19215 }
19216 } // The current tree already timed out. That means each child set is
19217 // wrapped in a fragment fiber.
19218
19219
19220 var currentPrimaryChildFragment = current$$1.child;
19221 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
19222
19223 if (nextDidTimeout) {
19224 // Still timed out. Reuse the current primary children by cloning
19225 // its fragment. We're going to skip over these entirely.
19226 var _nextFallbackChildren2 = nextProps.fallback;
19227
19228 var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
19229
19230 _primaryChildFragment2.return = workInProgress;
19231
19232 if ((workInProgress.mode & BatchedMode) === NoMode) {
19233 // Outside of batched mode, we commit the effects from the
19234 // partially completed, timed-out tree, too.
19235 var _progressedState = workInProgress.memoizedState;
19236
19237 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
19238
19239 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
19240 _primaryChildFragment2.child = _progressedPrimaryChild;
19241 var _progressedChild2 = _progressedPrimaryChild;
19242
19243 while (_progressedChild2 !== null) {
19244 _progressedChild2.return = _primaryChildFragment2;
19245 _progressedChild2 = _progressedChild2.sibling;
19246 }
19247 }
19248 } // Because primaryChildFragment is a new fiber that we're inserting as the
19249 // parent of a new tree, we need to set its treeBaseDuration.
19250
19251
19252 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19253 // treeBaseDuration is the sum of all the child tree base durations.
19254 var _treeBaseDuration = 0;
19255 var _hiddenChild = _primaryChildFragment2.child;
19256
19257 while (_hiddenChild !== null) {
19258 _treeBaseDuration += _hiddenChild.treeBaseDuration;
19259 _hiddenChild = _hiddenChild.sibling;
19260 }
19261
19262 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
19263 } // Clone the fallback child fragment, too. These we'll continue
19264 // working on.
19265
19266
19267 var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2, currentFallbackChildFragment.expirationTime);
19268
19269 _fallbackChildFragment2.return = workInProgress;
19270 _primaryChildFragment2.sibling = _fallbackChildFragment2;
19271 _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19272 // fallback children.
19273
19274 workInProgress.memoizedState = SUSPENDED_MARKER;
19275 workInProgress.child = _primaryChildFragment2;
19276 return _fallbackChildFragment2;
19277 } else {
19278 // No longer suspended. Switch back to showing the primary children,
19279 // and remove the intermediate fragment fiber.
19280 var _nextPrimaryChildren = nextProps.children;
19281 var currentPrimaryChild = currentPrimaryChildFragment.child;
19282 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
19283 // children. Wait until the complete phase, after we've confirmed the
19284 // fallback is no longer needed.
19285 // TODO: Would it be better to store the fallback fragment on
19286 // the stateNode?
19287 // Continue rendering the children, like we normally do.
19288
19289 workInProgress.memoizedState = null;
19290 return workInProgress.child = primaryChild;
19291 }
19292 } else {
19293 // The current tree has not already timed out. That means the primary
19294 // children are not wrapped in a fragment fiber.
19295 var _currentPrimaryChild = current$$1.child;
19296
19297 if (nextDidTimeout) {
19298 // Timed out. Wrap the children in a fragment fiber to keep them
19299 // separate from the fallback children.
19300 var _nextFallbackChildren3 = nextProps.fallback;
19301
19302 var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19303 // going to render this fragment.
19304 null, mode, NoWork, null);
19305
19306 _primaryChildFragment3.return = workInProgress;
19307 _primaryChildFragment3.child = _currentPrimaryChild;
19308
19309 if (_currentPrimaryChild !== null) {
19310 _currentPrimaryChild.return = _primaryChildFragment3;
19311 } // Even though we're creating a new fiber, there are no new children,
19312 // because we're reusing an already mounted tree. So we don't need to
19313 // schedule a placement.
19314 // primaryChildFragment.effectTag |= Placement;
19315
19316
19317 if ((workInProgress.mode & BatchedMode) === NoMode) {
19318 // Outside of batched mode, we commit the effects from the
19319 // partially completed, timed-out tree, too.
19320 var _progressedState2 = workInProgress.memoizedState;
19321
19322 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
19323
19324 _primaryChildFragment3.child = _progressedPrimaryChild2;
19325 var _progressedChild3 = _progressedPrimaryChild2;
19326
19327 while (_progressedChild3 !== null) {
19328 _progressedChild3.return = _primaryChildFragment3;
19329 _progressedChild3 = _progressedChild3.sibling;
19330 }
19331 } // Because primaryChildFragment is a new fiber that we're inserting as the
19332 // parent of a new tree, we need to set its treeBaseDuration.
19333
19334
19335 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19336 // treeBaseDuration is the sum of all the child tree base durations.
19337 var _treeBaseDuration2 = 0;
19338 var _hiddenChild2 = _primaryChildFragment3.child;
19339
19340 while (_hiddenChild2 !== null) {
19341 _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
19342 _hiddenChild2 = _hiddenChild2.sibling;
19343 }
19344
19345 _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
19346 } // Create a fragment from the fallback children, too.
19347
19348
19349 var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
19350
19351 _fallbackChildFragment3.return = workInProgress;
19352 _primaryChildFragment3.sibling = _fallbackChildFragment3;
19353 _fallbackChildFragment3.effectTag |= Placement;
19354 _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19355 // fallback children.
19356
19357 workInProgress.memoizedState = SUSPENDED_MARKER;
19358 workInProgress.child = _primaryChildFragment3;
19359 return _fallbackChildFragment3;
19360 } else {
19361 // Still haven't timed out. Continue rendering the children, like we
19362 // normally do.
19363 workInProgress.memoizedState = null;
19364 var _nextPrimaryChildren2 = nextProps.children;
19365 return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
19366 }
19367 }
19368 }
19369}
19370
19371function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
19372 // We're now not suspended nor dehydrated.
19373 workInProgress.memoizedState = null; // Retry with the full children.
19374
19375 var nextProps = workInProgress.pendingProps;
19376 var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and
19377 // that the old child gets a Deletion effect.
19378 // We could also call forceUnmountCurrentAndReconcile.
19379
19380 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19381 return workInProgress.child;
19382}
19383
19384function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderExpirationTime) {
19385 // During the first pass, we'll bail out and not drill into the children.
19386 // Instead, we'll leave the content in place and try to hydrate it later.
19387 if ((workInProgress.mode & BatchedMode) === NoMode) {
19388 {
19389 warning$1(false, 'Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOM.unstable_createSyncRoot(container, { hydrate: true })' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
19390 }
19391
19392 workInProgress.expirationTime = Sync;
19393 } else if (isSuspenseInstanceFallback(suspenseInstance)) {
19394 // This is a client-only boundary. Since we won't get any content from the server
19395 // for this, we need to schedule that at a higher priority based on when it would
19396 // have timed out. In theory we could render it in this pass but it would have the
19397 // wrong priority associated with it and will prevent hydration of parent path.
19398 // Instead, we'll leave work left on it to render it in a separate commit.
19399 // TODO This time should be the time at which the server rendered response that is
19400 // a parent to this boundary was displayed. However, since we currently don't have
19401 // a protocol to transfer that time, we'll just estimate it by using the current
19402 // time. This will mean that Suspense timeouts are slightly shifted to later than
19403 // they should be.
19404 var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content.
19405
19406 var newExpirationTime = computeAsyncExpiration(serverDisplayTime);
19407
19408 if (enableSchedulerTracing) {
19409 markSpawnedWork(newExpirationTime);
19410 }
19411
19412 workInProgress.expirationTime = newExpirationTime;
19413 } else {
19414 // We'll continue hydrating the rest at offscreen priority since we'll already
19415 // be showing the right content coming from the server, it is no rush.
19416 workInProgress.expirationTime = Never;
19417
19418 if (enableSchedulerTracing) {
19419 markSpawnedWork(Never);
19420 }
19421 }
19422
19423 return null;
19424}
19425
19426function updateDehydratedSuspenseComponent(current$$1, workInProgress, suspenseInstance, suspenseState, renderExpirationTime) {
19427 // We should never be hydrating at this point because it is the first pass,
19428 // but after we've already committed once.
19429 warnIfHydrating();
19430
19431 if ((workInProgress.mode & BatchedMode) === NoMode) {
19432 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19433 }
19434
19435 if (isSuspenseInstanceFallback(suspenseInstance)) {
19436 // This boundary is in a permanent fallback state. In this case, we'll never
19437 // get an update and we'll never be able to hydrate the final content. Let's just try the
19438 // client side render instead.
19439 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19440 } // We use childExpirationTime to indicate that a child might depend on context, so if
19441 // any context has changed, we need to treat is as if the input might have changed.
19442
19443
19444 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
19445
19446 if (didReceiveUpdate || hasContextChanged$$1) {
19447 // This boundary has changed since the first render. This means that we are now unable to
19448 // hydrate it. We might still be able to hydrate it using an earlier expiration time, if
19449 // we are rendering at lower expiration than sync.
19450 if (renderExpirationTime < Sync) {
19451 if (suspenseState.retryTime <= renderExpirationTime) {
19452 // This render is even higher pri than we've seen before, let's try again
19453 // at even higher pri.
19454 var attemptHydrationAtExpirationTime = renderExpirationTime + 1;
19455 suspenseState.retryTime = attemptHydrationAtExpirationTime;
19456 scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render.
19457 } else {// We have already tried to ping at a higher priority than we're rendering with
19458 // so if we got here, we must have failed to hydrate at those levels. We must
19459 // now give up. Instead, we're going to delete the whole subtree and instead inject
19460 // a new real Suspense boundary to take its place, which may render content
19461 // or fallback. This might suspend for a while and if it does we might still have
19462 // an opportunity to hydrate before this pass commits.
19463 }
19464 } // If we have scheduled higher pri work above, this will probably just abort the render
19465 // since we now have higher priority work, but in case it doesn't, we need to prepare to
19466 // render something, if we time out. Even if that requires us to delete everything and
19467 // skip hydration.
19468 // Delay having to do this as long as the suspense timeout allows us.
19469
19470
19471 renderDidSuspendDelayIfPossible();
19472 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19473 } else if (isSuspenseInstancePending(suspenseInstance)) {
19474 // This component is still pending more data from the server, so we can't hydrate its
19475 // content. We treat it as if this component suspended itself. It might seem as if
19476 // we could just try to render it client-side instead. However, this will perform a
19477 // lot of unnecessary work and is unlikely to complete since it often will suspend
19478 // on missing data anyway. Additionally, the server might be able to render more
19479 // than we can on the client yet. In that case we'd end up with more fallback states
19480 // on the client than if we just leave it alone. If the server times out or errors
19481 // these should update this boundary to the permanent Fallback state instead.
19482 // Mark it as having captured (i.e. suspended).
19483 workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
19484
19485 workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result.
19486
19487 registerSuspenseInstanceRetry(suspenseInstance, retryDehydratedSuspenseBoundary.bind(null, current$$1));
19488 return null;
19489 } else {
19490 // This is the first attempt.
19491 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance);
19492 var nextProps = workInProgress.pendingProps;
19493 var nextChildren = nextProps.children;
19494 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19495 var node = child;
19496
19497 while (node) {
19498 // Mark each child as hydrating. This is a fast path to know whether this
19499 // tree is part of a hydrating tree. This is used to determine if a child
19500 // node has fully mounted yet, and for scheduling event replaying.
19501 // Conceptually this is similar to Placement in that a new subtree is
19502 // inserted into the React tree here. It just happens to not need DOM
19503 // mutations because it already exists.
19504 node.effectTag |= Hydrating;
19505 node = node.sibling;
19506 }
19507
19508 workInProgress.child = child;
19509 return workInProgress.child;
19510 }
19511}
19512
19513function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
19514 // Mark any Suspense boundaries with fallbacks as having work to do.
19515 // If they were previously forced into fallbacks, they may now be able
19516 // to unblock.
19517 var node = firstChild;
19518
19519 while (node !== null) {
19520 if (node.tag === SuspenseComponent) {
19521 var state = node.memoizedState;
19522
19523 if (state !== null) {
19524 if (node.expirationTime < renderExpirationTime) {
19525 node.expirationTime = renderExpirationTime;
19526 }
19527
19528 var alternate = node.alternate;
19529
19530 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
19531 alternate.expirationTime = renderExpirationTime;
19532 }
19533
19534 scheduleWorkOnParentPath(node.return, renderExpirationTime);
19535 }
19536 } else if (node.child !== null) {
19537 node.child.return = node;
19538 node = node.child;
19539 continue;
19540 }
19541
19542 if (node === workInProgress) {
19543 return;
19544 }
19545
19546 while (node.sibling === null) {
19547 if (node.return === null || node.return === workInProgress) {
19548 return;
19549 }
19550
19551 node = node.return;
19552 }
19553
19554 node.sibling.return = node.return;
19555 node = node.sibling;
19556 }
19557}
19558
19559function findLastContentRow(firstChild) {
19560 // This is going to find the last row among these children that is already
19561 // showing content on the screen, as opposed to being in fallback state or
19562 // new. If a row has multiple Suspense boundaries, any of them being in the
19563 // fallback state, counts as the whole row being in a fallback state.
19564 // Note that the "rows" will be workInProgress, but any nested children
19565 // will still be current since we haven't rendered them yet. The mounted
19566 // order may not be the same as the new order. We use the new order.
19567 var row = firstChild;
19568 var lastContentRow = null;
19569
19570 while (row !== null) {
19571 var currentRow = row.alternate; // New rows can't be content rows.
19572
19573 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19574 lastContentRow = row;
19575 }
19576
19577 row = row.sibling;
19578 }
19579
19580 return lastContentRow;
19581}
19582
19583function validateRevealOrder(revealOrder) {
19584 {
19585 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
19586 didWarnAboutRevealOrder[revealOrder] = true;
19587
19588 if (typeof revealOrder === 'string') {
19589 switch (revealOrder.toLowerCase()) {
19590 case 'together':
19591 case 'forwards':
19592 case 'backwards':
19593 {
19594 warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
19595 break;
19596 }
19597
19598 case 'forward':
19599 case 'backward':
19600 {
19601 warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
19602 break;
19603 }
19604
19605 default:
19606 warning$1(false, '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19607 break;
19608 }
19609 } else {
19610 warning$1(false, '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19611 }
19612 }
19613 }
19614}
19615
19616function validateTailOptions(tailMode, revealOrder) {
19617 {
19618 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
19619 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
19620 didWarnAboutTailOptions[tailMode] = true;
19621 warning$1(false, '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
19622 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
19623 didWarnAboutTailOptions[tailMode] = true;
19624 warning$1(false, '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
19625 }
19626 }
19627 }
19628}
19629
19630function validateSuspenseListNestedChild(childSlot, index) {
19631 {
19632 var isArray = Array.isArray(childSlot);
19633 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
19634
19635 if (isArray || isIterable) {
19636 var type = isArray ? 'array' : 'iterable';
19637 warning$1(false, 'A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
19638 return false;
19639 }
19640 }
19641
19642 return true;
19643}
19644
19645function validateSuspenseListChildren(children, revealOrder) {
19646 {
19647 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
19648 if (Array.isArray(children)) {
19649 for (var i = 0; i < children.length; i++) {
19650 if (!validateSuspenseListNestedChild(children[i], i)) {
19651 return;
19652 }
19653 }
19654 } else {
19655 var iteratorFn = getIteratorFn(children);
19656
19657 if (typeof iteratorFn === 'function') {
19658 var childrenIterator = iteratorFn.call(children);
19659
19660 if (childrenIterator) {
19661 var step = childrenIterator.next();
19662 var _i = 0;
19663
19664 for (; !step.done; step = childrenIterator.next()) {
19665 if (!validateSuspenseListNestedChild(step.value, _i)) {
19666 return;
19667 }
19668
19669 _i++;
19670 }
19671 }
19672 } else {
19673 warning$1(false, 'A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
19674 }
19675 }
19676 }
19677 }
19678}
19679
19680function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
19681 var renderState = workInProgress.memoizedState;
19682
19683 if (renderState === null) {
19684 workInProgress.memoizedState = {
19685 isBackwards: isBackwards,
19686 rendering: null,
19687 last: lastContentRow,
19688 tail: tail,
19689 tailExpiration: 0,
19690 tailMode: tailMode
19691 };
19692 } else {
19693 // We can reuse the existing object from previous renders.
19694 renderState.isBackwards = isBackwards;
19695 renderState.rendering = null;
19696 renderState.last = lastContentRow;
19697 renderState.tail = tail;
19698 renderState.tailExpiration = 0;
19699 renderState.tailMode = tailMode;
19700 }
19701} // This can end up rendering this component multiple passes.
19702// The first pass splits the children fibers into two sets. A head and tail.
19703// We first render the head. If anything is in fallback state, we do another
19704// pass through beginWork to rerender all children (including the tail) with
19705// the force suspend context. If the first render didn't have anything in
19706// in fallback state. Then we render each row in the tail one-by-one.
19707// That happens in the completeWork phase without going back to beginWork.
19708
19709
19710function updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime) {
19711 var nextProps = workInProgress.pendingProps;
19712 var revealOrder = nextProps.revealOrder;
19713 var tailMode = nextProps.tail;
19714 var newChildren = nextProps.children;
19715 validateRevealOrder(revealOrder);
19716 validateTailOptions(tailMode, revealOrder);
19717 validateSuspenseListChildren(newChildren, revealOrder);
19718 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19719 var suspenseContext = suspenseStackCursor.current;
19720 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
19721
19722 if (shouldForceFallback) {
19723 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
19724 workInProgress.effectTag |= DidCapture;
19725 } else {
19726 var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect;
19727
19728 if (didSuspendBefore) {
19729 // If we previously forced a fallback, we need to schedule work
19730 // on any nested boundaries to let them know to try to render
19731 // again. This is the same as context updating.
19732 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
19733 }
19734
19735 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19736 }
19737
19738 pushSuspenseContext(workInProgress, suspenseContext);
19739
19740 if ((workInProgress.mode & BatchedMode) === NoMode) {
19741 // Outside of batched mode, SuspenseList doesn't work so we just
19742 // use make it a noop by treating it as the default revealOrder.
19743 workInProgress.memoizedState = null;
19744 } else {
19745 switch (revealOrder) {
19746 case 'forwards':
19747 {
19748 var lastContentRow = findLastContentRow(workInProgress.child);
19749 var tail;
19750
19751 if (lastContentRow === null) {
19752 // The whole list is part of the tail.
19753 // TODO: We could fast path by just rendering the tail now.
19754 tail = workInProgress.child;
19755 workInProgress.child = null;
19756 } else {
19757 // Disconnect the tail rows after the content row.
19758 // We're going to render them separately later.
19759 tail = lastContentRow.sibling;
19760 lastContentRow.sibling = null;
19761 }
19762
19763 initSuspenseListRenderState(workInProgress, false, // isBackwards
19764 tail, lastContentRow, tailMode);
19765 break;
19766 }
19767
19768 case 'backwards':
19769 {
19770 // We're going to find the first row that has existing content.
19771 // At the same time we're going to reverse the list of everything
19772 // we pass in the meantime. That's going to be our tail in reverse
19773 // order.
19774 var _tail = null;
19775 var row = workInProgress.child;
19776 workInProgress.child = null;
19777
19778 while (row !== null) {
19779 var currentRow = row.alternate; // New rows can't be content rows.
19780
19781 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19782 // This is the beginning of the main content.
19783 workInProgress.child = row;
19784 break;
19785 }
19786
19787 var nextRow = row.sibling;
19788 row.sibling = _tail;
19789 _tail = row;
19790 row = nextRow;
19791 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
19792
19793
19794 initSuspenseListRenderState(workInProgress, true, // isBackwards
19795 _tail, null, // last
19796 tailMode);
19797 break;
19798 }
19799
19800 case 'together':
19801 {
19802 initSuspenseListRenderState(workInProgress, false, // isBackwards
19803 null, // tail
19804 null, // last
19805 undefined);
19806 break;
19807 }
19808
19809 default:
19810 {
19811 // The default reveal order is the same as not having
19812 // a boundary.
19813 workInProgress.memoizedState = null;
19814 }
19815 }
19816 }
19817
19818 return workInProgress.child;
19819}
19820
19821function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
19822 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19823 var nextChildren = workInProgress.pendingProps;
19824
19825 if (current$$1 === null) {
19826 // Portals are special because we don't append the children during mount
19827 // but at commit. Therefore we need to track insertions which the normal
19828 // flow doesn't do during mount. This doesn't happen at the root because
19829 // the root always starts with a "current" with a null child.
19830 // TODO: Consider unifying this with how the root works.
19831 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19832 } else {
19833 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19834 }
19835
19836 return workInProgress.child;
19837}
19838
19839function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
19840 var providerType = workInProgress.type;
19841 var context = providerType._context;
19842 var newProps = workInProgress.pendingProps;
19843 var oldProps = workInProgress.memoizedProps;
19844 var newValue = newProps.value;
19845
19846 {
19847 var providerPropTypes = workInProgress.type.propTypes;
19848
19849 if (providerPropTypes) {
19850 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
19851 }
19852 }
19853
19854 pushProvider(workInProgress, newValue);
19855
19856 if (oldProps !== null) {
19857 var oldValue = oldProps.value;
19858 var changedBits = calculateChangedBits(context, newValue, oldValue);
19859
19860 if (changedBits === 0) {
19861 // No change. Bailout early if children are the same.
19862 if (oldProps.children === newProps.children && !hasContextChanged()) {
19863 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
19864 }
19865 } else {
19866 // The context value changed. Search for matching consumers and schedule
19867 // them to update.
19868 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
19869 }
19870 }
19871
19872 var newChildren = newProps.children;
19873 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19874 return workInProgress.child;
19875}
19876
19877var hasWarnedAboutUsingContextAsConsumer = false;
19878
19879function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
19880 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
19881 // DEV mode, we create a separate object for Context.Consumer that acts
19882 // like a proxy to Context. This proxy object adds unnecessary code in PROD
19883 // so we use the old behaviour (Context.Consumer references Context) to
19884 // reduce size and overhead. The separate object references context via
19885 // a property called "_context", which also gives us the ability to check
19886 // in DEV mode if this property exists or not and warn if it does not.
19887
19888 {
19889 if (context._context === undefined) {
19890 // This may be because it's a Context (rather than a Consumer).
19891 // Or it may be because it's older React where they're the same thing.
19892 // We only want to warn if we're sure it's a new React.
19893 if (context !== context.Consumer) {
19894 if (!hasWarnedAboutUsingContextAsConsumer) {
19895 hasWarnedAboutUsingContextAsConsumer = true;
19896 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?');
19897 }
19898 }
19899 } else {
19900 context = context._context;
19901 }
19902 }
19903
19904 var newProps = workInProgress.pendingProps;
19905 var render = newProps.children;
19906
19907 {
19908 !(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;
19909 }
19910
19911 prepareToReadContext(workInProgress, renderExpirationTime);
19912 var newValue = readContext(context, newProps.unstable_observedBits);
19913 var newChildren;
19914
19915 {
19916 ReactCurrentOwner$3.current = workInProgress;
19917 setCurrentPhase('render');
19918 newChildren = render(newValue);
19919 setCurrentPhase(null);
19920 } // React DevTools reads this flag.
19921
19922
19923 workInProgress.effectTag |= PerformedWork;
19924 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19925 return workInProgress.child;
19926}
19927
19928function updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime) {
19929 var fundamentalImpl = workInProgress.type.impl;
19930
19931 if (fundamentalImpl.reconcileChildren === false) {
19932 return null;
19933 }
19934
19935 var nextProps = workInProgress.pendingProps;
19936 var nextChildren = nextProps.children;
19937 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19938 return workInProgress.child;
19939}
19940
19941function updateScopeComponent(current$$1, workInProgress, renderExpirationTime) {
19942 var nextProps = workInProgress.pendingProps;
19943 var nextChildren = nextProps.children;
19944 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19945 return workInProgress.child;
19946}
19947
19948function markWorkInProgressReceivedUpdate() {
19949 didReceiveUpdate = true;
19950}
19951
19952function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
19953 cancelWorkTimer(workInProgress);
19954
19955 if (current$$1 !== null) {
19956 // Reuse previous dependencies
19957 workInProgress.dependencies = current$$1.dependencies;
19958 }
19959
19960 if (enableProfilerTimer) {
19961 // Don't update "base" render times for bailouts.
19962 stopProfilerTimerIfRunning(workInProgress);
19963 }
19964
19965 var updateExpirationTime = workInProgress.expirationTime;
19966
19967 if (updateExpirationTime !== NoWork) {
19968 markUnprocessedUpdateTime(updateExpirationTime);
19969 } // Check if the children have any pending work.
19970
19971
19972 var childExpirationTime = workInProgress.childExpirationTime;
19973
19974 if (childExpirationTime < renderExpirationTime) {
19975 // The children don't have any work either. We can skip them.
19976 // TODO: Once we add back resuming, we should check if the children are
19977 // a work-in-progress set. If so, we need to transfer their effects.
19978 return null;
19979 } else {
19980 // This fiber doesn't have work, but its subtree does. Clone the child
19981 // fibers and continue.
19982 cloneChildFibers(current$$1, workInProgress);
19983 return workInProgress.child;
19984 }
19985}
19986
19987function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
19988 {
19989 var returnFiber = oldWorkInProgress.return;
19990
19991 if (returnFiber === null) {
19992 throw new Error('Cannot swap the root fiber.');
19993 } // Disconnect from the old current.
19994 // It will get deleted.
19995
19996
19997 current$$1.alternate = null;
19998 oldWorkInProgress.alternate = null; // Connect to the new tree.
19999
20000 newWorkInProgress.index = oldWorkInProgress.index;
20001 newWorkInProgress.sibling = oldWorkInProgress.sibling;
20002 newWorkInProgress.return = oldWorkInProgress.return;
20003 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
20004
20005 if (oldWorkInProgress === returnFiber.child) {
20006 returnFiber.child = newWorkInProgress;
20007 } else {
20008 var prevSibling = returnFiber.child;
20009
20010 if (prevSibling === null) {
20011 throw new Error('Expected parent to have a child.');
20012 }
20013
20014 while (prevSibling.sibling !== oldWorkInProgress) {
20015 prevSibling = prevSibling.sibling;
20016
20017 if (prevSibling === null) {
20018 throw new Error('Expected to find the previous sibling.');
20019 }
20020 }
20021
20022 prevSibling.sibling = newWorkInProgress;
20023 } // Delete the old fiber and place the new one.
20024 // Since the old fiber is disconnected, we have to schedule it manually.
20025
20026
20027 var last = returnFiber.lastEffect;
20028
20029 if (last !== null) {
20030 last.nextEffect = current$$1;
20031 returnFiber.lastEffect = current$$1;
20032 } else {
20033 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
20034 }
20035
20036 current$$1.nextEffect = null;
20037 current$$1.effectTag = Deletion;
20038 newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
20039
20040 return newWorkInProgress;
20041 }
20042}
20043
20044function beginWork$1(current$$1, workInProgress, renderExpirationTime) {
20045 var updateExpirationTime = workInProgress.expirationTime;
20046
20047 {
20048 if (workInProgress._debugNeedsRemount && current$$1 !== null) {
20049 // This will restart the begin phase with a new fiber.
20050 return remountFiber(current$$1, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
20051 }
20052 }
20053
20054 if (current$$1 !== null) {
20055 var oldProps = current$$1.memoizedProps;
20056 var newProps = workInProgress.pendingProps;
20057
20058 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
20059 workInProgress.type !== current$$1.type)) {
20060 // If props or context changed, mark the fiber as having performed work.
20061 // This may be unset if the props are determined to be equal later (memo).
20062 didReceiveUpdate = true;
20063 } else if (updateExpirationTime < renderExpirationTime) {
20064 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
20065 // the begin phase. There's still some bookkeeping we that needs to be done
20066 // in this optimized path, mostly pushing stuff onto the stack.
20067
20068 switch (workInProgress.tag) {
20069 case HostRoot:
20070 pushHostRootContext(workInProgress);
20071 resetHydrationState();
20072 break;
20073
20074 case HostComponent:
20075 pushHostContext(workInProgress);
20076
20077 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
20078 if (enableSchedulerTracing) {
20079 markSpawnedWork(Never);
20080 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
20081
20082
20083 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
20084 return null;
20085 }
20086
20087 break;
20088
20089 case ClassComponent:
20090 {
20091 var Component = workInProgress.type;
20092
20093 if (isContextProvider(Component)) {
20094 pushContextProvider(workInProgress);
20095 }
20096
20097 break;
20098 }
20099
20100 case HostPortal:
20101 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
20102 break;
20103
20104 case ContextProvider:
20105 {
20106 var newValue = workInProgress.memoizedProps.value;
20107 pushProvider(workInProgress, newValue);
20108 break;
20109 }
20110
20111 case Profiler:
20112 if (enableProfilerTimer) {
20113 workInProgress.effectTag |= Update;
20114 }
20115
20116 break;
20117
20118 case SuspenseComponent:
20119 {
20120 var state = workInProgress.memoizedState;
20121
20122 if (state !== null) {
20123 if (enableSuspenseServerRenderer) {
20124 if (state.dehydrated !== null) {
20125 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
20126 // been unsuspended it has committed as a resolved Suspense component.
20127 // If it needs to be retried, it should have work scheduled on it.
20128
20129 workInProgress.effectTag |= DidCapture;
20130 break;
20131 }
20132 } // If this boundary is currently timed out, we need to decide
20133 // whether to retry the primary children, or to skip over it and
20134 // go straight to the fallback. Check the priority of the primary
20135 // child fragment.
20136
20137
20138 var primaryChildFragment = workInProgress.child;
20139 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
20140
20141 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
20142 // The primary children have pending work. Use the normal path
20143 // to attempt to render the primary children again.
20144 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20145 } else {
20146 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
20147 // priority. Bailout.
20148
20149 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20150
20151 if (child !== null) {
20152 // The fallback children have pending work. Skip over the
20153 // primary children and work on the fallback.
20154 return child.sibling;
20155 } else {
20156 return null;
20157 }
20158 }
20159 } else {
20160 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
20161 }
20162
20163 break;
20164 }
20165
20166 case SuspenseListComponent:
20167 {
20168 var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect;
20169 var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20170
20171 if (didSuspendBefore) {
20172 if (hasChildWork) {
20173 // If something was in fallback state last time, and we have all the
20174 // same children then we're still in progressive loading state.
20175 // Something might get unblocked by state updates or retries in the
20176 // tree which will affect the tail. So we need to use the normal
20177 // path to compute the correct tail.
20178 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20179 } // If none of the children had any work, that means that none of
20180 // them got retried so they'll still be blocked in the same way
20181 // as before. We can fast bail out.
20182
20183
20184 workInProgress.effectTag |= DidCapture;
20185 } // If nothing suspended before and we're rendering the same children,
20186 // then the tail doesn't matter. Anything new that suspends will work
20187 // in the "together" mode, so we can continue from the state we had.
20188
20189
20190 var renderState = workInProgress.memoizedState;
20191
20192 if (renderState !== null) {
20193 // Reset to the "together" mode in case we've started a different
20194 // update in the past but didn't complete it.
20195 renderState.rendering = null;
20196 renderState.tail = null;
20197 }
20198
20199 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
20200
20201 if (hasChildWork) {
20202 break;
20203 } else {
20204 // If none of the children had any work, that means that none of
20205 // them got retried so they'll still be blocked in the same way
20206 // as before. We can fast bail out.
20207 return null;
20208 }
20209 }
20210 }
20211
20212 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20213 } else {
20214 // An update was scheduled on this fiber, but there are no new props
20215 // nor legacy context. Set this to false. If an update queue or context
20216 // consumer produces a changed value, it will set this to true. Otherwise,
20217 // the component will assume the children have not changed and bail out.
20218 didReceiveUpdate = false;
20219 }
20220 } else {
20221 didReceiveUpdate = false;
20222 } // Before entering the begin phase, clear the expiration time.
20223
20224
20225 workInProgress.expirationTime = NoWork;
20226
20227 switch (workInProgress.tag) {
20228 case IndeterminateComponent:
20229 {
20230 return mountIndeterminateComponent(current$$1, workInProgress, workInProgress.type, renderExpirationTime);
20231 }
20232
20233 case LazyComponent:
20234 {
20235 var elementType = workInProgress.elementType;
20236 return mountLazyComponent(current$$1, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
20237 }
20238
20239 case FunctionComponent:
20240 {
20241 var _Component = workInProgress.type;
20242 var unresolvedProps = workInProgress.pendingProps;
20243 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
20244 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
20245 }
20246
20247 case ClassComponent:
20248 {
20249 var _Component2 = workInProgress.type;
20250 var _unresolvedProps = workInProgress.pendingProps;
20251
20252 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
20253
20254 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
20255 }
20256
20257 case HostRoot:
20258 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
20259
20260 case HostComponent:
20261 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
20262
20263 case HostText:
20264 return updateHostText(current$$1, workInProgress);
20265
20266 case SuspenseComponent:
20267 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20268
20269 case HostPortal:
20270 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
20271
20272 case ForwardRef:
20273 {
20274 var type = workInProgress.type;
20275 var _unresolvedProps2 = workInProgress.pendingProps;
20276
20277 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
20278
20279 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
20280 }
20281
20282 case Fragment:
20283 return updateFragment(current$$1, workInProgress, renderExpirationTime);
20284
20285 case Mode:
20286 return updateMode(current$$1, workInProgress, renderExpirationTime);
20287
20288 case Profiler:
20289 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
20290
20291 case ContextProvider:
20292 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
20293
20294 case ContextConsumer:
20295 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
20296
20297 case MemoComponent:
20298 {
20299 var _type2 = workInProgress.type;
20300 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
20301
20302 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
20303
20304 {
20305 if (workInProgress.type !== workInProgress.elementType) {
20306 var outerPropTypes = _type2.propTypes;
20307
20308 if (outerPropTypes) {
20309 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
20310 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
20311 }
20312 }
20313 }
20314
20315 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
20316 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
20317 }
20318
20319 case SimpleMemoComponent:
20320 {
20321 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
20322 }
20323
20324 case IncompleteClassComponent:
20325 {
20326 var _Component3 = workInProgress.type;
20327 var _unresolvedProps4 = workInProgress.pendingProps;
20328
20329 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
20330
20331 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
20332 }
20333
20334 case SuspenseListComponent:
20335 {
20336 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20337 }
20338
20339 case FundamentalComponent:
20340 {
20341 if (enableFundamentalAPI) {
20342 return updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime);
20343 }
20344
20345 break;
20346 }
20347
20348 case ScopeComponent:
20349 {
20350 if (enableScopeAPI) {
20351 return updateScopeComponent(current$$1, workInProgress, renderExpirationTime);
20352 }
20353
20354 break;
20355 }
20356 }
20357
20358 (function () {
20359 {
20360 {
20361 throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
20362 }
20363 }
20364 })();
20365}
20366
20367function createFundamentalStateInstance(currentFiber, props, impl, state) {
20368 return {
20369 currentFiber: currentFiber,
20370 impl: impl,
20371 instance: null,
20372 prevProps: null,
20373 props: props,
20374 state: state
20375 };
20376}
20377
20378function isFiberSuspenseAndTimedOut(fiber) {
20379 return fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
20380}
20381
20382function getSuspenseFallbackChild(fiber) {
20383 return fiber.child.sibling.child;
20384}
20385
20386function collectScopedNodes(node, fn, scopedNodes) {
20387 if (enableScopeAPI) {
20388 if (node.tag === HostComponent) {
20389 var _type = node.type,
20390 memoizedProps = node.memoizedProps;
20391
20392 if (fn(_type, memoizedProps) === true) {
20393 scopedNodes.push(getPublicInstance(node.stateNode));
20394 }
20395 }
20396
20397 var child = node.child;
20398
20399 if (isFiberSuspenseAndTimedOut(node)) {
20400 child = getSuspenseFallbackChild(node);
20401 }
20402
20403 if (child !== null) {
20404 collectScopedNodesFromChildren(child, fn, scopedNodes);
20405 }
20406 }
20407}
20408
20409function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) {
20410 var child = startingChild;
20411
20412 while (child !== null) {
20413 collectScopedNodes(child, fn, scopedNodes);
20414 child = child.sibling;
20415 }
20416}
20417
20418function collectNearestScopeMethods(node, scope, childrenScopes) {
20419 if (isValidScopeNode(node, scope)) {
20420 childrenScopes.push(node.stateNode.methods);
20421 } else {
20422 var child = node.child;
20423
20424 if (isFiberSuspenseAndTimedOut(node)) {
20425 child = getSuspenseFallbackChild(node);
20426 }
20427
20428 if (child !== null) {
20429 collectNearestChildScopeMethods(child, scope, childrenScopes);
20430 }
20431 }
20432}
20433
20434function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) {
20435 var child = startingChild;
20436
20437 while (child !== null) {
20438 collectNearestScopeMethods(child, scope, childrenScopes);
20439 child = child.sibling;
20440 }
20441}
20442
20443function isValidScopeNode(node, scope) {
20444 return node.tag === ScopeComponent && node.type === scope;
20445}
20446
20447function createScopeMethods(scope, instance) {
20448 var fn = scope.fn;
20449 return {
20450 getChildren: function () {
20451 var currentFiber = instance.fiber;
20452 var child = currentFiber.child;
20453 var childrenScopes = [];
20454
20455 if (child !== null) {
20456 collectNearestChildScopeMethods(child, scope, childrenScopes);
20457 }
20458
20459 return childrenScopes.length === 0 ? null : childrenScopes;
20460 },
20461 getChildrenFromRoot: function () {
20462 var currentFiber = instance.fiber;
20463 var node = currentFiber;
20464
20465 while (node !== null) {
20466 var parent = node.return;
20467
20468 if (parent === null) {
20469 break;
20470 }
20471
20472 node = parent;
20473
20474 if (node.tag === ScopeComponent && node.type === scope) {
20475 break;
20476 }
20477 }
20478
20479 var childrenScopes = [];
20480 collectNearestChildScopeMethods(node.child, scope, childrenScopes);
20481 return childrenScopes.length === 0 ? null : childrenScopes;
20482 },
20483 getParent: function () {
20484 var node = instance.fiber.return;
20485
20486 while (node !== null) {
20487 if (node.tag === ScopeComponent && node.type === scope) {
20488 return node.stateNode.methods;
20489 }
20490
20491 node = node.return;
20492 }
20493
20494 return null;
20495 },
20496 getProps: function () {
20497 var currentFiber = instance.fiber;
20498 return currentFiber.memoizedProps;
20499 },
20500 getScopedNodes: function () {
20501 var currentFiber = instance.fiber;
20502 var child = currentFiber.child;
20503 var scopedNodes = [];
20504
20505 if (child !== null) {
20506 collectScopedNodesFromChildren(child, fn, scopedNodes);
20507 }
20508
20509 return scopedNodes.length === 0 ? null : scopedNodes;
20510 }
20511 };
20512}
20513
20514function markUpdate(workInProgress) {
20515 // Tag the fiber with an update effect. This turns a Placement into
20516 // a PlacementAndUpdate.
20517 workInProgress.effectTag |= Update;
20518}
20519
20520function markRef$1(workInProgress) {
20521 workInProgress.effectTag |= Ref;
20522}
20523
20524var appendAllChildren;
20525var updateHostContainer;
20526var updateHostComponent$1;
20527var updateHostText$1;
20528
20529if (supportsMutation) {
20530 // Mutation mode
20531 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20532 // We only have the top Fiber that was created but we need recurse down its
20533 // children to find all the terminal nodes.
20534 var node = workInProgress.child;
20535
20536 while (node !== null) {
20537 if (node.tag === HostComponent || node.tag === HostText) {
20538 appendInitialChild(parent, node.stateNode);
20539 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20540 appendInitialChild(parent, node.stateNode.instance);
20541 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20542 // down its children. Instead, we'll get insertions from each child in
20543 // the portal directly.
20544 } else if (node.child !== null) {
20545 node.child.return = node;
20546 node = node.child;
20547 continue;
20548 }
20549
20550 if (node === workInProgress) {
20551 return;
20552 }
20553
20554 while (node.sibling === null) {
20555 if (node.return === null || node.return === workInProgress) {
20556 return;
20557 }
20558
20559 node = node.return;
20560 }
20561
20562 node.sibling.return = node.return;
20563 node = node.sibling;
20564 }
20565 };
20566
20567 updateHostContainer = function (workInProgress) {// Noop
20568 };
20569
20570 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20571 // If we have an alternate, that means this is an update and we need to
20572 // schedule a side-effect to do the updates.
20573 var oldProps = current.memoizedProps;
20574
20575 if (oldProps === newProps) {
20576 // In mutation mode, this is sufficient for a bailout because
20577 // we won't touch this node even if children changed.
20578 return;
20579 } // If we get updated because one of our children updated, we don't
20580 // have newProps so we'll have to reuse them.
20581 // TODO: Split the update API as separate for the props vs. children.
20582 // Even better would be if children weren't special cased at all tho.
20583
20584
20585 var instance = workInProgress.stateNode;
20586 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
20587 // component is hitting the resume path. Figure out why. Possibly
20588 // related to `hidden`.
20589
20590 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
20591
20592 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
20593 // is a new ref we mark this as an update. All the work is done in commitWork.
20594
20595 if (updatePayload) {
20596 markUpdate(workInProgress);
20597 }
20598 };
20599
20600 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20601 // If the text differs, mark it as an update. All the work in done in commitWork.
20602 if (oldText !== newText) {
20603 markUpdate(workInProgress);
20604 }
20605 };
20606} else if (supportsPersistence) {
20607 // Persistent host tree mode
20608 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20609 // We only have the top Fiber that was created but we need recurse down its
20610 // children to find all the terminal nodes.
20611 var node = workInProgress.child;
20612
20613 while (node !== null) {
20614 // eslint-disable-next-line no-labels
20615 branches: if (node.tag === HostComponent) {
20616 var instance = node.stateNode;
20617
20618 if (needsVisibilityToggle && isHidden) {
20619 // This child is inside a timed out tree. Hide it.
20620 var props = node.memoizedProps;
20621 var type = node.type;
20622 instance = cloneHiddenInstance(instance, type, props, node);
20623 }
20624
20625 appendInitialChild(parent, instance);
20626 } else if (node.tag === HostText) {
20627 var _instance = node.stateNode;
20628
20629 if (needsVisibilityToggle && isHidden) {
20630 // This child is inside a timed out tree. Hide it.
20631 var text = node.memoizedProps;
20632 _instance = cloneHiddenTextInstance(_instance, text, node);
20633 }
20634
20635 appendInitialChild(parent, _instance);
20636 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20637 var _instance2 = node.stateNode.instance;
20638
20639 if (needsVisibilityToggle && isHidden) {
20640 // This child is inside a timed out tree. Hide it.
20641 var _props = node.memoizedProps;
20642 var _type = node.type;
20643 _instance2 = cloneHiddenInstance(_instance2, _type, _props, node);
20644 }
20645
20646 appendInitialChild(parent, _instance2);
20647 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20648 // down its children. Instead, we'll get insertions from each child in
20649 // the portal directly.
20650 } else if (node.tag === SuspenseComponent) {
20651 if ((node.effectTag & Update) !== NoEffect) {
20652 // Need to toggle the visibility of the primary children.
20653 var newIsHidden = node.memoizedState !== null;
20654
20655 if (newIsHidden) {
20656 var primaryChildParent = node.child;
20657
20658 if (primaryChildParent !== null) {
20659 if (primaryChildParent.child !== null) {
20660 primaryChildParent.child.return = primaryChildParent;
20661 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
20662 }
20663
20664 var fallbackChildParent = primaryChildParent.sibling;
20665
20666 if (fallbackChildParent !== null) {
20667 fallbackChildParent.return = node;
20668 node = fallbackChildParent;
20669 continue;
20670 }
20671 }
20672 }
20673 }
20674
20675 if (node.child !== null) {
20676 // Continue traversing like normal
20677 node.child.return = node;
20678 node = node.child;
20679 continue;
20680 }
20681 } else if (node.child !== null) {
20682 node.child.return = node;
20683 node = node.child;
20684 continue;
20685 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20686
20687
20688 node = node;
20689
20690 if (node === workInProgress) {
20691 return;
20692 }
20693
20694 while (node.sibling === null) {
20695 if (node.return === null || node.return === workInProgress) {
20696 return;
20697 }
20698
20699 node = node.return;
20700 }
20701
20702 node.sibling.return = node.return;
20703 node = node.sibling;
20704 }
20705 }; // An unfortunate fork of appendAllChildren because we have two different parent types.
20706
20707
20708 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
20709 // We only have the top Fiber that was created but we need recurse down its
20710 // children to find all the terminal nodes.
20711 var node = workInProgress.child;
20712
20713 while (node !== null) {
20714 // eslint-disable-next-line no-labels
20715 branches: if (node.tag === HostComponent) {
20716 var instance = node.stateNode;
20717
20718 if (needsVisibilityToggle && isHidden) {
20719 // This child is inside a timed out tree. Hide it.
20720 var props = node.memoizedProps;
20721 var type = node.type;
20722 instance = cloneHiddenInstance(instance, type, props, node);
20723 }
20724
20725 appendChildToContainerChildSet(containerChildSet, instance);
20726 } else if (node.tag === HostText) {
20727 var _instance3 = node.stateNode;
20728
20729 if (needsVisibilityToggle && isHidden) {
20730 // This child is inside a timed out tree. Hide it.
20731 var text = node.memoizedProps;
20732 _instance3 = cloneHiddenTextInstance(_instance3, text, node);
20733 }
20734
20735 appendChildToContainerChildSet(containerChildSet, _instance3);
20736 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20737 var _instance4 = node.stateNode.instance;
20738
20739 if (needsVisibilityToggle && isHidden) {
20740 // This child is inside a timed out tree. Hide it.
20741 var _props2 = node.memoizedProps;
20742 var _type2 = node.type;
20743 _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node);
20744 }
20745
20746 appendChildToContainerChildSet(containerChildSet, _instance4);
20747 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20748 // down its children. Instead, we'll get insertions from each child in
20749 // the portal directly.
20750 } else if (node.tag === SuspenseComponent) {
20751 if ((node.effectTag & Update) !== NoEffect) {
20752 // Need to toggle the visibility of the primary children.
20753 var newIsHidden = node.memoizedState !== null;
20754
20755 if (newIsHidden) {
20756 var primaryChildParent = node.child;
20757
20758 if (primaryChildParent !== null) {
20759 if (primaryChildParent.child !== null) {
20760 primaryChildParent.child.return = primaryChildParent;
20761 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
20762 }
20763
20764 var fallbackChildParent = primaryChildParent.sibling;
20765
20766 if (fallbackChildParent !== null) {
20767 fallbackChildParent.return = node;
20768 node = fallbackChildParent;
20769 continue;
20770 }
20771 }
20772 }
20773 }
20774
20775 if (node.child !== null) {
20776 // Continue traversing like normal
20777 node.child.return = node;
20778 node = node.child;
20779 continue;
20780 }
20781 } else if (node.child !== null) {
20782 node.child.return = node;
20783 node = node.child;
20784 continue;
20785 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20786
20787
20788 node = node;
20789
20790 if (node === workInProgress) {
20791 return;
20792 }
20793
20794 while (node.sibling === null) {
20795 if (node.return === null || node.return === workInProgress) {
20796 return;
20797 }
20798
20799 node = node.return;
20800 }
20801
20802 node.sibling.return = node.return;
20803 node = node.sibling;
20804 }
20805 };
20806
20807 updateHostContainer = function (workInProgress) {
20808 var portalOrRoot = workInProgress.stateNode;
20809 var childrenUnchanged = workInProgress.firstEffect === null;
20810
20811 if (childrenUnchanged) {// No changes, just reuse the existing instance.
20812 } else {
20813 var container = portalOrRoot.containerInfo;
20814 var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set.
20815
20816 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
20817 portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container.
20818
20819 markUpdate(workInProgress);
20820 finalizeContainerChildren(container, newChildSet);
20821 }
20822 };
20823
20824 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20825 var currentInstance = current.stateNode;
20826 var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates.
20827 // This guarantees that we can reuse all of them.
20828
20829 var childrenUnchanged = workInProgress.firstEffect === null;
20830
20831 if (childrenUnchanged && oldProps === newProps) {
20832 // No changes, just reuse the existing instance.
20833 // Note that this might release a previous clone.
20834 workInProgress.stateNode = currentInstance;
20835 return;
20836 }
20837
20838 var recyclableInstance = workInProgress.stateNode;
20839 var currentHostContext = getHostContext();
20840 var updatePayload = null;
20841
20842 if (oldProps !== newProps) {
20843 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
20844 }
20845
20846 if (childrenUnchanged && updatePayload === null) {
20847 // No changes, just reuse the existing instance.
20848 // Note that this might release a previous clone.
20849 workInProgress.stateNode = currentInstance;
20850 return;
20851 }
20852
20853 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
20854
20855 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
20856 markUpdate(workInProgress);
20857 }
20858
20859 workInProgress.stateNode = newInstance;
20860
20861 if (childrenUnchanged) {
20862 // If there are no other effects in this tree, we need to flag this node as having one.
20863 // Even though we're not going to use it for anything.
20864 // Otherwise parents won't know that there are new children to propagate upwards.
20865 markUpdate(workInProgress);
20866 } else {
20867 // If children might have changed, we have to add them all to the set.
20868 appendAllChildren(newInstance, workInProgress, false, false);
20869 }
20870 };
20871
20872 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20873 if (oldText !== newText) {
20874 // If the text content differs, we'll create a new text instance for it.
20875 var rootContainerInstance = getRootHostContainer();
20876 var currentHostContext = getHostContext();
20877 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything.
20878 // This lets the parents know that at least one of their children has changed.
20879
20880 markUpdate(workInProgress);
20881 }
20882 };
20883} else {
20884 // No host operations
20885 updateHostContainer = function (workInProgress) {// Noop
20886 };
20887
20888 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop
20889 };
20890
20891 updateHostText$1 = function (current, workInProgress, oldText, newText) {// Noop
20892 };
20893}
20894
20895function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
20896 switch (renderState.tailMode) {
20897 case 'hidden':
20898 {
20899 // Any insertions at the end of the tail list after this point
20900 // should be invisible. If there are already mounted boundaries
20901 // anything before them are not considered for collapsing.
20902 // Therefore we need to go through the whole tail to find if
20903 // there are any.
20904 var tailNode = renderState.tail;
20905 var lastTailNode = null;
20906
20907 while (tailNode !== null) {
20908 if (tailNode.alternate !== null) {
20909 lastTailNode = tailNode;
20910 }
20911
20912 tailNode = tailNode.sibling;
20913 } // Next we're simply going to delete all insertions after the
20914 // last rendered item.
20915
20916
20917 if (lastTailNode === null) {
20918 // All remaining items in the tail are insertions.
20919 renderState.tail = null;
20920 } else {
20921 // Detach the insertion after the last node that was already
20922 // inserted.
20923 lastTailNode.sibling = null;
20924 }
20925
20926 break;
20927 }
20928
20929 case 'collapsed':
20930 {
20931 // Any insertions at the end of the tail list after this point
20932 // should be invisible. If there are already mounted boundaries
20933 // anything before them are not considered for collapsing.
20934 // Therefore we need to go through the whole tail to find if
20935 // there are any.
20936 var _tailNode = renderState.tail;
20937 var _lastTailNode = null;
20938
20939 while (_tailNode !== null) {
20940 if (_tailNode.alternate !== null) {
20941 _lastTailNode = _tailNode;
20942 }
20943
20944 _tailNode = _tailNode.sibling;
20945 } // Next we're simply going to delete all insertions after the
20946 // last rendered item.
20947
20948
20949 if (_lastTailNode === null) {
20950 // All remaining items in the tail are insertions.
20951 if (!hasRenderedATailFallback && renderState.tail !== null) {
20952 // We suspended during the head. We want to show at least one
20953 // row at the tail. So we'll keep on and cut off the rest.
20954 renderState.tail.sibling = null;
20955 } else {
20956 renderState.tail = null;
20957 }
20958 } else {
20959 // Detach the insertion after the last node that was already
20960 // inserted.
20961 _lastTailNode.sibling = null;
20962 }
20963
20964 break;
20965 }
20966 }
20967}
20968
20969function completeWork(current, workInProgress, renderExpirationTime) {
20970 var newProps = workInProgress.pendingProps;
20971
20972 switch (workInProgress.tag) {
20973 case IndeterminateComponent:
20974 break;
20975
20976 case LazyComponent:
20977 break;
20978
20979 case SimpleMemoComponent:
20980 case FunctionComponent:
20981 break;
20982
20983 case ClassComponent:
20984 {
20985 var Component = workInProgress.type;
20986
20987 if (isContextProvider(Component)) {
20988 popContext(workInProgress);
20989 }
20990
20991 break;
20992 }
20993
20994 case HostRoot:
20995 {
20996 popHostContainer(workInProgress);
20997 popTopLevelContextObject(workInProgress);
20998 var fiberRoot = workInProgress.stateNode;
20999
21000 if (fiberRoot.pendingContext) {
21001 fiberRoot.context = fiberRoot.pendingContext;
21002 fiberRoot.pendingContext = null;
21003 }
21004
21005 if (current === null || current.child === null) {
21006 // If we hydrated, pop so that we can delete any remaining children
21007 // that weren't hydrated.
21008 var wasHydrated = popHydrationState(workInProgress);
21009
21010 if (wasHydrated) {
21011 // If we hydrated, then we'll need to schedule an update for
21012 // the commit side-effects on the root.
21013 markUpdate(workInProgress);
21014 }
21015 }
21016
21017 updateHostContainer(workInProgress);
21018 break;
21019 }
21020
21021 case HostComponent:
21022 {
21023 popHostContext(workInProgress);
21024 var rootContainerInstance = getRootHostContainer();
21025 var type = workInProgress.type;
21026
21027 if (current !== null && workInProgress.stateNode != null) {
21028 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
21029
21030 if (enableFlareAPI) {
21031 var prevListeners = current.memoizedProps.listeners;
21032 var nextListeners = newProps.listeners;
21033
21034 if (prevListeners !== nextListeners) {
21035 markUpdate(workInProgress);
21036 }
21037 }
21038
21039 if (current.ref !== workInProgress.ref) {
21040 markRef$1(workInProgress);
21041 }
21042 } else {
21043 if (!newProps) {
21044 (function () {
21045 if (!(workInProgress.stateNode !== null)) {
21046 {
21047 throw ReactError(Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."));
21048 }
21049 }
21050 })(); // This can happen when we abort work.
21051
21052
21053 break;
21054 }
21055
21056 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
21057 // "stack" as the parent. Then append children as we go in beginWork
21058 // or completeWork depending on we want to add then top->down or
21059 // bottom->up. Top->down is faster in IE11.
21060
21061 var _wasHydrated = popHydrationState(workInProgress);
21062
21063 if (_wasHydrated) {
21064 // TODO: Move this and createInstance step into the beginPhase
21065 // to consolidate.
21066 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
21067 // If changes to the hydrated node needs to be applied at the
21068 // commit-phase we mark this as such.
21069 markUpdate(workInProgress);
21070 }
21071
21072 if (enableFlareAPI) {
21073 var listeners = newProps.listeners;
21074
21075 if (listeners != null) {
21076 updateEventListeners(listeners, workInProgress, rootContainerInstance);
21077 }
21078 }
21079 } else {
21080 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
21081 appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
21082
21083 workInProgress.stateNode = instance;
21084
21085 if (enableFlareAPI) {
21086 var _listeners = newProps.listeners;
21087
21088 if (_listeners != null) {
21089 updateEventListeners(_listeners, workInProgress, rootContainerInstance);
21090 }
21091 } // Certain renderers require commit-time effects for initial mount.
21092 // (eg DOM renderer supports auto-focus for certain elements).
21093 // Make sure such renderers get scheduled for later work.
21094
21095
21096 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
21097 markUpdate(workInProgress);
21098 }
21099 }
21100
21101 if (workInProgress.ref !== null) {
21102 // If there is a ref on a host node we need to schedule a callback
21103 markRef$1(workInProgress);
21104 }
21105 }
21106
21107 break;
21108 }
21109
21110 case HostText:
21111 {
21112 var newText = newProps;
21113
21114 if (current && workInProgress.stateNode != null) {
21115 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
21116 // to schedule a side-effect to do the updates.
21117
21118 updateHostText$1(current, workInProgress, oldText, newText);
21119 } else {
21120 if (typeof newText !== 'string') {
21121 (function () {
21122 if (!(workInProgress.stateNode !== null)) {
21123 {
21124 throw ReactError(Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."));
21125 }
21126 }
21127 })(); // This can happen when we abort work.
21128
21129 }
21130
21131 var _rootContainerInstance = getRootHostContainer();
21132
21133 var _currentHostContext = getHostContext();
21134
21135 var _wasHydrated2 = popHydrationState(workInProgress);
21136
21137 if (_wasHydrated2) {
21138 if (prepareToHydrateHostTextInstance(workInProgress)) {
21139 markUpdate(workInProgress);
21140 }
21141 } else {
21142 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
21143 }
21144 }
21145
21146 break;
21147 }
21148
21149 case ForwardRef:
21150 break;
21151
21152 case SuspenseComponent:
21153 {
21154 popSuspenseContext(workInProgress);
21155 var nextState = workInProgress.memoizedState;
21156
21157 if (enableSuspenseServerRenderer) {
21158 if (nextState !== null && nextState.dehydrated !== null) {
21159 if (current === null) {
21160 var _wasHydrated3 = popHydrationState(workInProgress);
21161
21162 (function () {
21163 if (!_wasHydrated3) {
21164 {
21165 throw ReactError(Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."));
21166 }
21167 }
21168 })();
21169
21170 prepareToHydrateHostSuspenseInstance(workInProgress);
21171
21172 if (enableSchedulerTracing) {
21173 markSpawnedWork(Never);
21174 }
21175
21176 return null;
21177 } else {
21178 // We should never have been in a hydration state if we didn't have a current.
21179 // However, in some of those paths, we might have reentered a hydration state
21180 // and then we might be inside a hydration state. In that case, we'll need to
21181 // exit out of it.
21182 resetHydrationState();
21183
21184 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
21185 // This boundary did not suspend so it's now hydrated and unsuspended.
21186 workInProgress.memoizedState = null;
21187 } // If nothing suspended, we need to schedule an effect to mark this boundary
21188 // as having hydrated so events know that they're free be invoked.
21189 // It's also a signal to replay events and the suspense callback.
21190 // If something suspended, schedule an effect to attach retry listeners.
21191 // So we might as well always mark this.
21192
21193
21194 workInProgress.effectTag |= Update;
21195 return null;
21196 }
21197 }
21198 }
21199
21200 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
21201 // Something suspended. Re-render with the fallback children.
21202 workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
21203
21204 return workInProgress;
21205 }
21206
21207 var nextDidTimeout = nextState !== null;
21208 var prevDidTimeout = false;
21209
21210 if (current === null) {
21211 // In cases where we didn't find a suitable hydration boundary we never
21212 // put this in dehydrated mode, but we still need to pop the hydration
21213 // state since we might be inside the insertion tree.
21214 popHydrationState(workInProgress);
21215 } else {
21216 var prevState = current.memoizedState;
21217 prevDidTimeout = prevState !== null;
21218
21219 if (!nextDidTimeout && prevState !== null) {
21220 // We just switched from the fallback to the normal children.
21221 // Delete the fallback.
21222 // TODO: Would it be better to store the fallback fragment on
21223 // the stateNode during the begin phase?
21224 var currentFallbackChild = current.child.sibling;
21225
21226 if (currentFallbackChild !== null) {
21227 // Deletions go at the beginning of the return fiber's effect list
21228 var first = workInProgress.firstEffect;
21229
21230 if (first !== null) {
21231 workInProgress.firstEffect = currentFallbackChild;
21232 currentFallbackChild.nextEffect = first;
21233 } else {
21234 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
21235 currentFallbackChild.nextEffect = null;
21236 }
21237
21238 currentFallbackChild.effectTag = Deletion;
21239 }
21240 }
21241 }
21242
21243 if (nextDidTimeout && !prevDidTimeout) {
21244 // If this subtreee is running in batched mode we can suspend,
21245 // otherwise we won't suspend.
21246 // TODO: This will still suspend a synchronous tree if anything
21247 // in the concurrent tree already suspended during this render.
21248 // This is a known bug.
21249 if ((workInProgress.mode & BatchedMode) !== NoMode) {
21250 // TODO: Move this back to throwException because this is too late
21251 // if this is a large tree which is common for initial loads. We
21252 // don't know if we should restart a render or not until we get
21253 // this marker, and this is too late.
21254 // If this render already had a ping or lower pri updates,
21255 // and this is the first time we know we're going to suspend we
21256 // should be able to immediately restart from within throwException.
21257 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
21258
21259 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
21260 // If this was in an invisible tree or a new render, then showing
21261 // this boundary is ok.
21262 renderDidSuspend();
21263 } else {
21264 // Otherwise, we're going to have to hide content so we should
21265 // suspend for longer if possible.
21266 renderDidSuspendDelayIfPossible();
21267 }
21268 }
21269 }
21270
21271 if (supportsPersistence) {
21272 // TODO: Only schedule updates if not prevDidTimeout.
21273 if (nextDidTimeout) {
21274 // If this boundary just timed out, schedule an effect to attach a
21275 // retry listener to the proimse. This flag is also used to hide the
21276 // primary children.
21277 workInProgress.effectTag |= Update;
21278 }
21279 }
21280
21281 if (supportsMutation) {
21282 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
21283 if (nextDidTimeout || prevDidTimeout) {
21284 // If this boundary just timed out, schedule an effect to attach a
21285 // retry listener to the proimse. This flag is also used to hide the
21286 // primary children. In mutation mode, we also need the flag to
21287 // *unhide* children that were previously hidden, so check if the
21288 // is currently timed out, too.
21289 workInProgress.effectTag |= Update;
21290 }
21291 }
21292
21293 if (enableSuspenseCallback && workInProgress.updateQueue !== null && workInProgress.memoizedProps.suspenseCallback != null) {
21294 // Always notify the callback
21295 workInProgress.effectTag |= Update;
21296 }
21297
21298 break;
21299 }
21300
21301 case Fragment:
21302 break;
21303
21304 case Mode:
21305 break;
21306
21307 case Profiler:
21308 break;
21309
21310 case HostPortal:
21311 popHostContainer(workInProgress);
21312 updateHostContainer(workInProgress);
21313 break;
21314
21315 case ContextProvider:
21316 // Pop provider fiber
21317 popProvider(workInProgress);
21318 break;
21319
21320 case ContextConsumer:
21321 break;
21322
21323 case MemoComponent:
21324 break;
21325
21326 case IncompleteClassComponent:
21327 {
21328 // Same as class component case. I put it down here so that the tags are
21329 // sequential to ensure this switch is compiled to a jump table.
21330 var _Component = workInProgress.type;
21331
21332 if (isContextProvider(_Component)) {
21333 popContext(workInProgress);
21334 }
21335
21336 break;
21337 }
21338
21339 case SuspenseListComponent:
21340 {
21341 popSuspenseContext(workInProgress);
21342 var renderState = workInProgress.memoizedState;
21343
21344 if (renderState === null) {
21345 // We're running in the default, "independent" mode. We don't do anything
21346 // in this mode.
21347 break;
21348 }
21349
21350 var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
21351 var renderedTail = renderState.rendering;
21352
21353 if (renderedTail === null) {
21354 // We just rendered the head.
21355 if (!didSuspendAlready) {
21356 // This is the first pass. We need to figure out if anything is still
21357 // suspended in the rendered set.
21358 // If new content unsuspended, but there's still some content that
21359 // didn't. Then we need to do a second pass that forces everything
21360 // to keep showing their fallbacks.
21361 // We might be suspended if something in this render pass suspended, or
21362 // something in the previous committed pass suspended. Otherwise,
21363 // there's no chance so we can skip the expensive call to
21364 // findFirstSuspended.
21365 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
21366
21367 if (!cannotBeSuspended) {
21368 var row = workInProgress.child;
21369
21370 while (row !== null) {
21371 var suspended = findFirstSuspended(row);
21372
21373 if (suspended !== null) {
21374 didSuspendAlready = true;
21375 workInProgress.effectTag |= DidCapture;
21376 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
21377 // part of the second pass. In that case nothing will subscribe to
21378 // its thennables. Instead, we'll transfer its thennables to the
21379 // SuspenseList so that it can retry if they resolve.
21380 // There might be multiple of these in the list but since we're
21381 // going to wait for all of them anyway, it doesn't really matter
21382 // which ones gets to ping. In theory we could get clever and keep
21383 // track of how many dependencies remain but it gets tricky because
21384 // in the meantime, we can add/remove/change items and dependencies.
21385 // We might bail out of the loop before finding any but that
21386 // doesn't matter since that means that the other boundaries that
21387 // we did find already has their listeners attached.
21388
21389 var newThennables = suspended.updateQueue;
21390
21391 if (newThennables !== null) {
21392 workInProgress.updateQueue = newThennables;
21393 workInProgress.effectTag |= Update;
21394 } // Rerender the whole list, but this time, we'll force fallbacks
21395 // to stay in place.
21396 // Reset the effect list before doing the second pass since that's now invalid.
21397
21398
21399 workInProgress.firstEffect = workInProgress.lastEffect = null; // Reset the child fibers to their original state.
21400
21401 resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
21402 // rerender the children.
21403
21404 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
21405 return workInProgress.child;
21406 }
21407
21408 row = row.sibling;
21409 }
21410 }
21411 } else {
21412 cutOffTailIfNeeded(renderState, false);
21413 } // Next we're going to render the tail.
21414
21415 } else {
21416 // Append the rendered row to the child list.
21417 if (!didSuspendAlready) {
21418 var _suspended = findFirstSuspended(renderedTail);
21419
21420 if (_suspended !== null) {
21421 workInProgress.effectTag |= DidCapture;
21422 didSuspendAlready = true;
21423 cutOffTailIfNeeded(renderState, true); // This might have been modified.
21424
21425 if (renderState.tail === null && renderState.tailMode === 'hidden') {
21426 // We need to delete the row we just rendered.
21427 // Ensure we transfer the update queue to the parent.
21428 var _newThennables = _suspended.updateQueue;
21429
21430 if (_newThennables !== null) {
21431 workInProgress.updateQueue = _newThennables;
21432 workInProgress.effectTag |= Update;
21433 } // Reset the effect list to what it w as before we rendered this
21434 // child. The nested children have already appended themselves.
21435
21436
21437 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
21438
21439 if (lastEffect !== null) {
21440 lastEffect.nextEffect = null;
21441 } // We're done.
21442
21443
21444 return null;
21445 }
21446 } else if (now() > renderState.tailExpiration && renderExpirationTime > Never) {
21447 // We have now passed our CPU deadline and we'll just give up further
21448 // attempts to render the main content and only render fallbacks.
21449 // The assumption is that this is usually faster.
21450 workInProgress.effectTag |= DidCapture;
21451 didSuspendAlready = true;
21452 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
21453 // to get it started back up to attempt the next item. If we can show
21454 // them, then they really have the same priority as this render.
21455 // So we'll pick it back up the very next render pass once we've had
21456 // an opportunity to yield for paint.
21457
21458 var nextPriority = renderExpirationTime - 1;
21459 workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
21460
21461 if (enableSchedulerTracing) {
21462 markSpawnedWork(nextPriority);
21463 }
21464 }
21465 }
21466
21467 if (renderState.isBackwards) {
21468 // The effect list of the backwards tail will have been added
21469 // to the end. This breaks the guarantee that life-cycles fire in
21470 // sibling order but that isn't a strong guarantee promised by React.
21471 // Especially since these might also just pop in during future commits.
21472 // Append to the beginning of the list.
21473 renderedTail.sibling = workInProgress.child;
21474 workInProgress.child = renderedTail;
21475 } else {
21476 var previousSibling = renderState.last;
21477
21478 if (previousSibling !== null) {
21479 previousSibling.sibling = renderedTail;
21480 } else {
21481 workInProgress.child = renderedTail;
21482 }
21483
21484 renderState.last = renderedTail;
21485 }
21486 }
21487
21488 if (renderState.tail !== null) {
21489 // We still have tail rows to render.
21490 if (renderState.tailExpiration === 0) {
21491 // Heuristic for how long we're willing to spend rendering rows
21492 // until we just give up and show what we have so far.
21493 var TAIL_EXPIRATION_TIMEOUT_MS = 500;
21494 renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
21495 } // Pop a row.
21496
21497
21498 var next = renderState.tail;
21499 renderState.rendering = next;
21500 renderState.tail = next.sibling;
21501 renderState.lastEffect = workInProgress.lastEffect;
21502 next.sibling = null; // Restore the context.
21503 // TODO: We can probably just avoid popping it instead and only
21504 // setting it the first time we go from not suspended to suspended.
21505
21506 var suspenseContext = suspenseStackCursor.current;
21507
21508 if (didSuspendAlready) {
21509 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21510 } else {
21511 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21512 }
21513
21514 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
21515
21516 return next;
21517 }
21518
21519 break;
21520 }
21521
21522 case FundamentalComponent:
21523 {
21524 if (enableFundamentalAPI) {
21525 var fundamentalImpl = workInProgress.type.impl;
21526 var fundamentalInstance = workInProgress.stateNode;
21527
21528 if (fundamentalInstance === null) {
21529 var getInitialState = fundamentalImpl.getInitialState;
21530 var fundamentalState;
21531
21532 if (getInitialState !== undefined) {
21533 fundamentalState = getInitialState(newProps);
21534 }
21535
21536 fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(workInProgress, newProps, fundamentalImpl, fundamentalState || {});
21537
21538 var _instance5 = getFundamentalComponentInstance(fundamentalInstance);
21539
21540 fundamentalInstance.instance = _instance5;
21541
21542 if (fundamentalImpl.reconcileChildren === false) {
21543 return null;
21544 }
21545
21546 appendAllChildren(_instance5, workInProgress, false, false);
21547 mountFundamentalComponent(fundamentalInstance);
21548 } else {
21549 // We fire update in commit phase
21550 var prevProps = fundamentalInstance.props;
21551 fundamentalInstance.prevProps = prevProps;
21552 fundamentalInstance.props = newProps;
21553 fundamentalInstance.currentFiber = workInProgress;
21554
21555 if (supportsPersistence) {
21556 var _instance6 = cloneFundamentalInstance(fundamentalInstance);
21557
21558 fundamentalInstance.instance = _instance6;
21559 appendAllChildren(_instance6, workInProgress, false, false);
21560 }
21561
21562 var shouldUpdate = shouldUpdateFundamentalComponent(fundamentalInstance);
21563
21564 if (shouldUpdate) {
21565 markUpdate(workInProgress);
21566 }
21567 }
21568 }
21569
21570 break;
21571 }
21572
21573 case ScopeComponent:
21574 {
21575 if (enableScopeAPI) {
21576 if (current === null) {
21577 var _type3 = workInProgress.type;
21578 var scopeInstance = {
21579 fiber: workInProgress,
21580 methods: null
21581 };
21582 workInProgress.stateNode = scopeInstance;
21583 scopeInstance.methods = createScopeMethods(_type3, scopeInstance);
21584
21585 if (enableFlareAPI) {
21586 var _listeners2 = newProps.listeners;
21587
21588 if (_listeners2 != null) {
21589 var _rootContainerInstance2 = getRootHostContainer();
21590
21591 updateEventListeners(_listeners2, workInProgress, _rootContainerInstance2);
21592 }
21593 }
21594
21595 if (workInProgress.ref !== null) {
21596 markRef$1(workInProgress);
21597 markUpdate(workInProgress);
21598 }
21599 } else {
21600 if (enableFlareAPI) {
21601 var _prevListeners = current.memoizedProps.listeners;
21602 var _nextListeners = newProps.listeners;
21603
21604 if (_prevListeners !== _nextListeners || workInProgress.ref !== null) {
21605 markUpdate(workInProgress);
21606 }
21607 } else {
21608 if (workInProgress.ref !== null) {
21609 markUpdate(workInProgress);
21610 }
21611 }
21612
21613 if (current.ref !== workInProgress.ref) {
21614 markRef$1(workInProgress);
21615 }
21616 }
21617 }
21618
21619 break;
21620 }
21621
21622 default:
21623 (function () {
21624 {
21625 {
21626 throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
21627 }
21628 }
21629 })();
21630
21631 }
21632
21633 return null;
21634}
21635
21636function unwindWork(workInProgress, renderExpirationTime) {
21637 switch (workInProgress.tag) {
21638 case ClassComponent:
21639 {
21640 var Component = workInProgress.type;
21641
21642 if (isContextProvider(Component)) {
21643 popContext(workInProgress);
21644 }
21645
21646 var effectTag = workInProgress.effectTag;
21647
21648 if (effectTag & ShouldCapture) {
21649 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
21650 return workInProgress;
21651 }
21652
21653 return null;
21654 }
21655
21656 case HostRoot:
21657 {
21658 popHostContainer(workInProgress);
21659 popTopLevelContextObject(workInProgress);
21660 var _effectTag = workInProgress.effectTag;
21661
21662 (function () {
21663 if (!((_effectTag & DidCapture) === NoEffect)) {
21664 {
21665 throw ReactError(Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue."));
21666 }
21667 }
21668 })();
21669
21670 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
21671 return workInProgress;
21672 }
21673
21674 case HostComponent:
21675 {
21676 // TODO: popHydrationState
21677 popHostContext(workInProgress);
21678 return null;
21679 }
21680
21681 case SuspenseComponent:
21682 {
21683 popSuspenseContext(workInProgress);
21684
21685 if (enableSuspenseServerRenderer) {
21686 var suspenseState = workInProgress.memoizedState;
21687
21688 if (suspenseState !== null && suspenseState.dehydrated !== null) {
21689 (function () {
21690 if (!(workInProgress.alternate !== null)) {
21691 {
21692 throw ReactError(Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."));
21693 }
21694 }
21695 })();
21696
21697 resetHydrationState();
21698 }
21699 }
21700
21701 var _effectTag2 = workInProgress.effectTag;
21702
21703 if (_effectTag2 & ShouldCapture) {
21704 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
21705
21706 return workInProgress;
21707 }
21708
21709 return null;
21710 }
21711
21712 case SuspenseListComponent:
21713 {
21714 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
21715 // caught by a nested boundary. If not, it should bubble through.
21716
21717 return null;
21718 }
21719
21720 case HostPortal:
21721 popHostContainer(workInProgress);
21722 return null;
21723
21724 case ContextProvider:
21725 popProvider(workInProgress);
21726 return null;
21727
21728 default:
21729 return null;
21730 }
21731}
21732
21733function unwindInterruptedWork(interruptedWork) {
21734 switch (interruptedWork.tag) {
21735 case ClassComponent:
21736 {
21737 var childContextTypes = interruptedWork.type.childContextTypes;
21738
21739 if (childContextTypes !== null && childContextTypes !== undefined) {
21740 popContext(interruptedWork);
21741 }
21742
21743 break;
21744 }
21745
21746 case HostRoot:
21747 {
21748 popHostContainer(interruptedWork);
21749 popTopLevelContextObject(interruptedWork);
21750 break;
21751 }
21752
21753 case HostComponent:
21754 {
21755 popHostContext(interruptedWork);
21756 break;
21757 }
21758
21759 case HostPortal:
21760 popHostContainer(interruptedWork);
21761 break;
21762
21763 case SuspenseComponent:
21764 popSuspenseContext(interruptedWork);
21765 break;
21766
21767 case SuspenseListComponent:
21768 popSuspenseContext(interruptedWork);
21769 break;
21770
21771 case ContextProvider:
21772 popProvider(interruptedWork);
21773 break;
21774
21775 default:
21776 break;
21777 }
21778}
21779
21780function createCapturedValue(value, source) {
21781 // If the value is an error, call this function immediately after it is thrown
21782 // so the stack is accurate.
21783 return {
21784 value: value,
21785 source: source,
21786 stack: getStackByFiberInDevAndProd(source)
21787 };
21788}
21789
21790// This module is forked in different environments.
21791// By default, return `true` to log errors to the console.
21792// Forks can return `false` if this isn't desirable.
21793function showErrorDialog(capturedError) {
21794 return true;
21795}
21796
21797function logCapturedError(capturedError) {
21798 var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging.
21799 // This enables renderers like ReactNative to better manage redbox behavior.
21800
21801 if (logError === false) {
21802 return;
21803 }
21804
21805 var error = capturedError.error;
21806
21807 {
21808 var componentName = capturedError.componentName,
21809 componentStack = capturedError.componentStack,
21810 errorBoundaryName = capturedError.errorBoundaryName,
21811 errorBoundaryFound = capturedError.errorBoundaryFound,
21812 willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
21813 // `preventDefault()` in window `error` handler.
21814 // We record this information as an expando on the error.
21815
21816 if (error != null && error._suppressLogging) {
21817 if (errorBoundaryFound && willRetry) {
21818 // The error is recoverable and was silenced.
21819 // Ignore it and don't print the stack addendum.
21820 // This is handy for testing error boundaries without noise.
21821 return;
21822 } // The error is fatal. Since the silencing might have
21823 // been accidental, we'll surface it anyway.
21824 // However, the browser would have silenced the original error
21825 // so we'll print it first, and then print the stack addendum.
21826
21827
21828 console.error(error); // For a more detailed description of this block, see:
21829 // https://github.com/facebook/react/pull/13384
21830 }
21831
21832 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
21833 var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
21834
21835 if (errorBoundaryFound && errorBoundaryName) {
21836 if (willRetry) {
21837 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
21838 } else {
21839 errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
21840 }
21841 } else {
21842 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.';
21843 }
21844
21845 var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
21846 // We don't include the original error message and JS stack because the browser
21847 // has already printed it. Even if the application swallows the error, it is still
21848 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
21849
21850 console.error(combinedMessage);
21851 }
21852}
21853
21854var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
21855
21856{
21857 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
21858}
21859
21860var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
21861function logError(boundary, errorInfo) {
21862 var source = errorInfo.source;
21863 var stack = errorInfo.stack;
21864
21865 if (stack === null && source !== null) {
21866 stack = getStackByFiberInDevAndProd(source);
21867 }
21868
21869 var capturedError = {
21870 componentName: source !== null ? getComponentName(source.type) : null,
21871 componentStack: stack !== null ? stack : '',
21872 error: errorInfo.value,
21873 errorBoundary: null,
21874 errorBoundaryName: null,
21875 errorBoundaryFound: false,
21876 willRetry: false
21877 };
21878
21879 if (boundary !== null && boundary.tag === ClassComponent) {
21880 capturedError.errorBoundary = boundary.stateNode;
21881 capturedError.errorBoundaryName = getComponentName(boundary.type);
21882 capturedError.errorBoundaryFound = true;
21883 capturedError.willRetry = true;
21884 }
21885
21886 try {
21887 logCapturedError(capturedError);
21888 } catch (e) {
21889 // This method must not throw, or React internal state will get messed up.
21890 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
21891 // we want to report this error outside of the normal stack as a last resort.
21892 // https://github.com/facebook/react/issues/13188
21893 setTimeout(function () {
21894 throw e;
21895 });
21896 }
21897}
21898
21899var callComponentWillUnmountWithTimer = function (current$$1, instance) {
21900 startPhaseTimer(current$$1, 'componentWillUnmount');
21901 instance.props = current$$1.memoizedProps;
21902 instance.state = current$$1.memoizedState;
21903 instance.componentWillUnmount();
21904 stopPhaseTimer();
21905}; // Capture errors so they don't interrupt unmounting.
21906
21907
21908function safelyCallComponentWillUnmount(current$$1, instance) {
21909 {
21910 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
21911
21912 if (hasCaughtError()) {
21913 var unmountError = clearCaughtError();
21914 captureCommitPhaseError(current$$1, unmountError);
21915 }
21916 }
21917}
21918
21919function safelyDetachRef(current$$1) {
21920 var ref = current$$1.ref;
21921
21922 if (ref !== null) {
21923 if (typeof ref === 'function') {
21924 {
21925 invokeGuardedCallback(null, ref, null, null);
21926
21927 if (hasCaughtError()) {
21928 var refError = clearCaughtError();
21929 captureCommitPhaseError(current$$1, refError);
21930 }
21931 }
21932 } else {
21933 ref.current = null;
21934 }
21935 }
21936}
21937
21938function safelyCallDestroy(current$$1, destroy) {
21939 {
21940 invokeGuardedCallback(null, destroy, null);
21941
21942 if (hasCaughtError()) {
21943 var error = clearCaughtError();
21944 captureCommitPhaseError(current$$1, error);
21945 }
21946 }
21947}
21948
21949function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
21950 switch (finishedWork.tag) {
21951 case FunctionComponent:
21952 case ForwardRef:
21953 case SimpleMemoComponent:
21954 {
21955 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
21956 return;
21957 }
21958
21959 case ClassComponent:
21960 {
21961 if (finishedWork.effectTag & Snapshot) {
21962 if (current$$1 !== null) {
21963 var prevProps = current$$1.memoizedProps;
21964 var prevState = current$$1.memoizedState;
21965 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
21966 var instance = finishedWork.stateNode; // We could update instance props and state here,
21967 // but instead we rely on them being set during last render.
21968 // TODO: revisit this when we implement resuming.
21969
21970 {
21971 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21972 !(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;
21973 !(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;
21974 }
21975 }
21976
21977 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
21978
21979 {
21980 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
21981
21982 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
21983 didWarnSet.add(finishedWork.type);
21984 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
21985 }
21986 }
21987
21988 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
21989 stopPhaseTimer();
21990 }
21991 }
21992
21993 return;
21994 }
21995
21996 case HostRoot:
21997 case HostComponent:
21998 case HostText:
21999 case HostPortal:
22000 case IncompleteClassComponent:
22001 // Nothing to do for these component types
22002 return;
22003
22004 default:
22005 {
22006 (function () {
22007 {
22008 {
22009 throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22010 }
22011 }
22012 })();
22013 }
22014 }
22015}
22016
22017function commitHookEffectList(unmountTag, mountTag, finishedWork) {
22018 var updateQueue = finishedWork.updateQueue;
22019 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
22020
22021 if (lastEffect !== null) {
22022 var firstEffect = lastEffect.next;
22023 var effect = firstEffect;
22024
22025 do {
22026 if ((effect.tag & unmountTag) !== NoEffect$1) {
22027 // Unmount
22028 var destroy = effect.destroy;
22029 effect.destroy = undefined;
22030
22031 if (destroy !== undefined) {
22032 destroy();
22033 }
22034 }
22035
22036 if ((effect.tag & mountTag) !== NoEffect$1) {
22037 // Mount
22038 var create = effect.create;
22039 effect.destroy = create();
22040
22041 {
22042 var _destroy = effect.destroy;
22043
22044 if (_destroy !== undefined && typeof _destroy !== 'function') {
22045 var addendum = void 0;
22046
22047 if (_destroy === null) {
22048 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
22049 } else if (typeof _destroy.then === 'function') {
22050 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';
22051 } else {
22052 addendum = ' You returned: ' + _destroy;
22053 }
22054
22055 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
22056 }
22057 }
22058 }
22059
22060 effect = effect.next;
22061 } while (effect !== firstEffect);
22062 }
22063}
22064
22065function commitPassiveHookEffects(finishedWork) {
22066 if ((finishedWork.effectTag & Passive) !== NoEffect) {
22067 switch (finishedWork.tag) {
22068 case FunctionComponent:
22069 case ForwardRef:
22070 case SimpleMemoComponent:
22071 {
22072 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
22073 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
22074 break;
22075 }
22076
22077 default:
22078 break;
22079 }
22080 }
22081}
22082
22083function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
22084 switch (finishedWork.tag) {
22085 case FunctionComponent:
22086 case ForwardRef:
22087 case SimpleMemoComponent:
22088 {
22089 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
22090 break;
22091 }
22092
22093 case ClassComponent:
22094 {
22095 var instance = finishedWork.stateNode;
22096
22097 if (finishedWork.effectTag & Update) {
22098 if (current$$1 === null) {
22099 startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
22100 // but instead we rely on them being set during last render.
22101 // TODO: revisit this when we implement resuming.
22102
22103 {
22104 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22105 !(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;
22106 !(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;
22107 }
22108 }
22109
22110 instance.componentDidMount();
22111 stopPhaseTimer();
22112 } else {
22113 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
22114 var prevState = current$$1.memoizedState;
22115 startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
22116 // but instead we rely on them being set during last render.
22117 // TODO: revisit this when we implement resuming.
22118
22119 {
22120 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22121 !(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;
22122 !(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;
22123 }
22124 }
22125
22126 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
22127 stopPhaseTimer();
22128 }
22129 }
22130
22131 var updateQueue = finishedWork.updateQueue;
22132
22133 if (updateQueue !== null) {
22134 {
22135 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22136 !(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;
22137 !(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;
22138 }
22139 } // We could update instance props and state here,
22140 // but instead we rely on them being set during last render.
22141 // TODO: revisit this when we implement resuming.
22142
22143
22144 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
22145 }
22146
22147 return;
22148 }
22149
22150 case HostRoot:
22151 {
22152 var _updateQueue = finishedWork.updateQueue;
22153
22154 if (_updateQueue !== null) {
22155 var _instance = null;
22156
22157 if (finishedWork.child !== null) {
22158 switch (finishedWork.child.tag) {
22159 case HostComponent:
22160 _instance = getPublicInstance(finishedWork.child.stateNode);
22161 break;
22162
22163 case ClassComponent:
22164 _instance = finishedWork.child.stateNode;
22165 break;
22166 }
22167 }
22168
22169 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
22170 }
22171
22172 return;
22173 }
22174
22175 case HostComponent:
22176 {
22177 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
22178 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
22179 // These effects should only be committed when components are first mounted,
22180 // aka when there is no current/alternate.
22181
22182 if (current$$1 === null && finishedWork.effectTag & Update) {
22183 var type = finishedWork.type;
22184 var props = finishedWork.memoizedProps;
22185 commitMount(_instance2, type, props, finishedWork);
22186 }
22187
22188 return;
22189 }
22190
22191 case HostText:
22192 {
22193 // We have no life-cycles associated with text.
22194 return;
22195 }
22196
22197 case HostPortal:
22198 {
22199 // We have no life-cycles associated with portals.
22200 return;
22201 }
22202
22203 case Profiler:
22204 {
22205 if (enableProfilerTimer) {
22206 var onRender = finishedWork.memoizedProps.onRender;
22207
22208 if (typeof onRender === 'function') {
22209 if (enableSchedulerTracing) {
22210 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
22211 } else {
22212 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
22213 }
22214 }
22215 }
22216
22217 return;
22218 }
22219
22220 case SuspenseComponent:
22221 {
22222 commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
22223 return;
22224 }
22225
22226 case SuspenseListComponent:
22227 case IncompleteClassComponent:
22228 case FundamentalComponent:
22229 case ScopeComponent:
22230 return;
22231
22232 default:
22233 {
22234 (function () {
22235 {
22236 {
22237 throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22238 }
22239 }
22240 })();
22241 }
22242 }
22243}
22244
22245function hideOrUnhideAllChildren(finishedWork, isHidden) {
22246 if (supportsMutation) {
22247 // We only have the top Fiber that was inserted but we need to recurse down its
22248 // children to find all the terminal nodes.
22249 var node = finishedWork;
22250
22251 while (true) {
22252 if (node.tag === HostComponent) {
22253 var instance = node.stateNode;
22254
22255 if (isHidden) {
22256 hideInstance(instance);
22257 } else {
22258 unhideInstance(node.stateNode, node.memoizedProps);
22259 }
22260 } else if (node.tag === HostText) {
22261 var _instance3 = node.stateNode;
22262
22263 if (isHidden) {
22264 hideTextInstance(_instance3);
22265 } else {
22266 unhideTextInstance(_instance3, node.memoizedProps);
22267 }
22268 } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
22269 // Found a nested Suspense component that timed out. Skip over the
22270 // primary child fragment, which should remain hidden.
22271 var fallbackChildFragment = node.child.sibling;
22272 fallbackChildFragment.return = node;
22273 node = fallbackChildFragment;
22274 continue;
22275 } else if (node.child !== null) {
22276 node.child.return = node;
22277 node = node.child;
22278 continue;
22279 }
22280
22281 if (node === finishedWork) {
22282 return;
22283 }
22284
22285 while (node.sibling === null) {
22286 if (node.return === null || node.return === finishedWork) {
22287 return;
22288 }
22289
22290 node = node.return;
22291 }
22292
22293 node.sibling.return = node.return;
22294 node = node.sibling;
22295 }
22296 }
22297}
22298
22299function commitAttachRef(finishedWork) {
22300 var ref = finishedWork.ref;
22301
22302 if (ref !== null) {
22303 var instance = finishedWork.stateNode;
22304 var instanceToUse;
22305
22306 switch (finishedWork.tag) {
22307 case HostComponent:
22308 instanceToUse = getPublicInstance(instance);
22309 break;
22310
22311 default:
22312 instanceToUse = instance;
22313 } // Moved outside to ensure DCE works with this flag
22314
22315
22316 if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
22317 instanceToUse = instance.methods;
22318 }
22319
22320 if (typeof ref === 'function') {
22321 ref(instanceToUse);
22322 } else {
22323 {
22324 if (!ref.hasOwnProperty('current')) {
22325 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
22326 }
22327 }
22328
22329 ref.current = instanceToUse;
22330 }
22331 }
22332}
22333
22334function commitDetachRef(current$$1) {
22335 var currentRef = current$$1.ref;
22336
22337 if (currentRef !== null) {
22338 if (typeof currentRef === 'function') {
22339 currentRef(null);
22340 } else {
22341 currentRef.current = null;
22342 }
22343 }
22344} // User-originating errors (lifecycles and refs) should not interrupt
22345// deletion, so don't let them throw. Host-originating errors should
22346// interrupt deletion, so it's okay
22347
22348
22349function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) {
22350 onCommitUnmount(current$$1);
22351
22352 switch (current$$1.tag) {
22353 case FunctionComponent:
22354 case ForwardRef:
22355 case MemoComponent:
22356 case SimpleMemoComponent:
22357 {
22358 var updateQueue = current$$1.updateQueue;
22359
22360 if (updateQueue !== null) {
22361 var lastEffect = updateQueue.lastEffect;
22362
22363 if (lastEffect !== null) {
22364 var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive
22365 // effect hook is called during the synchronous commit phase. This is
22366 // a concession to implementation complexity. Calling it in the
22367 // passive effect phase (like they usually are, when dependencies
22368 // change during an update) would require either traversing the
22369 // children of the deleted fiber again, or including unmount effects
22370 // as part of the fiber effect list.
22371 //
22372 // Because this is during the sync commit phase, we need to change
22373 // the priority.
22374 //
22375 // TODO: Reconsider this implementation trade off.
22376
22377 var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
22378 runWithPriority$2(priorityLevel, function () {
22379 var effect = firstEffect;
22380
22381 do {
22382 var destroy = effect.destroy;
22383
22384 if (destroy !== undefined) {
22385 safelyCallDestroy(current$$1, destroy);
22386 }
22387
22388 effect = effect.next;
22389 } while (effect !== firstEffect);
22390 });
22391 }
22392 }
22393
22394 break;
22395 }
22396
22397 case ClassComponent:
22398 {
22399 safelyDetachRef(current$$1);
22400 var instance = current$$1.stateNode;
22401
22402 if (typeof instance.componentWillUnmount === 'function') {
22403 safelyCallComponentWillUnmount(current$$1, instance);
22404 }
22405
22406 return;
22407 }
22408
22409 case HostComponent:
22410 {
22411 if (enableFlareAPI) {
22412 var dependencies = current$$1.dependencies;
22413
22414 if (dependencies !== null) {
22415 var respondersMap = dependencies.responders;
22416
22417 if (respondersMap !== null) {
22418 var responderInstances = Array.from(respondersMap.values());
22419
22420 for (var i = 0, length = responderInstances.length; i < length; i++) {
22421 var responderInstance = responderInstances[i];
22422 unmountResponderInstance(responderInstance);
22423 }
22424
22425 dependencies.responders = null;
22426 }
22427 }
22428 }
22429
22430 safelyDetachRef(current$$1);
22431 return;
22432 }
22433
22434 case HostPortal:
22435 {
22436 // TODO: this is recursive.
22437 // We are also not using this parent because
22438 // the portal will get pushed immediately.
22439 if (supportsMutation) {
22440 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22441 } else if (supportsPersistence) {
22442 emptyPortalContainer(current$$1);
22443 }
22444
22445 return;
22446 }
22447
22448 case FundamentalComponent:
22449 {
22450 if (enableFundamentalAPI) {
22451 var fundamentalInstance = current$$1.stateNode;
22452
22453 if (fundamentalInstance !== null) {
22454 unmountFundamentalComponent(fundamentalInstance);
22455 current$$1.stateNode = null;
22456 }
22457 }
22458
22459 return;
22460 }
22461
22462 case DehydratedFragment:
22463 {
22464 if (enableSuspenseCallback) {
22465 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22466
22467 if (hydrationCallbacks !== null) {
22468 var onDeleted = hydrationCallbacks.onDeleted;
22469
22470 if (onDeleted) {
22471 onDeleted(current$$1.stateNode);
22472 }
22473 }
22474 }
22475
22476 return;
22477 }
22478
22479 case ScopeComponent:
22480 {
22481 if (enableScopeAPI) {
22482 safelyDetachRef(current$$1);
22483 }
22484 }
22485 }
22486}
22487
22488function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
22489 // While we're inside a removed host node we don't want to call
22490 // removeChild on the inner nodes because they're removed by the top
22491 // call anyway. We also want to call componentWillUnmount on all
22492 // composites before this host node is removed from the tree. Therefore
22493 // we do an inner loop while we're still inside the host node.
22494 var node = root;
22495
22496 while (true) {
22497 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
22498 // Skip portals because commitUnmount() currently visits them recursively.
22499
22500 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
22501 // If we don't use mutation we drill down into portals here instead.
22502 !supportsMutation || node.tag !== HostPortal)) {
22503 node.child.return = node;
22504 node = node.child;
22505 continue;
22506 }
22507
22508 if (node === root) {
22509 return;
22510 }
22511
22512 while (node.sibling === null) {
22513 if (node.return === null || node.return === root) {
22514 return;
22515 }
22516
22517 node = node.return;
22518 }
22519
22520 node.sibling.return = node.return;
22521 node = node.sibling;
22522 }
22523}
22524
22525function detachFiber(current$$1) {
22526 var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
22527 // should clear the child pointer of the parent alternate to let this
22528 // get GC:ed but we don't know which for sure which parent is the current
22529 // one so we'll settle for GC:ing the subtree of this child. This child
22530 // itself will be GC:ed when the parent updates the next time.
22531
22532 current$$1.return = null;
22533 current$$1.child = null;
22534 current$$1.memoizedState = null;
22535 current$$1.updateQueue = null;
22536 current$$1.dependencies = null;
22537 current$$1.alternate = null;
22538 current$$1.firstEffect = null;
22539 current$$1.lastEffect = null;
22540 current$$1.pendingProps = null;
22541 current$$1.memoizedProps = null;
22542
22543 if (alternate !== null) {
22544 detachFiber(alternate);
22545 }
22546}
22547
22548function emptyPortalContainer(current$$1) {
22549 if (!supportsPersistence) {
22550 return;
22551 }
22552
22553 var portal = current$$1.stateNode;
22554 var containerInfo = portal.containerInfo;
22555 var emptyChildSet = createContainerChildSet(containerInfo);
22556 replaceContainerChildren(containerInfo, emptyChildSet);
22557}
22558
22559function commitContainer(finishedWork) {
22560 if (!supportsPersistence) {
22561 return;
22562 }
22563
22564 switch (finishedWork.tag) {
22565 case ClassComponent:
22566 case HostComponent:
22567 case HostText:
22568 case FundamentalComponent:
22569 {
22570 return;
22571 }
22572
22573 case HostRoot:
22574 case HostPortal:
22575 {
22576 var portalOrRoot = finishedWork.stateNode;
22577 var containerInfo = portalOrRoot.containerInfo,
22578 pendingChildren = portalOrRoot.pendingChildren;
22579 replaceContainerChildren(containerInfo, pendingChildren);
22580 return;
22581 }
22582
22583 default:
22584 {
22585 (function () {
22586 {
22587 {
22588 throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
22589 }
22590 }
22591 })();
22592 }
22593 }
22594}
22595
22596function getHostParentFiber(fiber) {
22597 var parent = fiber.return;
22598
22599 while (parent !== null) {
22600 if (isHostParent(parent)) {
22601 return parent;
22602 }
22603
22604 parent = parent.return;
22605 }
22606
22607 (function () {
22608 {
22609 {
22610 throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22611 }
22612 }
22613 })();
22614}
22615
22616function isHostParent(fiber) {
22617 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
22618}
22619
22620function getHostSibling(fiber) {
22621 // We're going to search forward into the tree until we find a sibling host
22622 // node. Unfortunately, if multiple insertions are done in a row we have to
22623 // search past them. This leads to exponential search for the next sibling.
22624 // TODO: Find a more efficient way to do this.
22625 var node = fiber;
22626
22627 siblings: while (true) {
22628 // If we didn't find anything, let's try the next sibling.
22629 while (node.sibling === null) {
22630 if (node.return === null || isHostParent(node.return)) {
22631 // If we pop out of the root or hit the parent the fiber we are the
22632 // last sibling.
22633 return null;
22634 }
22635
22636 node = node.return;
22637 }
22638
22639 node.sibling.return = node.return;
22640 node = node.sibling;
22641
22642 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
22643 // If it is not host node and, we might have a host node inside it.
22644 // Try to search down until we find one.
22645 if (node.effectTag & Placement) {
22646 // If we don't have a child, try the siblings instead.
22647 continue siblings;
22648 } // If we don't have a child, try the siblings instead.
22649 // We also skip portals because they are not part of this host tree.
22650
22651
22652 if (node.child === null || node.tag === HostPortal) {
22653 continue siblings;
22654 } else {
22655 node.child.return = node;
22656 node = node.child;
22657 }
22658 } // Check if this host node is stable or about to be placed.
22659
22660
22661 if (!(node.effectTag & Placement)) {
22662 // Found it!
22663 return node.stateNode;
22664 }
22665 }
22666}
22667
22668function commitPlacement(finishedWork) {
22669 if (!supportsMutation) {
22670 return;
22671 } // Recursively insert all host nodes into the parent.
22672
22673
22674 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
22675
22676 var parent;
22677 var isContainer;
22678 var parentStateNode = parentFiber.stateNode;
22679
22680 switch (parentFiber.tag) {
22681 case HostComponent:
22682 parent = parentStateNode;
22683 isContainer = false;
22684 break;
22685
22686 case HostRoot:
22687 parent = parentStateNode.containerInfo;
22688 isContainer = true;
22689 break;
22690
22691 case HostPortal:
22692 parent = parentStateNode.containerInfo;
22693 isContainer = true;
22694 break;
22695
22696 case FundamentalComponent:
22697 if (enableFundamentalAPI) {
22698 parent = parentStateNode.instance;
22699 isContainer = false;
22700 }
22701
22702 // eslint-disable-next-line-no-fallthrough
22703
22704 default:
22705 (function () {
22706 {
22707 {
22708 throw ReactError(Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."));
22709 }
22710 }
22711 })();
22712
22713 }
22714
22715 if (parentFiber.effectTag & ContentReset) {
22716 // Reset the text content of the parent before doing any insertions
22717 resetTextContent(parent); // Clear ContentReset from the effect tag
22718
22719 parentFiber.effectTag &= ~ContentReset;
22720 }
22721
22722 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
22723 // children to find all the terminal nodes.
22724
22725 var node = finishedWork;
22726
22727 while (true) {
22728 var isHost = node.tag === HostComponent || node.tag === HostText;
22729
22730 if (isHost || enableFundamentalAPI && node.tag === FundamentalComponent) {
22731 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
22732
22733 if (before) {
22734 if (isContainer) {
22735 insertInContainerBefore(parent, stateNode, before);
22736 } else {
22737 insertBefore(parent, stateNode, before);
22738 }
22739 } else {
22740 if (isContainer) {
22741 appendChildToContainer(parent, stateNode);
22742 } else {
22743 appendChild(parent, stateNode);
22744 }
22745 }
22746 } else if (node.tag === HostPortal) {// If the insertion itself is a portal, then we don't want to traverse
22747 // down its children. Instead, we'll get insertions from each child in
22748 // the portal directly.
22749 } else if (node.child !== null) {
22750 node.child.return = node;
22751 node = node.child;
22752 continue;
22753 }
22754
22755 if (node === finishedWork) {
22756 return;
22757 }
22758
22759 while (node.sibling === null) {
22760 if (node.return === null || node.return === finishedWork) {
22761 return;
22762 }
22763
22764 node = node.return;
22765 }
22766
22767 node.sibling.return = node.return;
22768 node = node.sibling;
22769 }
22770}
22771
22772function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) {
22773 // We only have the top Fiber that was deleted but we need to recurse down its
22774 // children to find all the terminal nodes.
22775 var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not
22776 // currentParentIsValid.
22777
22778 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
22779
22780 var currentParent;
22781 var currentParentIsContainer;
22782
22783 while (true) {
22784 if (!currentParentIsValid) {
22785 var parent = node.return;
22786
22787 findParent: while (true) {
22788 (function () {
22789 if (!(parent !== null)) {
22790 {
22791 throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22792 }
22793 }
22794 })();
22795
22796 var parentStateNode = parent.stateNode;
22797
22798 switch (parent.tag) {
22799 case HostComponent:
22800 currentParent = parentStateNode;
22801 currentParentIsContainer = false;
22802 break findParent;
22803
22804 case HostRoot:
22805 currentParent = parentStateNode.containerInfo;
22806 currentParentIsContainer = true;
22807 break findParent;
22808
22809 case HostPortal:
22810 currentParent = parentStateNode.containerInfo;
22811 currentParentIsContainer = true;
22812 break findParent;
22813
22814 case FundamentalComponent:
22815 if (enableFundamentalAPI) {
22816 currentParent = parentStateNode.instance;
22817 currentParentIsContainer = false;
22818 }
22819
22820 }
22821
22822 parent = parent.return;
22823 }
22824
22825 currentParentIsValid = true;
22826 }
22827
22828 if (node.tag === HostComponent || node.tag === HostText) {
22829 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22830 // node from the tree.
22831
22832 if (currentParentIsContainer) {
22833 removeChildFromContainer(currentParent, node.stateNode);
22834 } else {
22835 removeChild(currentParent, node.stateNode);
22836 } // Don't visit children because we already visited them.
22837
22838 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
22839 var fundamentalNode = node.stateNode.instance;
22840 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22841 // node from the tree.
22842
22843 if (currentParentIsContainer) {
22844 removeChildFromContainer(currentParent, fundamentalNode);
22845 } else {
22846 removeChild(currentParent, fundamentalNode);
22847 }
22848 } else if (enableSuspenseServerRenderer && node.tag === DehydratedFragment) {
22849 if (enableSuspenseCallback) {
22850 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22851
22852 if (hydrationCallbacks !== null) {
22853 var onDeleted = hydrationCallbacks.onDeleted;
22854
22855 if (onDeleted) {
22856 onDeleted(node.stateNode);
22857 }
22858 }
22859 } // Delete the dehydrated suspense boundary and all of its content.
22860
22861
22862 if (currentParentIsContainer) {
22863 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
22864 } else {
22865 clearSuspenseBoundary(currentParent, node.stateNode);
22866 }
22867 } else if (node.tag === HostPortal) {
22868 if (node.child !== null) {
22869 // When we go into a portal, it becomes the parent to remove from.
22870 // We will reassign it back when we pop the portal on the way up.
22871 currentParent = node.stateNode.containerInfo;
22872 currentParentIsContainer = true; // Visit children because portals might contain host components.
22873
22874 node.child.return = node;
22875 node = node.child;
22876 continue;
22877 }
22878 } else {
22879 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
22880
22881 if (node.child !== null) {
22882 node.child.return = node;
22883 node = node.child;
22884 continue;
22885 }
22886 }
22887
22888 if (node === current$$1) {
22889 return;
22890 }
22891
22892 while (node.sibling === null) {
22893 if (node.return === null || node.return === current$$1) {
22894 return;
22895 }
22896
22897 node = node.return;
22898
22899 if (node.tag === HostPortal) {
22900 // When we go out of the portal, we need to restore the parent.
22901 // Since we don't keep a stack of them, we will search for it.
22902 currentParentIsValid = false;
22903 }
22904 }
22905
22906 node.sibling.return = node.return;
22907 node = node.sibling;
22908 }
22909}
22910
22911function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) {
22912 if (supportsMutation) {
22913 // Recursively delete all host nodes from the parent.
22914 // Detach refs and call componentWillUnmount() on the whole subtree.
22915 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22916 } else {
22917 // Detach refs and call componentWillUnmount() on the whole subtree.
22918 commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel);
22919 }
22920
22921 detachFiber(current$$1);
22922}
22923
22924function commitWork(current$$1, finishedWork) {
22925 if (!supportsMutation) {
22926 switch (finishedWork.tag) {
22927 case FunctionComponent:
22928 case ForwardRef:
22929 case MemoComponent:
22930 case SimpleMemoComponent:
22931 {
22932 // Note: We currently never use MountMutation, but useLayout uses
22933 // UnmountMutation.
22934 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22935 return;
22936 }
22937
22938 case Profiler:
22939 {
22940 return;
22941 }
22942
22943 case SuspenseComponent:
22944 {
22945 commitSuspenseComponent(finishedWork);
22946 attachSuspenseRetryListeners(finishedWork);
22947 return;
22948 }
22949
22950 case SuspenseListComponent:
22951 {
22952 attachSuspenseRetryListeners(finishedWork);
22953 return;
22954 }
22955
22956 case HostRoot:
22957 {
22958 if (supportsHydration) {
22959 var root = finishedWork.stateNode;
22960
22961 if (root.hydrate) {
22962 // We've just hydrated. No need to hydrate again.
22963 root.hydrate = false;
22964 commitHydratedContainer(root.containerInfo);
22965 }
22966 }
22967
22968 break;
22969 }
22970 }
22971
22972 commitContainer(finishedWork);
22973 return;
22974 }
22975
22976 switch (finishedWork.tag) {
22977 case FunctionComponent:
22978 case ForwardRef:
22979 case MemoComponent:
22980 case SimpleMemoComponent:
22981 {
22982 // Note: We currently never use MountMutation, but useLayout uses
22983 // UnmountMutation.
22984 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22985 return;
22986 }
22987
22988 case ClassComponent:
22989 {
22990 return;
22991 }
22992
22993 case HostComponent:
22994 {
22995 var instance = finishedWork.stateNode;
22996
22997 if (instance != null) {
22998 // Commit the work prepared earlier.
22999 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23000 // as the newProps. The updatePayload will contain the real change in
23001 // this case.
23002
23003 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
23004 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
23005
23006 var updatePayload = finishedWork.updateQueue;
23007 finishedWork.updateQueue = null;
23008
23009 if (updatePayload !== null) {
23010 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
23011 }
23012
23013 if (enableFlareAPI) {
23014 var prevListeners = oldProps.listeners;
23015 var nextListeners = newProps.listeners;
23016
23017 if (prevListeners !== nextListeners) {
23018 updateEventListeners(nextListeners, finishedWork, null);
23019 }
23020 }
23021 }
23022
23023 return;
23024 }
23025
23026 case HostText:
23027 {
23028 (function () {
23029 if (!(finishedWork.stateNode !== null)) {
23030 {
23031 throw ReactError(Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."));
23032 }
23033 }
23034 })();
23035
23036 var textInstance = finishedWork.stateNode;
23037 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23038 // as the newProps. The updatePayload will contain the real change in
23039 // this case.
23040
23041 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
23042 commitTextUpdate(textInstance, oldText, newText);
23043 return;
23044 }
23045
23046 case HostRoot:
23047 {
23048 if (supportsHydration) {
23049 var _root = finishedWork.stateNode;
23050
23051 if (_root.hydrate) {
23052 // We've just hydrated. No need to hydrate again.
23053 _root.hydrate = false;
23054 commitHydratedContainer(_root.containerInfo);
23055 }
23056 }
23057
23058 return;
23059 }
23060
23061 case Profiler:
23062 {
23063 return;
23064 }
23065
23066 case SuspenseComponent:
23067 {
23068 commitSuspenseComponent(finishedWork);
23069 attachSuspenseRetryListeners(finishedWork);
23070 return;
23071 }
23072
23073 case SuspenseListComponent:
23074 {
23075 attachSuspenseRetryListeners(finishedWork);
23076 return;
23077 }
23078
23079 case IncompleteClassComponent:
23080 {
23081 return;
23082 }
23083
23084 case FundamentalComponent:
23085 {
23086 if (enableFundamentalAPI) {
23087 var fundamentalInstance = finishedWork.stateNode;
23088 updateFundamentalComponent(fundamentalInstance);
23089 }
23090
23091 return;
23092 }
23093
23094 case ScopeComponent:
23095 {
23096 if (enableScopeAPI) {
23097 var scopeInstance = finishedWork.stateNode;
23098 scopeInstance.fiber = finishedWork;
23099
23100 if (enableFlareAPI) {
23101 var _newProps = finishedWork.memoizedProps;
23102
23103 var _oldProps = current$$1 !== null ? current$$1.memoizedProps : _newProps;
23104
23105 var _prevListeners = _oldProps.listeners;
23106 var _nextListeners = _newProps.listeners;
23107
23108 if (_prevListeners !== _nextListeners) {
23109 updateEventListeners(_nextListeners, finishedWork, null);
23110 }
23111 }
23112 }
23113
23114 return;
23115 }
23116
23117 default:
23118 {
23119 (function () {
23120 {
23121 {
23122 throw ReactError(Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."));
23123 }
23124 }
23125 })();
23126 }
23127 }
23128}
23129
23130function commitSuspenseComponent(finishedWork) {
23131 var newState = finishedWork.memoizedState;
23132 var newDidTimeout;
23133 var primaryChildParent = finishedWork;
23134
23135 if (newState === null) {
23136 newDidTimeout = false;
23137 } else {
23138 newDidTimeout = true;
23139 primaryChildParent = finishedWork.child;
23140 markCommitTimeOfFallback();
23141 }
23142
23143 if (supportsMutation && primaryChildParent !== null) {
23144 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
23145 }
23146
23147 if (enableSuspenseCallback && newState !== null) {
23148 var suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
23149
23150 if (typeof suspenseCallback === 'function') {
23151 var thenables = finishedWork.updateQueue;
23152
23153 if (thenables !== null) {
23154 suspenseCallback(new Set(thenables));
23155 }
23156 } else {
23157 if (suspenseCallback !== undefined) {
23158 warning$1(false, 'Unexpected type for suspenseCallback.');
23159 }
23160 }
23161 }
23162}
23163
23164function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
23165 if (!supportsHydration) {
23166 return;
23167 }
23168
23169 var newState = finishedWork.memoizedState;
23170
23171 if (newState === null) {
23172 var current$$1 = finishedWork.alternate;
23173
23174 if (current$$1 !== null) {
23175 var prevState = current$$1.memoizedState;
23176
23177 if (prevState !== null) {
23178 var suspenseInstance = prevState.dehydrated;
23179
23180 if (suspenseInstance !== null) {
23181 commitHydratedSuspenseInstance(suspenseInstance);
23182
23183 if (enableSuspenseCallback) {
23184 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
23185
23186 if (hydrationCallbacks !== null) {
23187 var onHydrated = hydrationCallbacks.onHydrated;
23188
23189 if (onHydrated) {
23190 onHydrated(suspenseInstance);
23191 }
23192 }
23193 }
23194 }
23195 }
23196 }
23197 }
23198}
23199
23200function attachSuspenseRetryListeners(finishedWork) {
23201 // If this boundary just timed out, then it will have a set of thenables.
23202 // For each thenable, attach a listener so that when it resolves, React
23203 // attempts to re-render the boundary in the primary (pre-timeout) state.
23204 var thenables = finishedWork.updateQueue;
23205
23206 if (thenables !== null) {
23207 finishedWork.updateQueue = null;
23208 var retryCache = finishedWork.stateNode;
23209
23210 if (retryCache === null) {
23211 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
23212 }
23213
23214 thenables.forEach(function (thenable) {
23215 // Memoize using the boundary fiber to prevent redundant listeners.
23216 var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
23217
23218 if (!retryCache.has(thenable)) {
23219 if (enableSchedulerTracing) {
23220 if (thenable.__reactDoNotTraceInteractions !== true) {
23221 retry = unstable_wrap(retry);
23222 }
23223 }
23224
23225 retryCache.add(thenable);
23226 thenable.then(retry, retry);
23227 }
23228 });
23229 }
23230}
23231
23232function commitResetTextContent(current$$1) {
23233 if (!supportsMutation) {
23234 return;
23235 }
23236
23237 resetTextContent(current$$1.stateNode);
23238}
23239
23240var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
23241
23242function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
23243 var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
23244
23245 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
23246 // being called "element".
23247
23248 update.payload = {
23249 element: null
23250 };
23251 var error = errorInfo.value;
23252
23253 update.callback = function () {
23254 onUncaughtError(error);
23255 logError(fiber, errorInfo);
23256 };
23257
23258 return update;
23259}
23260
23261function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
23262 var update = createUpdate(expirationTime, null);
23263 update.tag = CaptureUpdate;
23264 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
23265
23266 if (typeof getDerivedStateFromError === 'function') {
23267 var error = errorInfo.value;
23268
23269 update.payload = function () {
23270 logError(fiber, errorInfo);
23271 return getDerivedStateFromError(error);
23272 };
23273 }
23274
23275 var inst = fiber.stateNode;
23276
23277 if (inst !== null && typeof inst.componentDidCatch === 'function') {
23278 update.callback = function callback() {
23279 {
23280 markFailedErrorBoundaryForHotReloading(fiber);
23281 }
23282
23283 if (typeof getDerivedStateFromError !== 'function') {
23284 // To preserve the preexisting retry behavior of error boundaries,
23285 // we keep track of which ones already failed during this batch.
23286 // This gets reset before we yield back to the browser.
23287 // TODO: Warn in strict mode if getDerivedStateFromError is
23288 // not defined.
23289 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
23290
23291 logError(fiber, errorInfo);
23292 }
23293
23294 var error = errorInfo.value;
23295 var stack = errorInfo.stack;
23296 this.componentDidCatch(error, {
23297 componentStack: stack !== null ? stack : ''
23298 });
23299
23300 {
23301 if (typeof getDerivedStateFromError !== 'function') {
23302 // If componentDidCatch is the only error boundary method defined,
23303 // then it needs to call setState to recover from errors.
23304 // If no state update is scheduled then the boundary will swallow the error.
23305 !(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;
23306 }
23307 }
23308 };
23309 } else {
23310 update.callback = function () {
23311 markFailedErrorBoundaryForHotReloading(fiber);
23312 };
23313 }
23314
23315 return update;
23316}
23317
23318function attachPingListener(root, renderExpirationTime, thenable) {
23319 // Attach a listener to the promise to "ping" the root and retry. But
23320 // only if one does not already exist for the current render expiration
23321 // time (which acts like a "thread ID" here).
23322 var pingCache = root.pingCache;
23323 var threadIDs;
23324
23325 if (pingCache === null) {
23326 pingCache = root.pingCache = new PossiblyWeakMap$1();
23327 threadIDs = new Set();
23328 pingCache.set(thenable, threadIDs);
23329 } else {
23330 threadIDs = pingCache.get(thenable);
23331
23332 if (threadIDs === undefined) {
23333 threadIDs = new Set();
23334 pingCache.set(thenable, threadIDs);
23335 }
23336 }
23337
23338 if (!threadIDs.has(renderExpirationTime)) {
23339 // Memoize using the thread ID to prevent redundant listeners.
23340 threadIDs.add(renderExpirationTime);
23341 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
23342 thenable.then(ping, ping);
23343 }
23344}
23345
23346function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
23347 // The source fiber did not complete.
23348 sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
23349
23350 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
23351
23352 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
23353 // This is a thenable.
23354 var thenable = value;
23355 checkForWrongSuspensePriorityInDEV(sourceFiber);
23356 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
23357
23358 var _workInProgress = returnFiber;
23359
23360 do {
23361 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
23362 // Found the nearest boundary.
23363 // Stash the promise on the boundary fiber. If the boundary times out, we'll
23364 // attach another listener to flip the boundary back to its normal state.
23365 var thenables = _workInProgress.updateQueue;
23366
23367 if (thenables === null) {
23368 var updateQueue = new Set();
23369 updateQueue.add(thenable);
23370 _workInProgress.updateQueue = updateQueue;
23371 } else {
23372 thenables.add(thenable);
23373 } // If the boundary is outside of batched mode, we should *not*
23374 // suspend the commit. Pretend as if the suspended component rendered
23375 // null and keep rendering. In the commit phase, we'll schedule a
23376 // subsequent synchronous update to re-render the Suspense.
23377 //
23378 // Note: It doesn't matter whether the component that suspended was
23379 // inside a batched mode tree. If the Suspense is outside of it, we
23380 // should *not* suspend the commit.
23381
23382
23383 if ((_workInProgress.mode & BatchedMode) === NoMode) {
23384 _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
23385 // But we shouldn't call any lifecycle methods or callbacks. Remove
23386 // all lifecycle effect tags.
23387
23388 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
23389
23390 if (sourceFiber.tag === ClassComponent) {
23391 var currentSourceFiber = sourceFiber.alternate;
23392
23393 if (currentSourceFiber === null) {
23394 // This is a new mount. Change the tag so it's not mistaken for a
23395 // completed class component. For example, we should not call
23396 // componentWillUnmount if it is deleted.
23397 sourceFiber.tag = IncompleteClassComponent;
23398 } else {
23399 // When we try rendering again, we should not reuse the current fiber,
23400 // since it's known to be in an inconsistent state. Use a force update to
23401 // prevent a bail out.
23402 var update = createUpdate(Sync, null);
23403 update.tag = ForceUpdate;
23404 enqueueUpdate(sourceFiber, update);
23405 }
23406 } // The source fiber did not complete. Mark it with Sync priority to
23407 // indicate that it still has pending work.
23408
23409
23410 sourceFiber.expirationTime = Sync; // Exit without suspending.
23411
23412 return;
23413 } // Confirmed that the boundary is in a concurrent mode tree. Continue
23414 // with the normal suspend path.
23415 //
23416 // After this we'll use a set of heuristics to determine whether this
23417 // render pass will run to completion or restart or "suspend" the commit.
23418 // The actual logic for this is spread out in different places.
23419 //
23420 // This first principle is that if we're going to suspend when we complete
23421 // a root, then we should also restart if we get an update or ping that
23422 // might unsuspend it, and vice versa. The only reason to suspend is
23423 // because you think you might want to restart before committing. However,
23424 // it doesn't make sense to restart only while in the period we're suspended.
23425 //
23426 // Restarting too aggressively is also not good because it starves out any
23427 // intermediate loading state. So we use heuristics to determine when.
23428 // Suspense Heuristics
23429 //
23430 // If nothing threw a Promise or all the same fallbacks are already showing,
23431 // then don't suspend/restart.
23432 //
23433 // If this is an initial render of a new tree of Suspense boundaries and
23434 // those trigger a fallback, then don't suspend/restart. We want to ensure
23435 // that we can show the initial loading state as quickly as possible.
23436 //
23437 // If we hit a "Delayed" case, such as when we'd switch from content back into
23438 // a fallback, then we should always suspend/restart. SuspenseConfig applies to
23439 // this case. If none is defined, JND is used instead.
23440 //
23441 // If we're already showing a fallback and it gets "retried", allowing us to show
23442 // another level, but there's still an inner boundary that would show a fallback,
23443 // then we suspend/restart for 500ms since the last time we showed a fallback
23444 // anywhere in the tree. This effectively throttles progressive loading into a
23445 // consistent train of commits. This also gives us an opportunity to restart to
23446 // get to the completed state slightly earlier.
23447 //
23448 // If there's ambiguity due to batching it's resolved in preference of:
23449 // 1) "delayed", 2) "initial render", 3) "retry".
23450 //
23451 // We want to ensure that a "busy" state doesn't get force committed. We want to
23452 // ensure that new initial loading states can commit as soon as possible.
23453
23454
23455 attachPingListener(root, renderExpirationTime, thenable);
23456 _workInProgress.effectTag |= ShouldCapture;
23457 _workInProgress.expirationTime = renderExpirationTime;
23458 return;
23459 } // This boundary already captured during this render. Continue to the next
23460 // boundary.
23461
23462
23463 _workInProgress = _workInProgress.return;
23464 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
23465 // TODO: Use invariant so the message is stripped in prod?
23466
23467
23468 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));
23469 } // We didn't find a boundary that could handle this type of exception. Start
23470 // over and traverse parent path again, this time treating the exception
23471 // as an error.
23472
23473
23474 renderDidError();
23475 value = createCapturedValue(value, sourceFiber);
23476 var workInProgress = returnFiber;
23477
23478 do {
23479 switch (workInProgress.tag) {
23480 case HostRoot:
23481 {
23482 var _errorInfo = value;
23483 workInProgress.effectTag |= ShouldCapture;
23484 workInProgress.expirationTime = renderExpirationTime;
23485
23486 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
23487
23488 enqueueCapturedUpdate(workInProgress, _update);
23489 return;
23490 }
23491
23492 case ClassComponent:
23493 // Capture and retry
23494 var errorInfo = value;
23495 var ctor = workInProgress.type;
23496 var instance = workInProgress.stateNode;
23497
23498 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
23499 workInProgress.effectTag |= ShouldCapture;
23500 workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
23501
23502 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
23503
23504 enqueueCapturedUpdate(workInProgress, _update2);
23505 return;
23506 }
23507
23508 break;
23509
23510 default:
23511 break;
23512 }
23513
23514 workInProgress = workInProgress.return;
23515 } while (workInProgress !== null);
23516}
23517
23518var ceil = Math.ceil;
23519var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
23520var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
23521var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
23522var NoContext =
23523/* */
235240;
23525var BatchedContext =
23526/* */
235271;
23528var EventContext =
23529/* */
235302;
23531var DiscreteEventContext =
23532/* */
235334;
23534var LegacyUnbatchedContext =
23535/* */
235368;
23537var RenderContext =
23538/* */
2353916;
23540var CommitContext =
23541/* */
2354232;
23543var RootIncomplete = 0;
23544var RootFatalErrored = 1;
23545var RootErrored = 2;
23546var RootSuspended = 3;
23547var RootSuspendedWithDelay = 4;
23548var RootCompleted = 5;
23549var RootLocked = 6;
23550// Describes where we are in the React execution stack
23551var executionContext = NoContext; // The root we're working on
23552
23553var workInProgressRoot = null; // The fiber we're working on
23554
23555var workInProgress = null; // The expiration time we're rendering
23556
23557var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc.
23558
23559var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
23560
23561var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
23562// This is conceptually a time stamp but expressed in terms of an ExpirationTime
23563// because we deal mostly with expiration times in the hot path, so this avoids
23564// the conversion happening in the hot path.
23565
23566var workInProgressRootLatestProcessedExpirationTime = Sync;
23567var workInProgressRootLatestSuspenseTimeout = Sync;
23568var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
23569// includes unprocessed updates, not work in bailed out children.
23570
23571var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
23572// This flag determines if it might be worthwhile to restart if an opportunity
23573// happens latere.
23574
23575var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
23576// model where we don't commit new loading states in too quick succession.
23577
23578var globalMostRecentFallbackTime = 0;
23579var FALLBACK_THROTTLE_MS = 500;
23580var nextEffect = null;
23581var hasUncaughtError = false;
23582var firstUncaughtError = null;
23583var legacyErrorBoundariesThatAlreadyFailed = null;
23584var rootDoesHavePassiveEffects = false;
23585var rootWithPendingPassiveEffects = null;
23586var pendingPassiveEffectsRenderPriority = NoPriority;
23587var pendingPassiveEffectsExpirationTime = NoWork;
23588var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
23589
23590var NESTED_UPDATE_LIMIT = 50;
23591var nestedUpdateCount = 0;
23592var rootWithNestedUpdates = null;
23593var NESTED_PASSIVE_UPDATE_LIMIT = 50;
23594var nestedPassiveUpdateCount = 0;
23595var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
23596// during the commit phase. This enables them to be traced across components
23597// that spawn new work during render. E.g. hidden boundaries, suspended SSR
23598// hydration or SuspenseList.
23599
23600var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
23601// time). However, if two updates are scheduled within the same event, we
23602// should treat their start times as simultaneous, even if the actual clock
23603// time has advanced between the first and second call.
23604// In other words, because expiration times determine how updates are batched,
23605// we want all updates of like priority that occur within the same event to
23606// receive the same expiration time. Otherwise we get tearing.
23607
23608var currentEventTime = NoWork;
23609function requestCurrentTime() {
23610 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
23611 // We're inside React, so it's fine to read the actual time.
23612 return msToExpirationTime(now());
23613 } // We're not inside React, so we may be in the middle of a browser event.
23614
23615
23616 if (currentEventTime !== NoWork) {
23617 // Use the same start time for all updates until we enter React again.
23618 return currentEventTime;
23619 } // This is the first update since React yielded. Compute a new start time.
23620
23621
23622 currentEventTime = msToExpirationTime(now());
23623 return currentEventTime;
23624}
23625function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
23626 var mode = fiber.mode;
23627
23628 if ((mode & BatchedMode) === NoMode) {
23629 return Sync;
23630 }
23631
23632 var priorityLevel = getCurrentPriorityLevel();
23633
23634 if ((mode & ConcurrentMode) === NoMode) {
23635 return priorityLevel === ImmediatePriority ? Sync : Batched;
23636 }
23637
23638 if ((executionContext & RenderContext) !== NoContext) {
23639 // Use whatever time we're already rendering
23640 // TODO: Should there be a way to opt out, like with `runWithPriority`?
23641 return renderExpirationTime;
23642 }
23643
23644 var expirationTime;
23645
23646 if (suspenseConfig !== null) {
23647 // Compute an expiration time based on the Suspense timeout.
23648 expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
23649 } else {
23650 // Compute an expiration time based on the Scheduler priority.
23651 switch (priorityLevel) {
23652 case ImmediatePriority:
23653 expirationTime = Sync;
23654 break;
23655
23656 case UserBlockingPriority$2:
23657 // TODO: Rename this to computeUserBlockingExpiration
23658 expirationTime = computeInteractiveExpiration(currentTime);
23659 break;
23660
23661 case NormalPriority:
23662 case LowPriority:
23663 // TODO: Handle LowPriority
23664 // TODO: Rename this to... something better.
23665 expirationTime = computeAsyncExpiration(currentTime);
23666 break;
23667
23668 case IdlePriority:
23669 expirationTime = Idle;
23670 break;
23671
23672 default:
23673 (function () {
23674 {
23675 {
23676 throw ReactError(Error("Expected a valid priority level"));
23677 }
23678 }
23679 })();
23680
23681 }
23682 } // If we're in the middle of rendering a tree, do not update at the same
23683 // expiration time that is already rendering.
23684 // TODO: We shouldn't have to do this if the update is on a different root.
23685 // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
23686 // the root when we check for this condition.
23687
23688
23689 if (workInProgressRoot !== null && expirationTime === renderExpirationTime) {
23690 // This is a trick to move this update into a separate batch
23691 expirationTime -= 1;
23692 }
23693
23694 return expirationTime;
23695}
23696var lastUniqueAsyncExpiration = NoWork;
23697function computeUniqueAsyncExpiration() {
23698 var currentTime = requestCurrentTime();
23699 var result = computeAsyncExpiration(currentTime);
23700
23701 if (result <= lastUniqueAsyncExpiration) {
23702 // Since we assume the current time monotonically increases, we only hit
23703 // this branch when computeUniqueAsyncExpiration is fired multiple times
23704 // within a 200ms window (or whatever the async bucket size is).
23705 result -= 1;
23706 }
23707
23708 lastUniqueAsyncExpiration = result;
23709 return result;
23710}
23711function scheduleUpdateOnFiber(fiber, expirationTime) {
23712 checkForNestedUpdates();
23713 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
23714 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
23715
23716 if (root === null) {
23717 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
23718 return;
23719 }
23720
23721 checkForInterruption(fiber, expirationTime);
23722 recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
23723 // priority as an argument to that function and this one.
23724
23725 var priorityLevel = getCurrentPriorityLevel();
23726
23727 if (expirationTime === Sync) {
23728 if ( // Check if we're inside unbatchedUpdates
23729 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
23730 (executionContext & (RenderContext | CommitContext)) === NoContext) {
23731 // Register pending interactions on the root to avoid losing traced interaction data.
23732 schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
23733 // root inside of batchedUpdates should be synchronous, but layout updates
23734 // should be deferred until the end of the batch.
23735
23736 performSyncWorkOnRoot(root);
23737 } else {
23738 ensureRootIsScheduled(root);
23739 schedulePendingInteractions(root, expirationTime);
23740
23741 if (executionContext === NoContext) {
23742 // Flush the synchronous work now, unless we're already working or inside
23743 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
23744 // scheduleCallbackForFiber to preserve the ability to schedule a callback
23745 // without immediately flushing it. We only do this for user-initiated
23746 // updates, to preserve historical behavior of sync mode.
23747 flushSyncCallbackQueue();
23748 }
23749 }
23750 } else {
23751 ensureRootIsScheduled(root);
23752 schedulePendingInteractions(root, expirationTime);
23753 }
23754
23755 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
23756 // discrete, even inside a discrete event.
23757 priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority)) {
23758 // This is the result of a discrete event. Track the lowest priority
23759 // discrete update per root so we can flush them early, if needed.
23760 if (rootsWithPendingDiscreteUpdates === null) {
23761 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
23762 } else {
23763 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
23764
23765 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
23766 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
23767 }
23768 }
23769 }
23770}
23771var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
23772// work without treating it as a typical update that originates from an event;
23773// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
23774// on a fiber.
23775
23776function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
23777 // Update the source fiber's expiration time
23778 if (fiber.expirationTime < expirationTime) {
23779 fiber.expirationTime = expirationTime;
23780 }
23781
23782 var alternate = fiber.alternate;
23783
23784 if (alternate !== null && alternate.expirationTime < expirationTime) {
23785 alternate.expirationTime = expirationTime;
23786 } // Walk the parent path to the root and update the child expiration time.
23787
23788
23789 var node = fiber.return;
23790 var root = null;
23791
23792 if (node === null && fiber.tag === HostRoot) {
23793 root = fiber.stateNode;
23794 } else {
23795 while (node !== null) {
23796 alternate = node.alternate;
23797
23798 if (node.childExpirationTime < expirationTime) {
23799 node.childExpirationTime = expirationTime;
23800
23801 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23802 alternate.childExpirationTime = expirationTime;
23803 }
23804 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23805 alternate.childExpirationTime = expirationTime;
23806 }
23807
23808 if (node.return === null && node.tag === HostRoot) {
23809 root = node.stateNode;
23810 break;
23811 }
23812
23813 node = node.return;
23814 }
23815 }
23816
23817 if (root !== null) {
23818 if (workInProgressRoot === root) {
23819 // Received an update to a tree that's in the middle of rendering. Mark
23820 // that's unprocessed work on this root.
23821 markUnprocessedUpdateTime(expirationTime);
23822
23823 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
23824 // The root already suspended with a delay, which means this render
23825 // definitely won't finish. Since we have a new update, let's mark it as
23826 // suspended now, right before marking the incoming update. This has the
23827 // effect of interrupting the current render and switching to the update.
23828 // TODO: This happens to work when receiving an update during the render
23829 // phase, because of the trick inside computeExpirationForFiber to
23830 // subtract 1 from `renderExpirationTime` to move it into a
23831 // separate bucket. But we should probably model it with an exception,
23832 // using the same mechanism we use to force hydration of a subtree.
23833 // TODO: This does not account for low pri updates that were already
23834 // scheduled before the root started rendering. Need to track the next
23835 // pending expiration time (perhaps by backtracking the return path) and
23836 // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
23837 markRootSuspendedAtTime(root, renderExpirationTime);
23838 }
23839 } // Mark that the root has a pending update.
23840
23841
23842 markRootUpdatedAtTime(root, expirationTime);
23843 }
23844
23845 return root;
23846}
23847
23848function getNextRootExpirationTimeToWorkOn(root) {
23849 // Determines the next expiration time that the root should render, taking
23850 // into account levels that may be suspended, or levels that may have
23851 // received a ping.
23852 var lastExpiredTime = root.lastExpiredTime;
23853
23854 if (lastExpiredTime !== NoWork) {
23855 return lastExpiredTime;
23856 } // "Pending" refers to any update that hasn't committed yet, including if it
23857 // suspended. The "suspended" range is therefore a subset.
23858
23859
23860 var firstPendingTime = root.firstPendingTime;
23861
23862 if (!isRootSuspendedAtTime(root, firstPendingTime)) {
23863 // The highest priority pending time is not suspended. Let's work on that.
23864 return firstPendingTime;
23865 } // If the first pending time is suspended, check if there's a lower priority
23866 // pending level that we know about. Or check if we received a ping. Work
23867 // on whichever is higher priority.
23868
23869
23870 var lastPingedTime = root.lastPingedTime;
23871 var nextKnownPendingLevel = root.nextKnownPendingLevel;
23872 return lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
23873} // Use this function to schedule a task for a root. There's only one task per
23874// root; if a task was already scheduled, we'll check to make sure the
23875// expiration time of the existing task is the same as the expiration time of
23876// the next level that the root has work on. This function is called on every
23877// update, and right before exiting a task.
23878
23879
23880function ensureRootIsScheduled(root) {
23881 var lastExpiredTime = root.lastExpiredTime;
23882
23883 if (lastExpiredTime !== NoWork) {
23884 // Special case: Expired work should flush synchronously.
23885 root.callbackExpirationTime = Sync;
23886 root.callbackPriority = ImmediatePriority;
23887 root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23888 return;
23889 }
23890
23891 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23892 var existingCallbackNode = root.callbackNode;
23893
23894 if (expirationTime === NoWork) {
23895 // There's nothing to work on.
23896 if (existingCallbackNode !== null) {
23897 root.callbackNode = null;
23898 root.callbackExpirationTime = NoWork;
23899 root.callbackPriority = NoPriority;
23900 }
23901
23902 return;
23903 } // TODO: If this is an update, we already read the current time. Pass the
23904 // time as an argument.
23905
23906
23907 var currentTime = requestCurrentTime();
23908 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
23909 // expiration time. Otherwise, we'll cancel it and schedule a new one.
23910
23911 if (existingCallbackNode !== null) {
23912 var existingCallbackPriority = root.callbackPriority;
23913 var existingCallbackExpirationTime = root.callbackExpirationTime;
23914
23915 if ( // Callback must have the exact same expiration time.
23916 existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
23917 existingCallbackPriority >= priorityLevel) {
23918 // Existing callback is sufficient.
23919 return;
23920 } // Need to schedule a new task.
23921 // TODO: Instead of scheduling a new task, we should be able to change the
23922 // priority of the existing one.
23923
23924
23925 cancelCallback(existingCallbackNode);
23926 }
23927
23928 root.callbackExpirationTime = expirationTime;
23929 root.callbackPriority = priorityLevel;
23930 var callbackNode;
23931
23932 if (expirationTime === Sync) {
23933 // Sync React callbacks are scheduled on a special internal queue
23934 callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23935 } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) {
23936 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root));
23937 } else {
23938 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
23939 // ordering because tasks are processed in timeout order.
23940 {
23941 timeout: expirationTimeToMs(expirationTime) - now()
23942 });
23943 }
23944
23945 root.callbackNode = callbackNode;
23946} // This is the entry point for every concurrent task, i.e. anything that
23947// goes through Scheduler.
23948
23949
23950function performConcurrentWorkOnRoot(root, didTimeout) {
23951 // Since we know we're in a React event, we can clear the current
23952 // event time. The next update will compute a new event time.
23953 currentEventTime = NoWork;
23954
23955 if (didTimeout) {
23956 // The render task took too long to complete. Mark the current time as
23957 // expired to synchronously render all expired work in a single batch.
23958 var currentTime = requestCurrentTime();
23959 markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
23960
23961 ensureRootIsScheduled(root);
23962 return null;
23963 } // Determine the next expiration time to work on, using the fields stored
23964 // on the root.
23965
23966
23967 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23968
23969 if (expirationTime !== NoWork) {
23970 var originalCallbackNode = root.callbackNode;
23971
23972 (function () {
23973 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
23974 {
23975 throw ReactError(Error("Should not already be working."));
23976 }
23977 }
23978 })();
23979
23980 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
23981 // and prepare a fresh one. Otherwise we'll continue where we left off.
23982
23983 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
23984 prepareFreshStack(root, expirationTime);
23985 startWorkOnPendingInteractions(root, expirationTime);
23986 } // If we have a work-in-progress fiber, it means there's still work to do
23987 // in this root.
23988
23989
23990 if (workInProgress !== null) {
23991 var prevExecutionContext = executionContext;
23992 executionContext |= RenderContext;
23993 var prevDispatcher = pushDispatcher(root);
23994 var prevInteractions = pushInteractions(root);
23995 startWorkLoopTimer(workInProgress);
23996
23997 do {
23998 try {
23999 workLoopConcurrent();
24000 break;
24001 } catch (thrownValue) {
24002 handleError(root, thrownValue);
24003 }
24004 } while (true);
24005
24006 resetContextDependencies();
24007 executionContext = prevExecutionContext;
24008 popDispatcher(prevDispatcher);
24009
24010 if (enableSchedulerTracing) {
24011 popInteractions(prevInteractions);
24012 }
24013
24014 if (workInProgressRootExitStatus === RootFatalErrored) {
24015 var fatalError = workInProgressRootFatalError;
24016 stopInterruptedWorkLoopTimer();
24017 prepareFreshStack(root, expirationTime);
24018 markRootSuspendedAtTime(root, expirationTime);
24019 ensureRootIsScheduled(root);
24020 throw fatalError;
24021 }
24022
24023 if (workInProgress !== null) {
24024 // There's still work left over. Exit without committing.
24025 stopInterruptedWorkLoopTimer();
24026 } else {
24027 // We now have a consistent tree. The next step is either to commit it,
24028 // or, if something suspended, wait to commit it after a timeout.
24029 stopFinishedWorkLoopTimer();
24030 var finishedWork = root.finishedWork = root.current.alternate;
24031 root.finishedExpirationTime = expirationTime;
24032 resolveLocksOnRoot(root, expirationTime);
24033 finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
24034 }
24035
24036 ensureRootIsScheduled(root);
24037
24038 if (root.callbackNode === originalCallbackNode) {
24039 // The task node scheduled for this root is the same one that's
24040 // currently executed. Need to return a continuation.
24041 return performConcurrentWorkOnRoot.bind(null, root);
24042 }
24043 }
24044 }
24045
24046 return null;
24047}
24048
24049function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
24050 // Set this to null to indicate there's no in-progress render.
24051 workInProgressRoot = null;
24052
24053 switch (exitStatus) {
24054 case RootIncomplete:
24055 case RootFatalErrored:
24056 {
24057 (function () {
24058 {
24059 {
24060 throw ReactError(Error("Root did not complete. This is a bug in React."));
24061 }
24062 }
24063 })();
24064 }
24065 // Flow knows about invariant, so it complains if I add a break
24066 // statement, but eslint doesn't know about invariant, so it complains
24067 // if I do. eslint-disable-next-line no-fallthrough
24068
24069 case RootErrored:
24070 {
24071 if (expirationTime !== Idle) {
24072 // If this was an async render, the error may have happened due to
24073 // a mutation in a concurrent event. Try rendering one more time,
24074 // synchronously, to see if the error goes away. If there are
24075 // lower priority updates, let's include those, too, in case they
24076 // fix the inconsistency. Render at Idle to include all updates.
24077 markRootExpiredAtTime(root, Idle);
24078 break;
24079 } // Commit the root in its errored state.
24080
24081
24082 commitRoot(root);
24083 break;
24084 }
24085
24086 case RootSuspended:
24087 {
24088 markRootSuspendedAtTime(root, expirationTime);
24089 var lastSuspendedTime = root.lastSuspendedTime;
24090
24091 if (expirationTime === lastSuspendedTime) {
24092 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24093 }
24094
24095 flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we
24096 // should immediately commit it or wait a bit.
24097 // If we have processed new updates during this render, we may now
24098 // have a new loading state ready. We want to ensure that we commit
24099 // that as soon as possible.
24100
24101 var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
24102
24103 if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
24104 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24105 // If we have not processed any new updates during this pass, then
24106 // this is either a retry of an existing fallback state or a
24107 // hidden tree. Hidden trees shouldn't be batched with other work
24108 // and after that's fixed it can only be a retry. We're going to
24109 // throttle committing retries so that we don't show too many
24110 // loading states too quickly.
24111 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
24112
24113 if (msUntilTimeout > 10) {
24114 if (workInProgressRootHasPendingPing) {
24115 var lastPingedTime = root.lastPingedTime;
24116
24117 if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
24118 // This render was pinged but we didn't get to restart
24119 // earlier so try restarting now instead.
24120 root.lastPingedTime = expirationTime;
24121 prepareFreshStack(root, expirationTime);
24122 break;
24123 }
24124 }
24125
24126 var nextTime = getNextRootExpirationTimeToWorkOn(root);
24127
24128 if (nextTime !== NoWork && nextTime !== expirationTime) {
24129 // There's additional work on this root.
24130 break;
24131 }
24132
24133 if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
24134 // We should prefer to render the fallback of at the last
24135 // suspended level. Ping the last suspended level to try
24136 // rendering it again.
24137 root.lastPingedTime = lastSuspendedTime;
24138 break;
24139 } // The render is suspended, it hasn't timed out, and there's no
24140 // lower priority work to do. Instead of committing the fallback
24141 // immediately, wait for more data to arrive.
24142
24143
24144 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
24145 break;
24146 }
24147 } // The work expired. Commit immediately.
24148
24149
24150 commitRoot(root);
24151 break;
24152 }
24153
24154 case RootSuspendedWithDelay:
24155 {
24156 markRootSuspendedAtTime(root, expirationTime);
24157 var _lastSuspendedTime = root.lastSuspendedTime;
24158
24159 if (expirationTime === _lastSuspendedTime) {
24160 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24161 }
24162
24163 flushSuspensePriorityWarningInDEV();
24164
24165 if ( // do not delay if we're inside an act() scope
24166 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24167 // We're suspended in a state that should be avoided. We'll try to
24168 // avoid committing it for as long as the timeouts let us.
24169 if (workInProgressRootHasPendingPing) {
24170 var _lastPingedTime = root.lastPingedTime;
24171
24172 if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
24173 // This render was pinged but we didn't get to restart earlier
24174 // so try restarting now instead.
24175 root.lastPingedTime = expirationTime;
24176 prepareFreshStack(root, expirationTime);
24177 break;
24178 }
24179 }
24180
24181 var _nextTime = getNextRootExpirationTimeToWorkOn(root);
24182
24183 if (_nextTime !== NoWork && _nextTime !== expirationTime) {
24184 // There's additional work on this root.
24185 break;
24186 }
24187
24188 if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
24189 // We should prefer to render the fallback of at the last
24190 // suspended level. Ping the last suspended level to try
24191 // rendering it again.
24192 root.lastPingedTime = _lastSuspendedTime;
24193 break;
24194 }
24195
24196 var _msUntilTimeout;
24197
24198 if (workInProgressRootLatestSuspenseTimeout !== Sync) {
24199 // We have processed a suspense config whose expiration time we
24200 // can use as the timeout.
24201 _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
24202 } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
24203 // This should never normally happen because only new updates
24204 // cause delayed states, so we should have processed something.
24205 // However, this could also happen in an offscreen tree.
24206 _msUntilTimeout = 0;
24207 } else {
24208 // If we don't have a suspense config, we're going to use a
24209 // heuristic to determine how long we can suspend.
24210 var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
24211 var currentTimeMs = now();
24212 var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
24213 var timeElapsed = currentTimeMs - eventTimeMs;
24214
24215 if (timeElapsed < 0) {
24216 // We get this wrong some time since we estimate the time.
24217 timeElapsed = 0;
24218 }
24219
24220 _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
24221 // event time is exact instead of inferred from expiration time
24222 // we don't need this.
24223
24224 if (timeUntilExpirationMs < _msUntilTimeout) {
24225 _msUntilTimeout = timeUntilExpirationMs;
24226 }
24227 } // Don't bother with a very short suspense time.
24228
24229
24230 if (_msUntilTimeout > 10) {
24231 // The render is suspended, it hasn't timed out, and there's no
24232 // lower priority work to do. Instead of committing the fallback
24233 // immediately, wait for more data to arrive.
24234 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
24235 break;
24236 }
24237 } // The work expired. Commit immediately.
24238
24239
24240 commitRoot(root);
24241 break;
24242 }
24243
24244 case RootCompleted:
24245 {
24246 // The work completed. Ready to commit.
24247 if ( // do not delay if we're inside an act() scope
24248 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
24249 // If we have exceeded the minimum loading delay, which probably
24250 // means we have shown a spinner already, we might have to suspend
24251 // a bit longer to ensure that the spinner is shown for
24252 // enough time.
24253 var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
24254
24255 if (_msUntilTimeout2 > 10) {
24256 markRootSuspendedAtTime(root, expirationTime);
24257 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
24258 break;
24259 }
24260 }
24261
24262 commitRoot(root);
24263 break;
24264 }
24265
24266 case RootLocked:
24267 {
24268 // This root has a lock that prevents it from committing. Exit. If
24269 // we begin work on the root again, without any intervening updates,
24270 // it will finish without doing additional work.
24271 markRootSuspendedAtTime(root, expirationTime);
24272 break;
24273 }
24274
24275 default:
24276 {
24277 (function () {
24278 {
24279 {
24280 throw ReactError(Error("Unknown root exit status."));
24281 }
24282 }
24283 })();
24284 }
24285 }
24286} // This is the entry point for synchronous tasks that don't go
24287// through Scheduler
24288
24289
24290function performSyncWorkOnRoot(root) {
24291 // Check if there's expired work on this root. Otherwise, render at Sync.
24292 var lastExpiredTime = root.lastExpiredTime;
24293 var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
24294
24295 if (root.finishedExpirationTime === expirationTime) {
24296 // There's already a pending commit at this expiration time.
24297 // TODO: This is poorly factored. This case only exists for the
24298 // batch.commit() API.
24299 commitRoot(root);
24300 } else {
24301 (function () {
24302 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24303 {
24304 throw ReactError(Error("Should not already be working."));
24305 }
24306 }
24307 })();
24308
24309 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24310 // and prepare a fresh one. Otherwise we'll continue where we left off.
24311
24312 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24313 prepareFreshStack(root, expirationTime);
24314 startWorkOnPendingInteractions(root, expirationTime);
24315 } // If we have a work-in-progress fiber, it means there's still work to do
24316 // in this root.
24317
24318
24319 if (workInProgress !== null) {
24320 var prevExecutionContext = executionContext;
24321 executionContext |= RenderContext;
24322 var prevDispatcher = pushDispatcher(root);
24323 var prevInteractions = pushInteractions(root);
24324 startWorkLoopTimer(workInProgress);
24325
24326 do {
24327 try {
24328 workLoopSync();
24329 break;
24330 } catch (thrownValue) {
24331 handleError(root, thrownValue);
24332 }
24333 } while (true);
24334
24335 resetContextDependencies();
24336 executionContext = prevExecutionContext;
24337 popDispatcher(prevDispatcher);
24338
24339 if (enableSchedulerTracing) {
24340 popInteractions(prevInteractions);
24341 }
24342
24343 if (workInProgressRootExitStatus === RootFatalErrored) {
24344 var fatalError = workInProgressRootFatalError;
24345 stopInterruptedWorkLoopTimer();
24346 prepareFreshStack(root, expirationTime);
24347 markRootSuspendedAtTime(root, expirationTime);
24348 ensureRootIsScheduled(root);
24349 throw fatalError;
24350 }
24351
24352 if (workInProgress !== null) {
24353 // This is a sync render, so we should have finished the whole tree.
24354 (function () {
24355 {
24356 {
24357 throw ReactError(Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."));
24358 }
24359 }
24360 })();
24361 } else {
24362 // We now have a consistent tree. Because this is a sync render, we
24363 // will commit it even if something suspended. The only exception is
24364 // if the root is locked (using the unstable_createBatch API).
24365 stopFinishedWorkLoopTimer();
24366 root.finishedWork = root.current.alternate;
24367 root.finishedExpirationTime = expirationTime;
24368 resolveLocksOnRoot(root, expirationTime);
24369 finishSyncRender(root, workInProgressRootExitStatus, expirationTime);
24370 } // Before exiting, make sure there's a callback scheduled for the next
24371 // pending level.
24372
24373
24374 ensureRootIsScheduled(root);
24375 }
24376 }
24377
24378 return null;
24379}
24380
24381function finishSyncRender(root, exitStatus, expirationTime) {
24382 if (exitStatus === RootLocked) {
24383 // This root has a lock that prevents it from committing. Exit. If we
24384 // begin work on the root again, without any intervening updates, it
24385 // will finish without doing additional work.
24386 markRootSuspendedAtTime(root, expirationTime);
24387 } else {
24388 // Set this to null to indicate there's no in-progress render.
24389 workInProgressRoot = null;
24390
24391 {
24392 if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) {
24393 flushSuspensePriorityWarningInDEV();
24394 }
24395 }
24396
24397 commitRoot(root);
24398 }
24399}
24400
24401function flushRoot(root, expirationTime) {
24402 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24403 (function () {
24404 {
24405 {
24406 throw ReactError(Error("work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method."));
24407 }
24408 }
24409 })();
24410 }
24411
24412 markRootExpiredAtTime(root, expirationTime);
24413 ensureRootIsScheduled(root);
24414 flushSyncCallbackQueue();
24415}
24416function flushDiscreteUpdates() {
24417 // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
24418 // However, `act` uses `batchedUpdates`, so there's no way to distinguish
24419 // those two cases. Need to fix this before exposing flushDiscreteUpdates
24420 // as a public API.
24421 if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
24422 if (true && (executionContext & RenderContext) !== NoContext) {
24423 warning$1(false, 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
24424 } // We're already rendering, so we can't synchronously flush pending work.
24425 // This is probably a nested event dispatch triggered by a lifecycle/effect,
24426 // like `el.focus()`. Exit.
24427
24428
24429 return;
24430 }
24431
24432 flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
24433 // they fire before the next serial event.
24434
24435 flushPassiveEffects();
24436}
24437
24438function resolveLocksOnRoot(root, expirationTime) {
24439 var firstBatch = root.firstBatch;
24440
24441 if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
24442 scheduleCallback(NormalPriority, function () {
24443 firstBatch._onComplete();
24444
24445 return null;
24446 });
24447 workInProgressRootExitStatus = RootLocked;
24448 }
24449}
24450
24451
24452
24453
24454function flushPendingDiscreteUpdates() {
24455 if (rootsWithPendingDiscreteUpdates !== null) {
24456 // For each root with pending discrete updates, schedule a callback to
24457 // immediately flush them.
24458 var roots = rootsWithPendingDiscreteUpdates;
24459 rootsWithPendingDiscreteUpdates = null;
24460 roots.forEach(function (expirationTime, root) {
24461 markRootExpiredAtTime(root, expirationTime);
24462 ensureRootIsScheduled(root);
24463 }); // Now flush the immediate queue.
24464
24465 flushSyncCallbackQueue();
24466 }
24467}
24468
24469function batchedUpdates$1(fn, a) {
24470 var prevExecutionContext = executionContext;
24471 executionContext |= BatchedContext;
24472
24473 try {
24474 return fn(a);
24475 } finally {
24476 executionContext = prevExecutionContext;
24477
24478 if (executionContext === NoContext) {
24479 // Flush the immediate callbacks that were scheduled during this batch
24480 flushSyncCallbackQueue();
24481 }
24482 }
24483}
24484function batchedEventUpdates$1(fn, a) {
24485 var prevExecutionContext = executionContext;
24486 executionContext |= EventContext;
24487
24488 try {
24489 return fn(a);
24490 } finally {
24491 executionContext = prevExecutionContext;
24492
24493 if (executionContext === NoContext) {
24494 // Flush the immediate callbacks that were scheduled during this batch
24495 flushSyncCallbackQueue();
24496 }
24497 }
24498}
24499function discreteUpdates$1(fn, a, b, c) {
24500 var prevExecutionContext = executionContext;
24501 executionContext |= DiscreteEventContext;
24502
24503 try {
24504 // Should this
24505 return runWithPriority$2(UserBlockingPriority$2, fn.bind(null, a, b, c));
24506 } finally {
24507 executionContext = prevExecutionContext;
24508
24509 if (executionContext === NoContext) {
24510 // Flush the immediate callbacks that were scheduled during this batch
24511 flushSyncCallbackQueue();
24512 }
24513 }
24514}
24515function unbatchedUpdates(fn, a) {
24516 var prevExecutionContext = executionContext;
24517 executionContext &= ~BatchedContext;
24518 executionContext |= LegacyUnbatchedContext;
24519
24520 try {
24521 return fn(a);
24522 } finally {
24523 executionContext = prevExecutionContext;
24524
24525 if (executionContext === NoContext) {
24526 // Flush the immediate callbacks that were scheduled during this batch
24527 flushSyncCallbackQueue();
24528 }
24529 }
24530}
24531function flushSync(fn, a) {
24532 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24533 (function () {
24534 {
24535 {
24536 throw ReactError(Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering."));
24537 }
24538 }
24539 })();
24540 }
24541
24542 var prevExecutionContext = executionContext;
24543 executionContext |= BatchedContext;
24544
24545 try {
24546 return runWithPriority$2(ImmediatePriority, fn.bind(null, a));
24547 } finally {
24548 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
24549 // Note that this will happen even if batchedUpdates is higher up
24550 // the stack.
24551
24552 flushSyncCallbackQueue();
24553 }
24554}
24555function flushControlled(fn) {
24556 var prevExecutionContext = executionContext;
24557 executionContext |= BatchedContext;
24558
24559 try {
24560 runWithPriority$2(ImmediatePriority, fn);
24561 } finally {
24562 executionContext = prevExecutionContext;
24563
24564 if (executionContext === NoContext) {
24565 // Flush the immediate callbacks that were scheduled during this batch
24566 flushSyncCallbackQueue();
24567 }
24568 }
24569}
24570
24571function prepareFreshStack(root, expirationTime) {
24572 root.finishedWork = null;
24573 root.finishedExpirationTime = NoWork;
24574 var timeoutHandle = root.timeoutHandle;
24575
24576 if (timeoutHandle !== noTimeout) {
24577 // The root previous suspended and scheduled a timeout to commit a fallback
24578 // state. Now that we have additional work, cancel the timeout.
24579 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
24580
24581 cancelTimeout(timeoutHandle);
24582 }
24583
24584 if (workInProgress !== null) {
24585 var interruptedWork = workInProgress.return;
24586
24587 while (interruptedWork !== null) {
24588 unwindInterruptedWork(interruptedWork);
24589 interruptedWork = interruptedWork.return;
24590 }
24591 }
24592
24593 workInProgressRoot = root;
24594 workInProgress = createWorkInProgress(root.current, null, expirationTime);
24595 renderExpirationTime = expirationTime;
24596 workInProgressRootExitStatus = RootIncomplete;
24597 workInProgressRootFatalError = null;
24598 workInProgressRootLatestProcessedExpirationTime = Sync;
24599 workInProgressRootLatestSuspenseTimeout = Sync;
24600 workInProgressRootCanSuspendUsingConfig = null;
24601 workInProgressRootNextUnprocessedUpdateTime = NoWork;
24602 workInProgressRootHasPendingPing = false;
24603
24604 if (enableSchedulerTracing) {
24605 spawnedWorkDuringRender = null;
24606 }
24607
24608 {
24609 ReactStrictModeWarnings.discardPendingWarnings();
24610 componentsThatTriggeredHighPriSuspend = null;
24611 }
24612}
24613
24614function handleError(root, thrownValue) {
24615 do {
24616 try {
24617 // Reset module-level state that was set during the render phase.
24618 resetContextDependencies();
24619 resetHooks();
24620
24621 if (workInProgress === null || workInProgress.return === null) {
24622 // Expected to be working on a non-root fiber. This is a fatal error
24623 // because there's no ancestor that can handle it; the root is
24624 // supposed to capture all errors that weren't caught by an error
24625 // boundary.
24626 workInProgressRootExitStatus = RootFatalErrored;
24627 workInProgressRootFatalError = thrownValue;
24628 return null;
24629 }
24630
24631 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
24632 // Record the time spent rendering before an error was thrown. This
24633 // avoids inaccurate Profiler durations in the case of a
24634 // suspended render.
24635 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
24636 }
24637
24638 throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime);
24639 workInProgress = completeUnitOfWork(workInProgress);
24640 } catch (yetAnotherThrownValue) {
24641 // Something in the return path also threw.
24642 thrownValue = yetAnotherThrownValue;
24643 continue;
24644 } // Return to the normal work loop.
24645
24646
24647 return;
24648 } while (true);
24649}
24650
24651function pushDispatcher(root) {
24652 var prevDispatcher = ReactCurrentDispatcher.current;
24653 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
24654
24655 if (prevDispatcher === null) {
24656 // The React isomorphic package does not include a default dispatcher.
24657 // Instead the first renderer will lazily attach one, in order to give
24658 // nicer error messages.
24659 return ContextOnlyDispatcher;
24660 } else {
24661 return prevDispatcher;
24662 }
24663}
24664
24665function popDispatcher(prevDispatcher) {
24666 ReactCurrentDispatcher.current = prevDispatcher;
24667}
24668
24669function pushInteractions(root) {
24670 if (enableSchedulerTracing) {
24671 var prevInteractions = __interactionsRef.current;
24672 __interactionsRef.current = root.memoizedInteractions;
24673 return prevInteractions;
24674 }
24675
24676 return null;
24677}
24678
24679function popInteractions(prevInteractions) {
24680 if (enableSchedulerTracing) {
24681 __interactionsRef.current = prevInteractions;
24682 }
24683}
24684
24685function markCommitTimeOfFallback() {
24686 globalMostRecentFallbackTime = now();
24687}
24688function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
24689 if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
24690 workInProgressRootLatestProcessedExpirationTime = expirationTime;
24691 }
24692
24693 if (suspenseConfig !== null) {
24694 if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
24695 workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
24696
24697 workInProgressRootCanSuspendUsingConfig = suspenseConfig;
24698 }
24699 }
24700}
24701function markUnprocessedUpdateTime(expirationTime) {
24702 if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
24703 workInProgressRootNextUnprocessedUpdateTime = expirationTime;
24704 }
24705}
24706function renderDidSuspend() {
24707 if (workInProgressRootExitStatus === RootIncomplete) {
24708 workInProgressRootExitStatus = RootSuspended;
24709 }
24710}
24711function renderDidSuspendDelayIfPossible() {
24712 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
24713 workInProgressRootExitStatus = RootSuspendedWithDelay;
24714 } // Check if there's a lower priority update somewhere else in the tree.
24715
24716
24717 if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
24718 // Mark the current render as suspended, and then mark that there's a
24719 // pending update.
24720 // TODO: This should immediately interrupt the current render, instead
24721 // of waiting until the next time we yield.
24722 markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
24723 markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
24724 }
24725}
24726function renderDidError() {
24727 if (workInProgressRootExitStatus !== RootCompleted) {
24728 workInProgressRootExitStatus = RootErrored;
24729 }
24730} // Called during render to determine if anything has suspended.
24731// Returns false if we're not sure.
24732
24733function renderHasNotSuspendedYet() {
24734 // If something errored or completed, we can't really be sure,
24735 // so those are false.
24736 return workInProgressRootExitStatus === RootIncomplete;
24737}
24738
24739function inferTimeFromExpirationTime(expirationTime) {
24740 // We don't know exactly when the update was scheduled, but we can infer an
24741 // approximate start time from the expiration time.
24742 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24743 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
24744}
24745
24746function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
24747 // We don't know exactly when the update was scheduled, but we can infer an
24748 // approximate start time from the expiration time by subtracting the timeout
24749 // that was added to the event time.
24750 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24751 return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
24752} // The work loop is an extremely hot path. Tell Closure not to inline it.
24753
24754/** @noinline */
24755
24756
24757function workLoopSync() {
24758 // Already timed out, so perform work without checking if we need to yield.
24759 while (workInProgress !== null) {
24760 workInProgress = performUnitOfWork(workInProgress);
24761 }
24762}
24763/** @noinline */
24764
24765
24766function workLoopConcurrent() {
24767 // Perform work until Scheduler asks us to yield
24768 while (workInProgress !== null && !shouldYield()) {
24769 workInProgress = performUnitOfWork(workInProgress);
24770 }
24771}
24772
24773function performUnitOfWork(unitOfWork) {
24774 // The current, flushed, state of this fiber is the alternate. Ideally
24775 // nothing should rely on this, but relying on it here means that we don't
24776 // need an additional field on the work in progress.
24777 var current$$1 = unitOfWork.alternate;
24778 startWorkTimer(unitOfWork);
24779 setCurrentFiber(unitOfWork);
24780 var next;
24781
24782 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
24783 startProfilerTimer(unitOfWork);
24784 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24785 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
24786 } else {
24787 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24788 }
24789
24790 resetCurrentFiber();
24791 unitOfWork.memoizedProps = unitOfWork.pendingProps;
24792
24793 if (next === null) {
24794 // If this doesn't spawn new work, complete the current work.
24795 next = completeUnitOfWork(unitOfWork);
24796 }
24797
24798 ReactCurrentOwner$2.current = null;
24799 return next;
24800}
24801
24802function completeUnitOfWork(unitOfWork) {
24803 // Attempt to complete the current unit of work, then move to the next
24804 // sibling. If there are no more siblings, return to the parent fiber.
24805 workInProgress = unitOfWork;
24806
24807 do {
24808 // The current, flushed, state of this fiber is the alternate. Ideally
24809 // nothing should rely on this, but relying on it here means that we don't
24810 // need an additional field on the work in progress.
24811 var current$$1 = workInProgress.alternate;
24812 var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
24813
24814 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
24815 setCurrentFiber(workInProgress);
24816 var next = void 0;
24817
24818 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode) {
24819 next = completeWork(current$$1, workInProgress, renderExpirationTime);
24820 } else {
24821 startProfilerTimer(workInProgress);
24822 next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error.
24823
24824 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
24825 }
24826
24827 stopWorkTimer(workInProgress);
24828 resetCurrentFiber();
24829 resetChildExpirationTime(workInProgress);
24830
24831 if (next !== null) {
24832 // Completing this fiber spawned new work. Work on that next.
24833 return next;
24834 }
24835
24836 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
24837 (returnFiber.effectTag & Incomplete) === NoEffect) {
24838 // Append all the effects of the subtree and this fiber onto the effect
24839 // list of the parent. The completion order of the children affects the
24840 // side-effect order.
24841 if (returnFiber.firstEffect === null) {
24842 returnFiber.firstEffect = workInProgress.firstEffect;
24843 }
24844
24845 if (workInProgress.lastEffect !== null) {
24846 if (returnFiber.lastEffect !== null) {
24847 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
24848 }
24849
24850 returnFiber.lastEffect = workInProgress.lastEffect;
24851 } // If this fiber had side-effects, we append it AFTER the children's
24852 // side-effects. We can perform certain side-effects earlier if needed,
24853 // by doing multiple passes over the effect list. We don't want to
24854 // schedule our own side-effect on our own list because if end up
24855 // reusing children we'll schedule this effect onto itself since we're
24856 // at the end.
24857
24858
24859 var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
24860 // list. PerformedWork effect is read by React DevTools but shouldn't be
24861 // committed.
24862
24863 if (effectTag > PerformedWork) {
24864 if (returnFiber.lastEffect !== null) {
24865 returnFiber.lastEffect.nextEffect = workInProgress;
24866 } else {
24867 returnFiber.firstEffect = workInProgress;
24868 }
24869
24870 returnFiber.lastEffect = workInProgress;
24871 }
24872 }
24873 } else {
24874 // This fiber did not complete because something threw. Pop values off
24875 // the stack without entering the complete phase. If this is a boundary,
24876 // capture values if possible.
24877 var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time.
24878
24879
24880 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode) {
24881 // Record the render duration for the fiber that errored.
24882 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
24883
24884 var actualDuration = workInProgress.actualDuration;
24885 var child = workInProgress.child;
24886
24887 while (child !== null) {
24888 actualDuration += child.actualDuration;
24889 child = child.sibling;
24890 }
24891
24892 workInProgress.actualDuration = actualDuration;
24893 }
24894
24895 if (_next !== null) {
24896 // If completing this work spawned new work, do that next. We'll come
24897 // back here again.
24898 // Since we're restarting, remove anything that is not a host effect
24899 // from the effect tag.
24900 // TODO: The name stopFailedWorkTimer is misleading because Suspense
24901 // also captures and restarts.
24902 stopFailedWorkTimer(workInProgress);
24903 _next.effectTag &= HostEffectMask;
24904 return _next;
24905 }
24906
24907 stopWorkTimer(workInProgress);
24908
24909 if (returnFiber !== null) {
24910 // Mark the parent fiber as incomplete and clear its effect list.
24911 returnFiber.firstEffect = returnFiber.lastEffect = null;
24912 returnFiber.effectTag |= Incomplete;
24913 }
24914 }
24915
24916 var siblingFiber = workInProgress.sibling;
24917
24918 if (siblingFiber !== null) {
24919 // If there is more work to do in this returnFiber, do that next.
24920 return siblingFiber;
24921 } // Otherwise, return to the parent
24922
24923
24924 workInProgress = returnFiber;
24925 } while (workInProgress !== null); // We've reached the root.
24926
24927
24928 if (workInProgressRootExitStatus === RootIncomplete) {
24929 workInProgressRootExitStatus = RootCompleted;
24930 }
24931
24932 return null;
24933}
24934
24935function getRemainingExpirationTime(fiber) {
24936 var updateExpirationTime = fiber.expirationTime;
24937 var childExpirationTime = fiber.childExpirationTime;
24938 return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
24939}
24940
24941function resetChildExpirationTime(completedWork) {
24942 if (renderExpirationTime !== Never && completedWork.childExpirationTime === Never) {
24943 // The children of this component are hidden. Don't bubble their
24944 // expiration times.
24945 return;
24946 }
24947
24948 var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
24949
24950 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
24951 // In profiling mode, resetChildExpirationTime is also used to reset
24952 // profiler durations.
24953 var actualDuration = completedWork.actualDuration;
24954 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
24955 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
24956 // When work is done, it should bubble to the parent's actualDuration. If
24957 // the fiber has not been cloned though, (meaning no work was done), then
24958 // this value will reflect the amount of time spent working on a previous
24959 // render. In that case it should not bubble. We determine whether it was
24960 // cloned by comparing the child pointer.
24961
24962 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
24963 var child = completedWork.child;
24964
24965 while (child !== null) {
24966 var childUpdateExpirationTime = child.expirationTime;
24967 var childChildExpirationTime = child.childExpirationTime;
24968
24969 if (childUpdateExpirationTime > newChildExpirationTime) {
24970 newChildExpirationTime = childUpdateExpirationTime;
24971 }
24972
24973 if (childChildExpirationTime > newChildExpirationTime) {
24974 newChildExpirationTime = childChildExpirationTime;
24975 }
24976
24977 if (shouldBubbleActualDurations) {
24978 actualDuration += child.actualDuration;
24979 }
24980
24981 treeBaseDuration += child.treeBaseDuration;
24982 child = child.sibling;
24983 }
24984
24985 completedWork.actualDuration = actualDuration;
24986 completedWork.treeBaseDuration = treeBaseDuration;
24987 } else {
24988 var _child = completedWork.child;
24989
24990 while (_child !== null) {
24991 var _childUpdateExpirationTime = _child.expirationTime;
24992 var _childChildExpirationTime = _child.childExpirationTime;
24993
24994 if (_childUpdateExpirationTime > newChildExpirationTime) {
24995 newChildExpirationTime = _childUpdateExpirationTime;
24996 }
24997
24998 if (_childChildExpirationTime > newChildExpirationTime) {
24999 newChildExpirationTime = _childChildExpirationTime;
25000 }
25001
25002 _child = _child.sibling;
25003 }
25004 }
25005
25006 completedWork.childExpirationTime = newChildExpirationTime;
25007}
25008
25009function commitRoot(root) {
25010 var renderPriorityLevel = getCurrentPriorityLevel();
25011 runWithPriority$2(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
25012 return null;
25013}
25014
25015function commitRootImpl(root, renderPriorityLevel) {
25016 flushPassiveEffects();
25017 flushRenderPhaseStrictModeWarningsInDEV();
25018
25019 (function () {
25020 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25021 {
25022 throw ReactError(Error("Should not already be working."));
25023 }
25024 }
25025 })();
25026
25027 var finishedWork = root.finishedWork;
25028 var expirationTime = root.finishedExpirationTime;
25029
25030 if (finishedWork === null) {
25031 return null;
25032 }
25033
25034 root.finishedWork = null;
25035 root.finishedExpirationTime = NoWork;
25036
25037 (function () {
25038 if (!(finishedWork !== root.current)) {
25039 {
25040 throw ReactError(Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."));
25041 }
25042 }
25043 })(); // commitRoot never returns a continuation; it always finishes synchronously.
25044 // So we can clear these now to allow a new callback to be scheduled.
25045
25046
25047 root.callbackNode = null;
25048 root.callbackExpirationTime = NoWork;
25049 root.callbackPriority = NoPriority;
25050 root.nextKnownPendingLevel = NoWork;
25051 startCommitTimer(); // Update the first and last pending times on this root. The new first
25052 // pending time is whatever is left on the root fiber.
25053
25054 var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
25055 markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
25056
25057 if (root === workInProgressRoot) {
25058 // We can reset these now that they are finished.
25059 workInProgressRoot = null;
25060 workInProgress = null;
25061 renderExpirationTime = NoWork;
25062 } else {} // This indicates that the last root we worked on is not the same one that
25063 // we're committing now. This most commonly happens when a suspended root
25064 // times out.
25065 // Get the list of effects.
25066
25067
25068 var firstEffect;
25069
25070 if (finishedWork.effectTag > PerformedWork) {
25071 // A fiber's effect list consists only of its children, not itself. So if
25072 // the root has an effect, we need to add it to the end of the list. The
25073 // resulting list is the set that would belong to the root's parent, if it
25074 // had one; that is, all the effects in the tree including the root.
25075 if (finishedWork.lastEffect !== null) {
25076 finishedWork.lastEffect.nextEffect = finishedWork;
25077 firstEffect = finishedWork.firstEffect;
25078 } else {
25079 firstEffect = finishedWork;
25080 }
25081 } else {
25082 // There is no effect on the root.
25083 firstEffect = finishedWork.firstEffect;
25084 }
25085
25086 if (firstEffect !== null) {
25087 var prevExecutionContext = executionContext;
25088 executionContext |= CommitContext;
25089 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
25090
25091 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
25092 // of the effect list for each phase: all mutation effects come before all
25093 // layout effects, and so on.
25094 // The first phase a "before mutation" phase. We use this phase to read the
25095 // state of the host tree right before we mutate it. This is where
25096 // getSnapshotBeforeUpdate is called.
25097
25098 startCommitSnapshotEffectsTimer();
25099 prepareForCommit(root.containerInfo);
25100 nextEffect = firstEffect;
25101
25102 do {
25103 {
25104 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
25105
25106 if (hasCaughtError()) {
25107 (function () {
25108 if (!(nextEffect !== null)) {
25109 {
25110 throw ReactError(Error("Should be working on an effect."));
25111 }
25112 }
25113 })();
25114
25115 var error = clearCaughtError();
25116 captureCommitPhaseError(nextEffect, error);
25117 nextEffect = nextEffect.nextEffect;
25118 }
25119 }
25120 } while (nextEffect !== null);
25121
25122 stopCommitSnapshotEffectsTimer();
25123
25124 if (enableProfilerTimer) {
25125 // Mark the current commit time to be shared by all Profilers in this
25126 // batch. This enables them to be grouped later.
25127 recordCommitTime();
25128 } // The next phase is the mutation phase, where we mutate the host tree.
25129
25130
25131 startCommitHostEffectsTimer();
25132 nextEffect = firstEffect;
25133
25134 do {
25135 {
25136 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
25137
25138 if (hasCaughtError()) {
25139 (function () {
25140 if (!(nextEffect !== null)) {
25141 {
25142 throw ReactError(Error("Should be working on an effect."));
25143 }
25144 }
25145 })();
25146
25147 var _error = clearCaughtError();
25148
25149 captureCommitPhaseError(nextEffect, _error);
25150 nextEffect = nextEffect.nextEffect;
25151 }
25152 }
25153 } while (nextEffect !== null);
25154
25155 stopCommitHostEffectsTimer();
25156 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
25157 // the mutation phase, so that the previous tree is still current during
25158 // componentWillUnmount, but before the layout phase, so that the finished
25159 // work is current during componentDidMount/Update.
25160
25161 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
25162 // the host tree after it's been mutated. The idiomatic use case for this is
25163 // layout, but class component lifecycles also fire here for legacy reasons.
25164
25165 startCommitLifeCyclesTimer();
25166 nextEffect = firstEffect;
25167
25168 do {
25169 {
25170 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
25171
25172 if (hasCaughtError()) {
25173 (function () {
25174 if (!(nextEffect !== null)) {
25175 {
25176 throw ReactError(Error("Should be working on an effect."));
25177 }
25178 }
25179 })();
25180
25181 var _error2 = clearCaughtError();
25182
25183 captureCommitPhaseError(nextEffect, _error2);
25184 nextEffect = nextEffect.nextEffect;
25185 }
25186 }
25187 } while (nextEffect !== null);
25188
25189 stopCommitLifeCyclesTimer();
25190 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
25191 // opportunity to paint.
25192
25193 requestPaint();
25194
25195 if (enableSchedulerTracing) {
25196 popInteractions(prevInteractions);
25197 }
25198
25199 executionContext = prevExecutionContext;
25200 } else {
25201 // No effects.
25202 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
25203 // no effects.
25204 // TODO: Maybe there's a better way to report this.
25205
25206 startCommitSnapshotEffectsTimer();
25207 stopCommitSnapshotEffectsTimer();
25208
25209 if (enableProfilerTimer) {
25210 recordCommitTime();
25211 }
25212
25213 startCommitHostEffectsTimer();
25214 stopCommitHostEffectsTimer();
25215 startCommitLifeCyclesTimer();
25216 stopCommitLifeCyclesTimer();
25217 }
25218
25219 stopCommitTimer();
25220 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
25221
25222 if (rootDoesHavePassiveEffects) {
25223 // This commit has passive effects. Stash a reference to them. But don't
25224 // schedule a callback until after flushing layout work.
25225 rootDoesHavePassiveEffects = false;
25226 rootWithPendingPassiveEffects = root;
25227 pendingPassiveEffectsExpirationTime = expirationTime;
25228 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
25229 } else {
25230 // We are done with the effect chain at this point so let's clear the
25231 // nextEffect pointers to assist with GC. If we have passive effects, we'll
25232 // clear this in flushPassiveEffects.
25233 nextEffect = firstEffect;
25234
25235 while (nextEffect !== null) {
25236 var nextNextEffect = nextEffect.nextEffect;
25237 nextEffect.nextEffect = null;
25238 nextEffect = nextNextEffect;
25239 }
25240 } // Check if there's remaining work on this root
25241
25242
25243 var remainingExpirationTime = root.firstPendingTime;
25244
25245 if (remainingExpirationTime !== NoWork) {
25246 if (enableSchedulerTracing) {
25247 if (spawnedWorkDuringRender !== null) {
25248 var expirationTimes = spawnedWorkDuringRender;
25249 spawnedWorkDuringRender = null;
25250
25251 for (var i = 0; i < expirationTimes.length; i++) {
25252 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
25253 }
25254 }
25255
25256 schedulePendingInteractions(root, remainingExpirationTime);
25257 }
25258 } else {
25259 // If there's no remaining work, we can clear the set of already failed
25260 // error boundaries.
25261 legacyErrorBoundariesThatAlreadyFailed = null;
25262 }
25263
25264 if (enableSchedulerTracing) {
25265 if (!rootDidHavePassiveEffects) {
25266 // If there are no passive effects, then we can complete the pending interactions.
25267 // Otherwise, we'll wait until after the passive effects are flushed.
25268 // Wait to do this until after remaining work has been scheduled,
25269 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
25270 finishPendingInteractions(root, expirationTime);
25271 }
25272 }
25273
25274 if (remainingExpirationTime === Sync) {
25275 // Count the number of times the root synchronously re-renders without
25276 // finishing. If there are too many, it indicates an infinite update loop.
25277 if (root === rootWithNestedUpdates) {
25278 nestedUpdateCount++;
25279 } else {
25280 nestedUpdateCount = 0;
25281 rootWithNestedUpdates = root;
25282 }
25283 } else {
25284 nestedUpdateCount = 0;
25285 }
25286
25287 onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
25288 // additional work on this root is scheduled.
25289
25290 ensureRootIsScheduled(root);
25291
25292 if (hasUncaughtError) {
25293 hasUncaughtError = false;
25294 var _error3 = firstUncaughtError;
25295 firstUncaughtError = null;
25296 throw _error3;
25297 }
25298
25299 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
25300 // This is a legacy edge case. We just committed the initial mount of
25301 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
25302 // synchronously, but layout updates should be deferred until the end
25303 // of the batch.
25304 return null;
25305 } // If layout work was scheduled, flush it now.
25306
25307
25308 flushSyncCallbackQueue();
25309 return null;
25310}
25311
25312function commitBeforeMutationEffects() {
25313 while (nextEffect !== null) {
25314 var effectTag = nextEffect.effectTag;
25315
25316 if ((effectTag & Snapshot) !== NoEffect) {
25317 setCurrentFiber(nextEffect);
25318 recordEffect();
25319 var current$$1 = nextEffect.alternate;
25320 commitBeforeMutationLifeCycles(current$$1, nextEffect);
25321 resetCurrentFiber();
25322 }
25323
25324 if ((effectTag & Passive) !== NoEffect) {
25325 // If there are passive effects, schedule a callback to flush at
25326 // the earliest opportunity.
25327 if (!rootDoesHavePassiveEffects) {
25328 rootDoesHavePassiveEffects = true;
25329 scheduleCallback(NormalPriority, function () {
25330 flushPassiveEffects();
25331 return null;
25332 });
25333 }
25334 }
25335
25336 nextEffect = nextEffect.nextEffect;
25337 }
25338}
25339
25340function commitMutationEffects(root, renderPriorityLevel) {
25341 // TODO: Should probably move the bulk of this function to commitWork.
25342 while (nextEffect !== null) {
25343 setCurrentFiber(nextEffect);
25344 var effectTag = nextEffect.effectTag;
25345
25346 if (effectTag & ContentReset) {
25347 commitResetTextContent(nextEffect);
25348 }
25349
25350 if (effectTag & Ref) {
25351 var current$$1 = nextEffect.alternate;
25352
25353 if (current$$1 !== null) {
25354 commitDetachRef(current$$1);
25355 }
25356 } // The following switch statement is only concerned about placement,
25357 // updates, and deletions. To avoid needing to add a case for every possible
25358 // bitmap value, we remove the secondary effects from the effect tag and
25359 // switch on that value.
25360
25361
25362 var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
25363
25364 switch (primaryEffectTag) {
25365 case Placement:
25366 {
25367 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25368 // inserted, before any life-cycles like componentDidMount gets called.
25369 // TODO: findDOMNode doesn't rely on this any more but isMounted does
25370 // and isMounted is deprecated anyway so we should be able to kill this.
25371
25372 nextEffect.effectTag &= ~Placement;
25373 break;
25374 }
25375
25376 case PlacementAndUpdate:
25377 {
25378 // Placement
25379 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25380 // inserted, before any life-cycles like componentDidMount gets called.
25381
25382 nextEffect.effectTag &= ~Placement; // Update
25383
25384 var _current = nextEffect.alternate;
25385 commitWork(_current, nextEffect);
25386 break;
25387 }
25388
25389 case Hydrating:
25390 {
25391 nextEffect.effectTag &= ~Hydrating;
25392 break;
25393 }
25394
25395 case HydratingAndUpdate:
25396 {
25397 nextEffect.effectTag &= ~Hydrating; // Update
25398
25399 var _current2 = nextEffect.alternate;
25400 commitWork(_current2, nextEffect);
25401 break;
25402 }
25403
25404 case Update:
25405 {
25406 var _current3 = nextEffect.alternate;
25407 commitWork(_current3, nextEffect);
25408 break;
25409 }
25410
25411 case Deletion:
25412 {
25413 commitDeletion(root, nextEffect, renderPriorityLevel);
25414 break;
25415 }
25416 } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
25417
25418
25419 recordEffect();
25420 resetCurrentFiber();
25421 nextEffect = nextEffect.nextEffect;
25422 }
25423}
25424
25425function commitLayoutEffects(root, committedExpirationTime) {
25426 // TODO: Should probably move the bulk of this function to commitWork.
25427 while (nextEffect !== null) {
25428 setCurrentFiber(nextEffect);
25429 var effectTag = nextEffect.effectTag;
25430
25431 if (effectTag & (Update | Callback)) {
25432 recordEffect();
25433 var current$$1 = nextEffect.alternate;
25434 commitLifeCycles(root, current$$1, nextEffect, committedExpirationTime);
25435 }
25436
25437 if (effectTag & Ref) {
25438 recordEffect();
25439 commitAttachRef(nextEffect);
25440 }
25441
25442 resetCurrentFiber();
25443 nextEffect = nextEffect.nextEffect;
25444 }
25445}
25446
25447function flushPassiveEffects() {
25448 if (pendingPassiveEffectsRenderPriority !== NoPriority) {
25449 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
25450 pendingPassiveEffectsRenderPriority = NoPriority;
25451 return runWithPriority$2(priorityLevel, flushPassiveEffectsImpl);
25452 }
25453}
25454
25455function flushPassiveEffectsImpl() {
25456 if (rootWithPendingPassiveEffects === null) {
25457 return false;
25458 }
25459
25460 var root = rootWithPendingPassiveEffects;
25461 var expirationTime = pendingPassiveEffectsExpirationTime;
25462 rootWithPendingPassiveEffects = null;
25463 pendingPassiveEffectsExpirationTime = NoWork;
25464
25465 (function () {
25466 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25467 {
25468 throw ReactError(Error("Cannot flush passive effects while already rendering."));
25469 }
25470 }
25471 })();
25472
25473 var prevExecutionContext = executionContext;
25474 executionContext |= CommitContext;
25475 var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root
25476 // fiber, because the root is not part of its own effect list. This could
25477 // change in the future.
25478
25479 var effect = root.current.firstEffect;
25480
25481 while (effect !== null) {
25482 {
25483 setCurrentFiber(effect);
25484 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
25485
25486 if (hasCaughtError()) {
25487 (function () {
25488 if (!(effect !== null)) {
25489 {
25490 throw ReactError(Error("Should be working on an effect."));
25491 }
25492 }
25493 })();
25494
25495 var error = clearCaughtError();
25496 captureCommitPhaseError(effect, error);
25497 }
25498
25499 resetCurrentFiber();
25500 }
25501
25502 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
25503
25504 effect.nextEffect = null;
25505 effect = nextNextEffect;
25506 }
25507
25508 if (enableSchedulerTracing) {
25509 popInteractions(prevInteractions);
25510 finishPendingInteractions(root, expirationTime);
25511 }
25512
25513 executionContext = prevExecutionContext;
25514 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
25515 // exceeds the limit, we'll fire a warning.
25516
25517 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
25518 return true;
25519}
25520
25521function isAlreadyFailedLegacyErrorBoundary(instance) {
25522 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
25523}
25524function markLegacyErrorBoundaryAsFailed(instance) {
25525 if (legacyErrorBoundariesThatAlreadyFailed === null) {
25526 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
25527 } else {
25528 legacyErrorBoundariesThatAlreadyFailed.add(instance);
25529 }
25530}
25531
25532function prepareToThrowUncaughtError(error) {
25533 if (!hasUncaughtError) {
25534 hasUncaughtError = true;
25535 firstUncaughtError = error;
25536 }
25537}
25538
25539var onUncaughtError = prepareToThrowUncaughtError;
25540
25541function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
25542 var errorInfo = createCapturedValue(error, sourceFiber);
25543 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
25544 enqueueUpdate(rootFiber, update);
25545 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
25546
25547 if (root !== null) {
25548 ensureRootIsScheduled(root);
25549 schedulePendingInteractions(root, Sync);
25550 }
25551}
25552
25553function captureCommitPhaseError(sourceFiber, error) {
25554 if (sourceFiber.tag === HostRoot) {
25555 // Error was thrown at the root. There is no parent, so the root
25556 // itself should capture it.
25557 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
25558 return;
25559 }
25560
25561 var fiber = sourceFiber.return;
25562
25563 while (fiber !== null) {
25564 if (fiber.tag === HostRoot) {
25565 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
25566 return;
25567 } else if (fiber.tag === ClassComponent) {
25568 var ctor = fiber.type;
25569 var instance = fiber.stateNode;
25570
25571 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
25572 var errorInfo = createCapturedValue(error, sourceFiber);
25573 var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
25574 Sync);
25575 enqueueUpdate(fiber, update);
25576 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
25577
25578 if (root !== null) {
25579 ensureRootIsScheduled(root);
25580 schedulePendingInteractions(root, Sync);
25581 }
25582
25583 return;
25584 }
25585 }
25586
25587 fiber = fiber.return;
25588 }
25589}
25590function pingSuspendedRoot(root, thenable, suspendedTime) {
25591 var pingCache = root.pingCache;
25592
25593 if (pingCache !== null) {
25594 // The thenable resolved, so we no longer need to memoize, because it will
25595 // never be thrown again.
25596 pingCache.delete(thenable);
25597 }
25598
25599 if (workInProgressRoot === root && renderExpirationTime === suspendedTime) {
25600 // Received a ping at the same priority level at which we're currently
25601 // rendering. We might want to restart this render. This should mirror
25602 // the logic of whether or not a root suspends once it completes.
25603 // TODO: If we're rendering sync either due to Sync, Batched or expired,
25604 // we should probably never restart.
25605 // If we're suspended with delay, we'll always suspend so we can always
25606 // restart. If we're suspended without any updates, it might be a retry.
25607 // If it's early in the retry we can restart. We can't know for sure
25608 // whether we'll eventually process an update during this render pass,
25609 // but it's somewhat unlikely that we get to a ping before that, since
25610 // getting to the root most update is usually very fast.
25611 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
25612 // Restart from the root. Don't need to schedule a ping because
25613 // we're already working on this tree.
25614 prepareFreshStack(root, renderExpirationTime);
25615 } else {
25616 // Even though we can't restart right now, we might get an
25617 // opportunity later. So we mark this render as having a ping.
25618 workInProgressRootHasPendingPing = true;
25619 }
25620
25621 return;
25622 }
25623
25624 if (!isRootSuspendedAtTime(root, suspendedTime)) {
25625 // The root is no longer suspended at this time.
25626 return;
25627 }
25628
25629 var lastPingedTime = root.lastPingedTime;
25630
25631 if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
25632 // There's already a lower priority ping scheduled.
25633 return;
25634 } // Mark the time at which this ping was scheduled.
25635
25636
25637 root.lastPingedTime = suspendedTime;
25638
25639 if (root.finishedExpirationTime === suspendedTime) {
25640 // If there's a pending fallback waiting to commit, throw it away.
25641 root.finishedExpirationTime = NoWork;
25642 root.finishedWork = null;
25643 }
25644
25645 ensureRootIsScheduled(root);
25646 schedulePendingInteractions(root, suspendedTime);
25647}
25648
25649function retryTimedOutBoundary(boundaryFiber, retryTime) {
25650 // The boundary fiber (a Suspense component or SuspenseList component)
25651 // previously was rendered in its fallback state. One of the promises that
25652 // suspended it has resolved, which means at least part of the tree was
25653 // likely unblocked. Try rendering again, at a new expiration time.
25654 if (retryTime === Never) {
25655 var suspenseConfig = null; // Retries don't carry over the already committed update.
25656
25657 var currentTime = requestCurrentTime();
25658 retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
25659 } // TODO: Special case idle priority?
25660
25661
25662 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
25663
25664 if (root !== null) {
25665 ensureRootIsScheduled(root);
25666 schedulePendingInteractions(root, retryTime);
25667 }
25668}
25669
25670function retryDehydratedSuspenseBoundary(boundaryFiber) {
25671 var suspenseState = boundaryFiber.memoizedState;
25672 var retryTime = Never;
25673
25674 if (suspenseState !== null) {
25675 retryTime = suspenseState.retryTime;
25676 }
25677
25678 retryTimedOutBoundary(boundaryFiber, retryTime);
25679}
25680function resolveRetryThenable(boundaryFiber, thenable) {
25681 var retryTime = Never; // Default
25682
25683 var retryCache;
25684
25685 if (enableSuspenseServerRenderer) {
25686 switch (boundaryFiber.tag) {
25687 case SuspenseComponent:
25688 retryCache = boundaryFiber.stateNode;
25689 var suspenseState = boundaryFiber.memoizedState;
25690
25691 if (suspenseState !== null) {
25692 retryTime = suspenseState.retryTime;
25693 }
25694
25695 break;
25696
25697 case SuspenseListComponent:
25698 retryCache = boundaryFiber.stateNode;
25699 break;
25700
25701 default:
25702 (function () {
25703 {
25704 {
25705 throw ReactError(Error("Pinged unknown suspense boundary type. This is probably a bug in React."));
25706 }
25707 }
25708 })();
25709
25710 }
25711 } else {
25712 retryCache = boundaryFiber.stateNode;
25713 }
25714
25715 if (retryCache !== null) {
25716 // The thenable resolved, so we no longer need to memoize, because it will
25717 // never be thrown again.
25718 retryCache.delete(thenable);
25719 }
25720
25721 retryTimedOutBoundary(boundaryFiber, retryTime);
25722} // Computes the next Just Noticeable Difference (JND) boundary.
25723// The theory is that a person can't tell the difference between small differences in time.
25724// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
25725// difference in the experience. However, waiting for longer might mean that we can avoid
25726// showing an intermediate loading state. The longer we have already waited, the harder it
25727// is to tell small differences in time. Therefore, the longer we've already waited,
25728// the longer we can wait additionally. At some point we have to give up though.
25729// We pick a train model where the next boundary commits at a consistent schedule.
25730// These particular numbers are vague estimates. We expect to adjust them based on research.
25731
25732function jnd(timeElapsed) {
25733 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
25734}
25735
25736function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
25737 var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
25738
25739 if (busyMinDurationMs <= 0) {
25740 return 0;
25741 }
25742
25743 var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
25744
25745 var currentTimeMs = now();
25746 var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
25747 var timeElapsed = currentTimeMs - eventTimeMs;
25748
25749 if (timeElapsed <= busyDelayMs) {
25750 // If we haven't yet waited longer than the initial delay, we don't
25751 // have to wait any additional time.
25752 return 0;
25753 }
25754
25755 var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
25756
25757 return msUntilTimeout;
25758}
25759
25760function checkForNestedUpdates() {
25761 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
25762 nestedUpdateCount = 0;
25763 rootWithNestedUpdates = null;
25764
25765 (function () {
25766 {
25767 {
25768 throw ReactError(Error("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."));
25769 }
25770 }
25771 })();
25772 }
25773
25774 {
25775 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
25776 nestedPassiveUpdateCount = 0;
25777 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.');
25778 }
25779 }
25780}
25781
25782function flushRenderPhaseStrictModeWarningsInDEV() {
25783 {
25784 ReactStrictModeWarnings.flushLegacyContextWarning();
25785
25786 if (warnAboutDeprecatedLifecycles) {
25787 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
25788 }
25789 }
25790}
25791
25792function stopFinishedWorkLoopTimer() {
25793 var didCompleteRoot = true;
25794 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25795 interruptedBy = null;
25796}
25797
25798function stopInterruptedWorkLoopTimer() {
25799 // TODO: Track which fiber caused the interruption.
25800 var didCompleteRoot = false;
25801 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25802 interruptedBy = null;
25803}
25804
25805function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
25806 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime) {
25807 interruptedBy = fiberThatReceivedUpdate;
25808 }
25809}
25810
25811var didWarnStateUpdateForUnmountedComponent = null;
25812
25813function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
25814 {
25815 var tag = fiber.tag;
25816
25817 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
25818 // Only warn for user-defined components, not internal ones like Suspense.
25819 return;
25820 } // We show the whole stack but dedupe on the top component's name because
25821 // the problematic code almost always lies inside that component.
25822
25823
25824 var componentName = getComponentName(fiber.type) || 'ReactComponent';
25825
25826 if (didWarnStateUpdateForUnmountedComponent !== null) {
25827 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
25828 return;
25829 }
25830
25831 didWarnStateUpdateForUnmountedComponent.add(componentName);
25832 } else {
25833 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
25834 }
25835
25836 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));
25837 }
25838}
25839
25840var beginWork$$1;
25841
25842if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
25843 var dummyFiber = null;
25844
25845 beginWork$$1 = function (current$$1, unitOfWork, expirationTime) {
25846 // If a component throws an error, we replay it again in a synchronously
25847 // dispatched event, so that the debugger will treat it as an uncaught
25848 // error See ReactErrorUtils for more information.
25849 // Before entering the begin phase, copy the work-in-progress onto a dummy
25850 // fiber. If beginWork throws, we'll use this to reset the state.
25851 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
25852
25853 try {
25854 return beginWork$1(current$$1, unitOfWork, expirationTime);
25855 } catch (originalError) {
25856 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
25857 // Don't replay promises. Treat everything else like an error.
25858 throw originalError;
25859 } // Keep this code in sync with renderRoot; any changes here must have
25860 // corresponding changes there.
25861
25862
25863 resetContextDependencies();
25864 resetHooks(); // Unwind the failed stack frame
25865
25866 unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
25867
25868 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
25869
25870 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
25871 // Reset the profiler timer.
25872 startProfilerTimer(unitOfWork);
25873 } // Run beginWork again.
25874
25875
25876 invokeGuardedCallback(null, beginWork$1, null, current$$1, unitOfWork, expirationTime);
25877
25878 if (hasCaughtError()) {
25879 var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
25880 // Rethrow this error instead of the original one.
25881
25882 throw replayError;
25883 } else {
25884 // This branch is reachable if the render phase is impure.
25885 throw originalError;
25886 }
25887 }
25888 };
25889} else {
25890 beginWork$$1 = beginWork$1;
25891}
25892
25893var didWarnAboutUpdateInRender = false;
25894var didWarnAboutUpdateInGetChildContext = false;
25895
25896function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
25897 {
25898 if (fiber.tag === ClassComponent) {
25899 switch (phase) {
25900 case 'getChildContext':
25901 if (didWarnAboutUpdateInGetChildContext) {
25902 return;
25903 }
25904
25905 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
25906 didWarnAboutUpdateInGetChildContext = true;
25907 break;
25908
25909 case 'render':
25910 if (didWarnAboutUpdateInRender) {
25911 return;
25912 }
25913
25914 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.');
25915 didWarnAboutUpdateInRender = true;
25916 break;
25917 }
25918 }
25919 }
25920} // a 'shared' variable that changes when act() opens/closes in tests.
25921
25922
25923var IsThisRendererActing = {
25924 current: false
25925};
25926function warnIfNotScopedWithMatchingAct(fiber) {
25927 {
25928 if (warnsIfNotActing === true && IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
25929 warningWithoutStack$1(false, "It looks like you're using the wrong act() around your test interactions.\n" + 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' + '// for react-dom:\n' + "import {act} from 'react-dom/test-utils';\n" + '// ...\n' + 'act(() => ...);\n\n' + '// for react-test-renderer:\n' + "import TestRenderer from 'react-test-renderer';\n" + 'const {act} = TestRenderer;\n' + '// ...\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));
25930 }
25931 }
25932}
25933function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
25934 {
25935 if (warnsIfNotActing === true && (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25936 warningWithoutStack$1(false, 'An update to %s ran an effect, but 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));
25937 }
25938 }
25939}
25940
25941function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
25942 {
25943 if (warnsIfNotActing === true && executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25944 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));
25945 }
25946 }
25947}
25948
25949var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
25950
25951var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
25952// scheduler is the actual recommendation. The alternative could be a testing build,
25953// a new lib, or whatever; we dunno just yet. This message is for early adopters
25954// to get their tests right.
25955
25956function warnIfUnmockedScheduler(fiber) {
25957 {
25958 if (didWarnAboutUnmockedScheduler === false && unstable_flushAllWithoutAsserting === undefined) {
25959 if (fiber.mode & BatchedMode || fiber.mode & ConcurrentMode) {
25960 didWarnAboutUnmockedScheduler = true;
25961 warningWithoutStack$1(false, 'In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
25962 } else if (warnAboutUnmockedScheduler === true) {
25963 didWarnAboutUnmockedScheduler = true;
25964 warningWithoutStack$1(false, 'Starting from React v17, the "scheduler" module will need to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
25965 }
25966 }
25967 }
25968}
25969var componentsThatTriggeredHighPriSuspend = null;
25970function checkForWrongSuspensePriorityInDEV(sourceFiber) {
25971 {
25972 var currentPriorityLevel = getCurrentPriorityLevel();
25973
25974 if ((sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$2 || currentPriorityLevel === ImmediatePriority)) {
25975 var workInProgressNode = sourceFiber;
25976
25977 while (workInProgressNode !== null) {
25978 // Add the component that triggered the suspense
25979 var current$$1 = workInProgressNode.alternate;
25980
25981 if (current$$1 !== null) {
25982 // TODO: warn component that triggers the high priority
25983 // suspend is the HostRoot
25984 switch (workInProgressNode.tag) {
25985 case ClassComponent:
25986 // Loop through the component's update queue and see whether the component
25987 // has triggered any high priority updates
25988 var updateQueue = current$$1.updateQueue;
25989
25990 if (updateQueue !== null) {
25991 var update = updateQueue.firstUpdate;
25992
25993 while (update !== null) {
25994 var priorityLevel = update.priority;
25995
25996 if (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority) {
25997 if (componentsThatTriggeredHighPriSuspend === null) {
25998 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
25999 } else {
26000 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26001 }
26002
26003 break;
26004 }
26005
26006 update = update.next;
26007 }
26008 }
26009
26010 break;
26011
26012 case FunctionComponent:
26013 case ForwardRef:
26014 case SimpleMemoComponent:
26015 if (workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null) {
26016 var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether
26017 // the component has triggered any high pri updates
26018
26019 while (_update !== null) {
26020 var priority = _update.priority;
26021
26022 if (priority === UserBlockingPriority$2 || priority === ImmediatePriority) {
26023 if (componentsThatTriggeredHighPriSuspend === null) {
26024 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
26025 } else {
26026 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26027 }
26028
26029 break;
26030 }
26031
26032 if (_update.next === workInProgressNode.memoizedState.baseUpdate) {
26033 break;
26034 }
26035
26036 _update = _update.next;
26037 }
26038 }
26039
26040 break;
26041
26042 default:
26043 break;
26044 }
26045 }
26046
26047 workInProgressNode = workInProgressNode.return;
26048 }
26049 }
26050 }
26051}
26052
26053function flushSuspensePriorityWarningInDEV() {
26054 {
26055 if (componentsThatTriggeredHighPriSuspend !== null) {
26056 var componentNames = [];
26057 componentsThatTriggeredHighPriSuspend.forEach(function (name) {
26058 return componentNames.push(name);
26059 });
26060 componentsThatTriggeredHighPriSuspend = null;
26061
26062 if (componentNames.length > 0) {
26063 warningWithoutStack$1(false, '%s triggered a user-blocking update that suspended.' + '\n\n' + 'The fix is to split the update into multiple parts: a user-blocking ' + 'update to provide immediate feedback, and another update that ' + 'triggers the bulk of the changes.' + '\n\n' + 'Refer to the documentation for useSuspenseTransition to learn how ' + 'to implement this pattern.', // TODO: Add link to React docs with more information, once it exists
26064 componentNames.sort().join(', '));
26065 }
26066 }
26067 }
26068}
26069
26070function computeThreadID(root, expirationTime) {
26071 // Interaction threads are unique per root and expiration time.
26072 return expirationTime * 1000 + root.interactionThreadID;
26073}
26074
26075function markSpawnedWork(expirationTime) {
26076 if (!enableSchedulerTracing) {
26077 return;
26078 }
26079
26080 if (spawnedWorkDuringRender === null) {
26081 spawnedWorkDuringRender = [expirationTime];
26082 } else {
26083 spawnedWorkDuringRender.push(expirationTime);
26084 }
26085}
26086
26087function scheduleInteractions(root, expirationTime, interactions) {
26088 if (!enableSchedulerTracing) {
26089 return;
26090 }
26091
26092 if (interactions.size > 0) {
26093 var pendingInteractionMap = root.pendingInteractionMap;
26094 var pendingInteractions = pendingInteractionMap.get(expirationTime);
26095
26096 if (pendingInteractions != null) {
26097 interactions.forEach(function (interaction) {
26098 if (!pendingInteractions.has(interaction)) {
26099 // Update the pending async work count for previously unscheduled interaction.
26100 interaction.__count++;
26101 }
26102
26103 pendingInteractions.add(interaction);
26104 });
26105 } else {
26106 pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
26107
26108 interactions.forEach(function (interaction) {
26109 interaction.__count++;
26110 });
26111 }
26112
26113 var subscriber = __subscriberRef.current;
26114
26115 if (subscriber !== null) {
26116 var threadID = computeThreadID(root, expirationTime);
26117 subscriber.onWorkScheduled(interactions, threadID);
26118 }
26119 }
26120}
26121
26122function schedulePendingInteractions(root, expirationTime) {
26123 // This is called when work is scheduled on a root.
26124 // It associates the current interactions with the newly-scheduled expiration.
26125 // They will be restored when that expiration is later committed.
26126 if (!enableSchedulerTracing) {
26127 return;
26128 }
26129
26130 scheduleInteractions(root, expirationTime, __interactionsRef.current);
26131}
26132
26133function startWorkOnPendingInteractions(root, expirationTime) {
26134 // This is called when new work is started on a root.
26135 if (!enableSchedulerTracing) {
26136 return;
26137 } // Determine which interactions this batch of work currently includes, So that
26138 // we can accurately attribute time spent working on it, And so that cascading
26139 // work triggered during the render phase will be associated with it.
26140
26141
26142 var interactions = new Set();
26143 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26144 if (scheduledExpirationTime >= expirationTime) {
26145 scheduledInteractions.forEach(function (interaction) {
26146 return interactions.add(interaction);
26147 });
26148 }
26149 }); // Store the current set of interactions on the FiberRoot for a few reasons:
26150 // We can re-use it in hot functions like renderRoot() without having to
26151 // recalculate it. We will also use it in commitWork() to pass to any Profiler
26152 // onRender() hooks. This also provides DevTools with a way to access it when
26153 // the onCommitRoot() hook is called.
26154
26155 root.memoizedInteractions = interactions;
26156
26157 if (interactions.size > 0) {
26158 var subscriber = __subscriberRef.current;
26159
26160 if (subscriber !== null) {
26161 var threadID = computeThreadID(root, expirationTime);
26162
26163 try {
26164 subscriber.onWorkStarted(interactions, threadID);
26165 } catch (error) {
26166 // If the subscriber throws, rethrow it in a separate task
26167 scheduleCallback(ImmediatePriority, function () {
26168 throw error;
26169 });
26170 }
26171 }
26172 }
26173}
26174
26175function finishPendingInteractions(root, committedExpirationTime) {
26176 if (!enableSchedulerTracing) {
26177 return;
26178 }
26179
26180 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
26181 var subscriber;
26182
26183 try {
26184 subscriber = __subscriberRef.current;
26185
26186 if (subscriber !== null && root.memoizedInteractions.size > 0) {
26187 var threadID = computeThreadID(root, committedExpirationTime);
26188 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
26189 }
26190 } catch (error) {
26191 // If the subscriber throws, rethrow it in a separate task
26192 scheduleCallback(ImmediatePriority, function () {
26193 throw error;
26194 });
26195 } finally {
26196 // Clear completed interactions from the pending Map.
26197 // Unless the render was suspended or cascading work was scheduled,
26198 // In which case– leave pending interactions until the subsequent render.
26199 var pendingInteractionMap = root.pendingInteractionMap;
26200 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26201 // Only decrement the pending interaction count if we're done.
26202 // If there's still work at the current priority,
26203 // That indicates that we are waiting for suspense data.
26204 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
26205 pendingInteractionMap.delete(scheduledExpirationTime);
26206 scheduledInteractions.forEach(function (interaction) {
26207 interaction.__count--;
26208
26209 if (subscriber !== null && interaction.__count === 0) {
26210 try {
26211 subscriber.onInteractionScheduledWorkCompleted(interaction);
26212 } catch (error) {
26213 // If the subscriber throws, rethrow it in a separate task
26214 scheduleCallback(ImmediatePriority, function () {
26215 throw error;
26216 });
26217 }
26218 }
26219 });
26220 }
26221 });
26222 }
26223}
26224
26225var onCommitFiberRoot = null;
26226var onCommitFiberUnmount = null;
26227var hasLoggedError = false;
26228var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
26229function injectInternals(internals) {
26230 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
26231 // No DevTools
26232 return false;
26233 }
26234
26235 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
26236
26237 if (hook.isDisabled) {
26238 // This isn't a real property on the hook, but it can be set to opt out
26239 // of DevTools integration and associated warnings and logs.
26240 // https://github.com/facebook/react/issues/3877
26241 return true;
26242 }
26243
26244 if (!hook.supportsFiber) {
26245 {
26246 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');
26247 } // DevTools exists, even though it doesn't support Fiber.
26248
26249
26250 return true;
26251 }
26252
26253 try {
26254 var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
26255
26256 onCommitFiberRoot = function (root, expirationTime) {
26257 try {
26258 var didError = (root.current.effectTag & DidCapture) === DidCapture;
26259
26260 if (enableProfilerTimer) {
26261 var currentTime = requestCurrentTime();
26262 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
26263 hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
26264 } else {
26265 hook.onCommitFiberRoot(rendererID, root, undefined, didError);
26266 }
26267 } catch (err) {
26268 if (true && !hasLoggedError) {
26269 hasLoggedError = true;
26270 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26271 }
26272 }
26273 };
26274
26275 onCommitFiberUnmount = function (fiber) {
26276 try {
26277 hook.onCommitFiberUnmount(rendererID, fiber);
26278 } catch (err) {
26279 if (true && !hasLoggedError) {
26280 hasLoggedError = true;
26281 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26282 }
26283 }
26284 };
26285 } catch (err) {
26286 // Catch all errors because it is unsafe to throw during initialization.
26287 {
26288 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
26289 }
26290 } // DevTools exists
26291
26292
26293 return true;
26294}
26295function onCommitRoot(root, expirationTime) {
26296 if (typeof onCommitFiberRoot === 'function') {
26297 onCommitFiberRoot(root, expirationTime);
26298 }
26299}
26300function onCommitUnmount(fiber) {
26301 if (typeof onCommitFiberUnmount === 'function') {
26302 onCommitFiberUnmount(fiber);
26303 }
26304}
26305
26306var hasBadMapPolyfill;
26307
26308{
26309 hasBadMapPolyfill = false;
26310
26311 try {
26312 var nonExtensibleObject = Object.preventExtensions({});
26313 var testMap = new Map([[nonExtensibleObject, null]]);
26314 var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
26315 // https://github.com/rollup/rollup/issues/1771
26316 // TODO: we can remove these if Rollup fixes the bug.
26317
26318 testMap.set(0, 0);
26319 testSet.add(0);
26320 } catch (e) {
26321 // TODO: Consider warning about bad polyfills
26322 hasBadMapPolyfill = true;
26323 }
26324}
26325
26326var debugCounter = 1;
26327
26328function FiberNode(tag, pendingProps, key, mode) {
26329 // Instance
26330 this.tag = tag;
26331 this.key = key;
26332 this.elementType = null;
26333 this.type = null;
26334 this.stateNode = null; // Fiber
26335
26336 this.return = null;
26337 this.child = null;
26338 this.sibling = null;
26339 this.index = 0;
26340 this.ref = null;
26341 this.pendingProps = pendingProps;
26342 this.memoizedProps = null;
26343 this.updateQueue = null;
26344 this.memoizedState = null;
26345 this.dependencies = null;
26346 this.mode = mode; // Effects
26347
26348 this.effectTag = NoEffect;
26349 this.nextEffect = null;
26350 this.firstEffect = null;
26351 this.lastEffect = null;
26352 this.expirationTime = NoWork;
26353 this.childExpirationTime = NoWork;
26354 this.alternate = null;
26355
26356 if (enableProfilerTimer) {
26357 // Note: The following is done to avoid a v8 performance cliff.
26358 //
26359 // Initializing the fields below to smis and later updating them with
26360 // double values will cause Fibers to end up having separate shapes.
26361 // This behavior/bug has something to do with Object.preventExtension().
26362 // Fortunately this only impacts DEV builds.
26363 // Unfortunately it makes React unusably slow for some applications.
26364 // To work around this, initialize the fields below with doubles.
26365 //
26366 // Learn more about this here:
26367 // https://github.com/facebook/react/issues/14365
26368 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
26369 this.actualDuration = Number.NaN;
26370 this.actualStartTime = Number.NaN;
26371 this.selfBaseDuration = Number.NaN;
26372 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
26373 // This won't trigger the performance cliff mentioned above,
26374 // and it simplifies other profiler code (including DevTools).
26375
26376 this.actualDuration = 0;
26377 this.actualStartTime = -1;
26378 this.selfBaseDuration = 0;
26379 this.treeBaseDuration = 0;
26380 } // This is normally DEV-only except www when it adds listeners.
26381 // TODO: remove the User Timing integration in favor of Root Events.
26382
26383
26384 if (enableUserTimingAPI) {
26385 this._debugID = debugCounter++;
26386 this._debugIsCurrentlyTiming = false;
26387 }
26388
26389 {
26390 this._debugSource = null;
26391 this._debugOwner = null;
26392 this._debugNeedsRemount = false;
26393 this._debugHookTypes = null;
26394
26395 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
26396 Object.preventExtensions(this);
26397 }
26398 }
26399} // This is a constructor function, rather than a POJO constructor, still
26400// please ensure we do the following:
26401// 1) Nobody should add any instance methods on this. Instance methods can be
26402// more difficult to predict when they get optimized and they are almost
26403// never inlined properly in static compilers.
26404// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
26405// always know when it is a fiber.
26406// 3) We might want to experiment with using numeric keys since they are easier
26407// to optimize in a non-JIT environment.
26408// 4) We can easily go from a constructor to a createFiber object literal if that
26409// is faster.
26410// 5) It should be easy to port this to a C struct and keep a C implementation
26411// compatible.
26412
26413
26414var createFiber = function (tag, pendingProps, key, mode) {
26415 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
26416 return new FiberNode(tag, pendingProps, key, mode);
26417};
26418
26419function shouldConstruct(Component) {
26420 var prototype = Component.prototype;
26421 return !!(prototype && prototype.isReactComponent);
26422}
26423
26424function isSimpleFunctionComponent(type) {
26425 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
26426}
26427function resolveLazyComponentTag(Component) {
26428 if (typeof Component === 'function') {
26429 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
26430 } else if (Component !== undefined && Component !== null) {
26431 var $$typeof = Component.$$typeof;
26432
26433 if ($$typeof === REACT_FORWARD_REF_TYPE) {
26434 return ForwardRef;
26435 }
26436
26437 if ($$typeof === REACT_MEMO_TYPE) {
26438 return MemoComponent;
26439 }
26440 }
26441
26442 return IndeterminateComponent;
26443} // This is used to create an alternate fiber to do work on.
26444
26445function createWorkInProgress(current, pendingProps, expirationTime) {
26446 var workInProgress = current.alternate;
26447
26448 if (workInProgress === null) {
26449 // We use a double buffering pooling technique because we know that we'll
26450 // only ever need at most two versions of a tree. We pool the "other" unused
26451 // node that we're free to reuse. This is lazily created to avoid allocating
26452 // extra objects for things that are never updated. It also allow us to
26453 // reclaim the extra memory if needed.
26454 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
26455 workInProgress.elementType = current.elementType;
26456 workInProgress.type = current.type;
26457 workInProgress.stateNode = current.stateNode;
26458
26459 {
26460 // DEV-only fields
26461 workInProgress._debugID = current._debugID;
26462 workInProgress._debugSource = current._debugSource;
26463 workInProgress._debugOwner = current._debugOwner;
26464 workInProgress._debugHookTypes = current._debugHookTypes;
26465 }
26466
26467 workInProgress.alternate = current;
26468 current.alternate = workInProgress;
26469 } else {
26470 workInProgress.pendingProps = pendingProps; // We already have an alternate.
26471 // Reset the effect tag.
26472
26473 workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
26474
26475 workInProgress.nextEffect = null;
26476 workInProgress.firstEffect = null;
26477 workInProgress.lastEffect = null;
26478
26479 if (enableProfilerTimer) {
26480 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
26481 // This prevents time from endlessly accumulating in new commits.
26482 // This has the downside of resetting values for different priority renders,
26483 // But works for yielding (the common case) and should support resuming.
26484 workInProgress.actualDuration = 0;
26485 workInProgress.actualStartTime = -1;
26486 }
26487 }
26488
26489 workInProgress.childExpirationTime = current.childExpirationTime;
26490 workInProgress.expirationTime = current.expirationTime;
26491 workInProgress.child = current.child;
26492 workInProgress.memoizedProps = current.memoizedProps;
26493 workInProgress.memoizedState = current.memoizedState;
26494 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26495 // it cannot be shared with the current fiber.
26496
26497 var currentDependencies = current.dependencies;
26498 workInProgress.dependencies = currentDependencies === null ? null : {
26499 expirationTime: currentDependencies.expirationTime,
26500 firstContext: currentDependencies.firstContext,
26501 responders: currentDependencies.responders
26502 }; // These will be overridden during the parent's reconciliation
26503
26504 workInProgress.sibling = current.sibling;
26505 workInProgress.index = current.index;
26506 workInProgress.ref = current.ref;
26507
26508 if (enableProfilerTimer) {
26509 workInProgress.selfBaseDuration = current.selfBaseDuration;
26510 workInProgress.treeBaseDuration = current.treeBaseDuration;
26511 }
26512
26513 {
26514 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
26515
26516 switch (workInProgress.tag) {
26517 case IndeterminateComponent:
26518 case FunctionComponent:
26519 case SimpleMemoComponent:
26520 workInProgress.type = resolveFunctionForHotReloading(current.type);
26521 break;
26522
26523 case ClassComponent:
26524 workInProgress.type = resolveClassForHotReloading(current.type);
26525 break;
26526
26527 case ForwardRef:
26528 workInProgress.type = resolveForwardRefForHotReloading(current.type);
26529 break;
26530
26531 default:
26532 break;
26533 }
26534 }
26535
26536 return workInProgress;
26537} // Used to reuse a Fiber for a second pass.
26538
26539function resetWorkInProgress(workInProgress, renderExpirationTime) {
26540 // This resets the Fiber to what createFiber or createWorkInProgress would
26541 // have set the values to before during the first pass. Ideally this wouldn't
26542 // be necessary but unfortunately many code paths reads from the workInProgress
26543 // when they should be reading from current and writing to workInProgress.
26544 // We assume pendingProps, index, key, ref, return are still untouched to
26545 // avoid doing another reconciliation.
26546 // Reset the effect tag but keep any Placement tags, since that's something
26547 // that child fiber is setting, not the reconciliation.
26548 workInProgress.effectTag &= Placement; // The effect list is no longer valid.
26549
26550 workInProgress.nextEffect = null;
26551 workInProgress.firstEffect = null;
26552 workInProgress.lastEffect = null;
26553 var current = workInProgress.alternate;
26554
26555 if (current === null) {
26556 // Reset to createFiber's initial values.
26557 workInProgress.childExpirationTime = NoWork;
26558 workInProgress.expirationTime = renderExpirationTime;
26559 workInProgress.child = null;
26560 workInProgress.memoizedProps = null;
26561 workInProgress.memoizedState = null;
26562 workInProgress.updateQueue = null;
26563 workInProgress.dependencies = null;
26564
26565 if (enableProfilerTimer) {
26566 // Note: We don't reset the actualTime counts. It's useful to accumulate
26567 // actual time across multiple render passes.
26568 workInProgress.selfBaseDuration = 0;
26569 workInProgress.treeBaseDuration = 0;
26570 }
26571 } else {
26572 // Reset to the cloned values that createWorkInProgress would've.
26573 workInProgress.childExpirationTime = current.childExpirationTime;
26574 workInProgress.expirationTime = current.expirationTime;
26575 workInProgress.child = current.child;
26576 workInProgress.memoizedProps = current.memoizedProps;
26577 workInProgress.memoizedState = current.memoizedState;
26578 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26579 // it cannot be shared with the current fiber.
26580
26581 var currentDependencies = current.dependencies;
26582 workInProgress.dependencies = currentDependencies === null ? null : {
26583 expirationTime: currentDependencies.expirationTime,
26584 firstContext: currentDependencies.firstContext,
26585 responders: currentDependencies.responders
26586 };
26587
26588 if (enableProfilerTimer) {
26589 // Note: We don't reset the actualTime counts. It's useful to accumulate
26590 // actual time across multiple render passes.
26591 workInProgress.selfBaseDuration = current.selfBaseDuration;
26592 workInProgress.treeBaseDuration = current.treeBaseDuration;
26593 }
26594 }
26595
26596 return workInProgress;
26597}
26598function createHostRootFiber(tag) {
26599 var mode;
26600
26601 if (tag === ConcurrentRoot) {
26602 mode = ConcurrentMode | BatchedMode | StrictMode;
26603 } else if (tag === BatchedRoot) {
26604 mode = BatchedMode | StrictMode;
26605 } else {
26606 mode = NoMode;
26607 }
26608
26609 if (enableProfilerTimer && isDevToolsPresent) {
26610 // Always collect profile timings when DevTools are present.
26611 // This enables DevTools to start capturing timing at any point–
26612 // Without some nodes in the tree having empty base times.
26613 mode |= ProfileMode;
26614 }
26615
26616 return createFiber(HostRoot, null, null, mode);
26617}
26618function createFiberFromTypeAndProps(type, // React$ElementType
26619key, pendingProps, owner, mode, expirationTime) {
26620 var fiber;
26621 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
26622
26623 var resolvedType = type;
26624
26625 if (typeof type === 'function') {
26626 if (shouldConstruct(type)) {
26627 fiberTag = ClassComponent;
26628
26629 {
26630 resolvedType = resolveClassForHotReloading(resolvedType);
26631 }
26632 } else {
26633 {
26634 resolvedType = resolveFunctionForHotReloading(resolvedType);
26635 }
26636 }
26637 } else if (typeof type === 'string') {
26638 fiberTag = HostComponent;
26639 } else {
26640 getTag: switch (type) {
26641 case REACT_FRAGMENT_TYPE:
26642 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
26643
26644 case REACT_CONCURRENT_MODE_TYPE:
26645 fiberTag = Mode;
26646 mode |= ConcurrentMode | BatchedMode | StrictMode;
26647 break;
26648
26649 case REACT_STRICT_MODE_TYPE:
26650 fiberTag = Mode;
26651 mode |= StrictMode;
26652 break;
26653
26654 case REACT_PROFILER_TYPE:
26655 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
26656
26657 case REACT_SUSPENSE_TYPE:
26658 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
26659
26660 case REACT_SUSPENSE_LIST_TYPE:
26661 return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
26662
26663 default:
26664 {
26665 if (typeof type === 'object' && type !== null) {
26666 switch (type.$$typeof) {
26667 case REACT_PROVIDER_TYPE:
26668 fiberTag = ContextProvider;
26669 break getTag;
26670
26671 case REACT_CONTEXT_TYPE:
26672 // This is a consumer
26673 fiberTag = ContextConsumer;
26674 break getTag;
26675
26676 case REACT_FORWARD_REF_TYPE:
26677 fiberTag = ForwardRef;
26678
26679 {
26680 resolvedType = resolveForwardRefForHotReloading(resolvedType);
26681 }
26682
26683 break getTag;
26684
26685 case REACT_MEMO_TYPE:
26686 fiberTag = MemoComponent;
26687 break getTag;
26688
26689 case REACT_LAZY_TYPE:
26690 fiberTag = LazyComponent;
26691 resolvedType = null;
26692 break getTag;
26693
26694 case REACT_FUNDAMENTAL_TYPE:
26695 if (enableFundamentalAPI) {
26696 return createFiberFromFundamental(type, pendingProps, mode, expirationTime, key);
26697 }
26698
26699 break;
26700
26701 case REACT_SCOPE_TYPE:
26702 if (enableScopeAPI) {
26703 return createFiberFromScope(type, pendingProps, mode, expirationTime, key);
26704 }
26705
26706 }
26707 }
26708
26709 var info = '';
26710
26711 {
26712 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
26713 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.';
26714 }
26715
26716 var ownerName = owner ? getComponentName(owner.type) : null;
26717
26718 if (ownerName) {
26719 info += '\n\nCheck the render method of `' + ownerName + '`.';
26720 }
26721 }
26722
26723 (function () {
26724 {
26725 {
26726 throw ReactError(Error("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));
26727 }
26728 }
26729 })();
26730 }
26731 }
26732 }
26733
26734 fiber = createFiber(fiberTag, pendingProps, key, mode);
26735 fiber.elementType = type;
26736 fiber.type = resolvedType;
26737 fiber.expirationTime = expirationTime;
26738 return fiber;
26739}
26740function createFiberFromElement(element, mode, expirationTime) {
26741 var owner = null;
26742
26743 {
26744 owner = element._owner;
26745 }
26746
26747 var type = element.type;
26748 var key = element.key;
26749 var pendingProps = element.props;
26750 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
26751
26752 {
26753 fiber._debugSource = element._source;
26754 fiber._debugOwner = element._owner;
26755 }
26756
26757 return fiber;
26758}
26759function createFiberFromFragment(elements, mode, expirationTime, key) {
26760 var fiber = createFiber(Fragment, elements, key, mode);
26761 fiber.expirationTime = expirationTime;
26762 return fiber;
26763}
26764function createFiberFromFundamental(fundamentalComponent, pendingProps, mode, expirationTime, key) {
26765 var fiber = createFiber(FundamentalComponent, pendingProps, key, mode);
26766 fiber.elementType = fundamentalComponent;
26767 fiber.type = fundamentalComponent;
26768 fiber.expirationTime = expirationTime;
26769 return fiber;
26770}
26771
26772function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) {
26773 var fiber = createFiber(ScopeComponent, pendingProps, key, mode);
26774 fiber.type = scope;
26775 fiber.elementType = scope;
26776 fiber.expirationTime = expirationTime;
26777 return fiber;
26778}
26779
26780function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
26781 {
26782 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
26783 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
26784 }
26785 }
26786
26787 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
26788
26789 fiber.elementType = REACT_PROFILER_TYPE;
26790 fiber.type = REACT_PROFILER_TYPE;
26791 fiber.expirationTime = expirationTime;
26792 return fiber;
26793}
26794
26795function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
26796 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
26797 // This needs to be fixed in getComponentName so that it relies on the tag
26798 // instead.
26799
26800 fiber.type = REACT_SUSPENSE_TYPE;
26801 fiber.elementType = REACT_SUSPENSE_TYPE;
26802 fiber.expirationTime = expirationTime;
26803 return fiber;
26804}
26805function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
26806 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
26807
26808 {
26809 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
26810 // This needs to be fixed in getComponentName so that it relies on the tag
26811 // instead.
26812 fiber.type = REACT_SUSPENSE_LIST_TYPE;
26813 }
26814
26815 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
26816 fiber.expirationTime = expirationTime;
26817 return fiber;
26818}
26819function createFiberFromText(content, mode, expirationTime) {
26820 var fiber = createFiber(HostText, content, null, mode);
26821 fiber.expirationTime = expirationTime;
26822 return fiber;
26823}
26824function createFiberFromHostInstanceForDeletion() {
26825 var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
26826
26827 fiber.elementType = 'DELETED';
26828 fiber.type = 'DELETED';
26829 return fiber;
26830}
26831function createFiberFromDehydratedFragment(dehydratedNode) {
26832 var fiber = createFiber(DehydratedFragment, null, null, NoMode);
26833 fiber.stateNode = dehydratedNode;
26834 return fiber;
26835}
26836function createFiberFromPortal(portal, mode, expirationTime) {
26837 var pendingProps = portal.children !== null ? portal.children : [];
26838 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
26839 fiber.expirationTime = expirationTime;
26840 fiber.stateNode = {
26841 containerInfo: portal.containerInfo,
26842 pendingChildren: null,
26843 // Used by persistent updates
26844 implementation: portal.implementation
26845 };
26846 return fiber;
26847} // Used for stashing WIP properties to replay failed work in DEV.
26848
26849function assignFiberPropertiesInDEV(target, source) {
26850 if (target === null) {
26851 // This Fiber's initial properties will always be overwritten.
26852 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
26853 target = createFiber(IndeterminateComponent, null, null, NoMode);
26854 } // This is intentionally written as a list of all properties.
26855 // We tried to use Object.assign() instead but this is called in
26856 // the hottest path, and Object.assign() was too slow:
26857 // https://github.com/facebook/react/issues/12502
26858 // This code is DEV-only so size is not a concern.
26859
26860
26861 target.tag = source.tag;
26862 target.key = source.key;
26863 target.elementType = source.elementType;
26864 target.type = source.type;
26865 target.stateNode = source.stateNode;
26866 target.return = source.return;
26867 target.child = source.child;
26868 target.sibling = source.sibling;
26869 target.index = source.index;
26870 target.ref = source.ref;
26871 target.pendingProps = source.pendingProps;
26872 target.memoizedProps = source.memoizedProps;
26873 target.updateQueue = source.updateQueue;
26874 target.memoizedState = source.memoizedState;
26875 target.dependencies = source.dependencies;
26876 target.mode = source.mode;
26877 target.effectTag = source.effectTag;
26878 target.nextEffect = source.nextEffect;
26879 target.firstEffect = source.firstEffect;
26880 target.lastEffect = source.lastEffect;
26881 target.expirationTime = source.expirationTime;
26882 target.childExpirationTime = source.childExpirationTime;
26883 target.alternate = source.alternate;
26884
26885 if (enableProfilerTimer) {
26886 target.actualDuration = source.actualDuration;
26887 target.actualStartTime = source.actualStartTime;
26888 target.selfBaseDuration = source.selfBaseDuration;
26889 target.treeBaseDuration = source.treeBaseDuration;
26890 }
26891
26892 target._debugID = source._debugID;
26893 target._debugSource = source._debugSource;
26894 target._debugOwner = source._debugOwner;
26895 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
26896 target._debugNeedsRemount = source._debugNeedsRemount;
26897 target._debugHookTypes = source._debugHookTypes;
26898 return target;
26899}
26900
26901function FiberRootNode(containerInfo, tag, hydrate) {
26902 this.tag = tag;
26903 this.current = null;
26904 this.containerInfo = containerInfo;
26905 this.pendingChildren = null;
26906 this.pingCache = null;
26907 this.finishedExpirationTime = NoWork;
26908 this.finishedWork = null;
26909 this.timeoutHandle = noTimeout;
26910 this.context = null;
26911 this.pendingContext = null;
26912 this.hydrate = hydrate;
26913 this.firstBatch = null;
26914 this.callbackNode = null;
26915 this.callbackPriority = NoPriority;
26916 this.firstPendingTime = NoWork;
26917 this.firstSuspendedTime = NoWork;
26918 this.lastSuspendedTime = NoWork;
26919 this.nextKnownPendingLevel = NoWork;
26920 this.lastPingedTime = NoWork;
26921 this.lastExpiredTime = NoWork;
26922
26923 if (enableSchedulerTracing) {
26924 this.interactionThreadID = unstable_getThreadID();
26925 this.memoizedInteractions = new Set();
26926 this.pendingInteractionMap = new Map();
26927 }
26928
26929 if (enableSuspenseCallback) {
26930 this.hydrationCallbacks = null;
26931 }
26932}
26933
26934function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
26935 var root = new FiberRootNode(containerInfo, tag, hydrate);
26936
26937 if (enableSuspenseCallback) {
26938 root.hydrationCallbacks = hydrationCallbacks;
26939 } // Cyclic construction. This cheats the type system right now because
26940 // stateNode is any.
26941
26942
26943 var uninitializedFiber = createHostRootFiber(tag);
26944 root.current = uninitializedFiber;
26945 uninitializedFiber.stateNode = root;
26946 return root;
26947}
26948function isRootSuspendedAtTime(root, expirationTime) {
26949 var firstSuspendedTime = root.firstSuspendedTime;
26950 var lastSuspendedTime = root.lastSuspendedTime;
26951 return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
26952}
26953function markRootSuspendedAtTime(root, expirationTime) {
26954 var firstSuspendedTime = root.firstSuspendedTime;
26955 var lastSuspendedTime = root.lastSuspendedTime;
26956
26957 if (firstSuspendedTime < expirationTime) {
26958 root.firstSuspendedTime = expirationTime;
26959 }
26960
26961 if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
26962 root.lastSuspendedTime = expirationTime;
26963 }
26964
26965 if (expirationTime <= root.lastPingedTime) {
26966 root.lastPingedTime = NoWork;
26967 }
26968
26969 if (expirationTime <= root.lastExpiredTime) {
26970 root.lastExpiredTime = NoWork;
26971 }
26972}
26973function markRootUpdatedAtTime(root, expirationTime) {
26974 // Update the range of pending times
26975 var firstPendingTime = root.firstPendingTime;
26976
26977 if (expirationTime > firstPendingTime) {
26978 root.firstPendingTime = expirationTime;
26979 } // Update the range of suspended times. Treat everything lower priority or
26980 // equal to this update as unsuspended.
26981
26982
26983 var firstSuspendedTime = root.firstSuspendedTime;
26984
26985 if (firstSuspendedTime !== NoWork) {
26986 if (expirationTime >= firstSuspendedTime) {
26987 // The entire suspended range is now unsuspended.
26988 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26989 } else if (expirationTime >= root.lastSuspendedTime) {
26990 root.lastSuspendedTime = expirationTime + 1;
26991 } // This is a pending level. Check if it's higher priority than the next
26992 // known pending level.
26993
26994
26995 if (expirationTime > root.nextKnownPendingLevel) {
26996 root.nextKnownPendingLevel = expirationTime;
26997 }
26998 }
26999}
27000function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
27001 // Update the range of pending times
27002 root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
27003 // equal to this update as unsuspended.
27004
27005 if (finishedExpirationTime <= root.lastSuspendedTime) {
27006 // The entire suspended range is now unsuspended.
27007 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
27008 } else if (finishedExpirationTime <= root.firstSuspendedTime) {
27009 // Part of the suspended range is now unsuspended. Narrow the range to
27010 // include everything between the unsuspended time (non-inclusive) and the
27011 // last suspended time.
27012 root.firstSuspendedTime = finishedExpirationTime - 1;
27013 }
27014
27015 if (finishedExpirationTime <= root.lastPingedTime) {
27016 // Clear the pinged time
27017 root.lastPingedTime = NoWork;
27018 }
27019
27020 if (finishedExpirationTime <= root.lastExpiredTime) {
27021 // Clear the expired time
27022 root.lastExpiredTime = NoWork;
27023 }
27024}
27025function markRootExpiredAtTime(root, expirationTime) {
27026 var lastExpiredTime = root.lastExpiredTime;
27027
27028 if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
27029 root.lastExpiredTime = expirationTime;
27030 }
27031}
27032
27033// This lets us hook into Fiber to debug what it's doing.
27034// See https://github.com/facebook/react/pull/8033.
27035// This is not part of the public API, not even for React DevTools.
27036// You may only inject a debugTool if you work on React Fiber itself.
27037var ReactFiberInstrumentation = {
27038 debugTool: null
27039};
27040var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
27041
27042var didWarnAboutNestedUpdates;
27043var didWarnAboutFindNodeInStrictMode;
27044
27045{
27046 didWarnAboutNestedUpdates = false;
27047 didWarnAboutFindNodeInStrictMode = {};
27048}
27049
27050function getContextForSubtree(parentComponent) {
27051 if (!parentComponent) {
27052 return emptyContextObject;
27053 }
27054
27055 var fiber = get(parentComponent);
27056 var parentContext = findCurrentUnmaskedContext(fiber);
27057
27058 if (fiber.tag === ClassComponent) {
27059 var Component = fiber.type;
27060
27061 if (isContextProvider(Component)) {
27062 return processChildContext(fiber, Component, parentContext);
27063 }
27064 }
27065
27066 return parentContext;
27067}
27068
27069function scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback) {
27070 {
27071 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
27072 didWarnAboutNestedUpdates = true;
27073 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');
27074 }
27075 }
27076
27077 var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
27078 // being called "element".
27079
27080 update.payload = {
27081 element: element
27082 };
27083 callback = callback === undefined ? null : callback;
27084
27085 if (callback !== null) {
27086 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
27087 update.callback = callback;
27088 }
27089
27090 enqueueUpdate(current$$1, update);
27091 scheduleWork(current$$1, expirationTime);
27092 return expirationTime;
27093}
27094
27095function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback) {
27096 // TODO: If this is a nested container, this won't be the root.
27097 var current$$1 = container.current;
27098
27099 {
27100 if (ReactFiberInstrumentation_1.debugTool) {
27101 if (current$$1.alternate === null) {
27102 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
27103 } else if (element === null) {
27104 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
27105 } else {
27106 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
27107 }
27108 }
27109 }
27110
27111 var context = getContextForSubtree(parentComponent);
27112
27113 if (container.context === null) {
27114 container.context = context;
27115 } else {
27116 container.pendingContext = context;
27117 }
27118
27119 return scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback);
27120}
27121
27122function findHostInstance(component) {
27123 var fiber = get(component);
27124
27125 if (fiber === undefined) {
27126 if (typeof component.render === 'function') {
27127 (function () {
27128 {
27129 {
27130 throw ReactError(Error("Unable to find node on an unmounted component."));
27131 }
27132 }
27133 })();
27134 } else {
27135 (function () {
27136 {
27137 {
27138 throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
27139 }
27140 }
27141 })();
27142 }
27143 }
27144
27145 var hostFiber = findCurrentHostFiber(fiber);
27146
27147 if (hostFiber === null) {
27148 return null;
27149 }
27150
27151 return hostFiber.stateNode;
27152}
27153
27154function findHostInstanceWithWarning(component, methodName) {
27155 {
27156 var fiber = get(component);
27157
27158 if (fiber === undefined) {
27159 if (typeof component.render === 'function') {
27160 (function () {
27161 {
27162 {
27163 throw ReactError(Error("Unable to find node on an unmounted component."));
27164 }
27165 }
27166 })();
27167 } else {
27168 (function () {
27169 {
27170 {
27171 throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
27172 }
27173 }
27174 })();
27175 }
27176 }
27177
27178 var hostFiber = findCurrentHostFiber(fiber);
27179
27180 if (hostFiber === null) {
27181 return null;
27182 }
27183
27184 if (hostFiber.mode & StrictMode) {
27185 var componentName = getComponentName(fiber.type) || 'Component';
27186
27187 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
27188 didWarnAboutFindNodeInStrictMode[componentName] = true;
27189
27190 if (fiber.mode & StrictMode) {
27191 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. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
27192 } else {
27193 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. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
27194 }
27195 }
27196 }
27197
27198 return hostFiber.stateNode;
27199 }
27200
27201 return findHostInstance(component);
27202}
27203
27204function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
27205 return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
27206}
27207function updateContainer(element, container, parentComponent, callback) {
27208 var current$$1 = container.current;
27209 var currentTime = requestCurrentTime();
27210
27211 {
27212 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
27213 if ('undefined' !== typeof jest) {
27214 warnIfUnmockedScheduler(current$$1);
27215 warnIfNotScopedWithMatchingAct(current$$1);
27216 }
27217 }
27218
27219 var suspenseConfig = requestCurrentSuspenseConfig();
27220 var expirationTime = computeExpirationForFiber(currentTime, current$$1, suspenseConfig);
27221 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback);
27222}
27223function getPublicRootInstance(container) {
27224 var containerFiber = container.current;
27225
27226 if (!containerFiber.child) {
27227 return null;
27228 }
27229
27230 switch (containerFiber.child.tag) {
27231 case HostComponent:
27232 return getPublicInstance(containerFiber.child.stateNode);
27233
27234 default:
27235 return containerFiber.child.stateNode;
27236 }
27237}
27238function attemptSynchronousHydration$1(fiber) {
27239 switch (fiber.tag) {
27240 case HostRoot:
27241 var root = fiber.stateNode;
27242
27243 if (root.hydrate) {
27244 // Flush the first scheduled "update".
27245 flushRoot(root, root.firstPendingTime);
27246 }
27247
27248 break;
27249
27250 case SuspenseComponent:
27251 flushSync(function () {
27252 return scheduleWork(fiber, Sync);
27253 });
27254 break;
27255 }
27256}
27257function findHostInstanceWithNoPortals(fiber) {
27258 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
27259
27260 if (hostFiber === null) {
27261 return null;
27262 }
27263
27264 if (hostFiber.tag === FundamentalComponent) {
27265 return hostFiber.stateNode.instance;
27266 }
27267
27268 return hostFiber.stateNode;
27269}
27270
27271var shouldSuspendImpl = function (fiber) {
27272 return false;
27273};
27274
27275function shouldSuspend(fiber) {
27276 return shouldSuspendImpl(fiber);
27277}
27278var overrideHookState = null;
27279var overrideProps = null;
27280var scheduleUpdate = null;
27281var setSuspenseHandler = null;
27282
27283{
27284 var copyWithSetImpl = function (obj, path, idx, value) {
27285 if (idx >= path.length) {
27286 return value;
27287 }
27288
27289 var key = path[idx];
27290 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
27291
27292 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
27293 return updated;
27294 };
27295
27296 var copyWithSet = function (obj, path, value) {
27297 return copyWithSetImpl(obj, path, 0, value);
27298 }; // Support DevTools editable values for useState and useReducer.
27299
27300
27301 overrideHookState = function (fiber, id, path, value) {
27302 // For now, the "id" of stateful hooks is just the stateful hook index.
27303 // This may change in the future with e.g. nested hooks.
27304 var currentHook = fiber.memoizedState;
27305
27306 while (currentHook !== null && id > 0) {
27307 currentHook = currentHook.next;
27308 id--;
27309 }
27310
27311 if (currentHook !== null) {
27312 var newState = copyWithSet(currentHook.memoizedState, path, value);
27313 currentHook.memoizedState = newState;
27314 currentHook.baseState = newState; // We aren't actually adding an update to the queue,
27315 // because there is no update we can add for useReducer hooks that won't trigger an error.
27316 // (There's no appropriate action type for DevTools overrides.)
27317 // As a result though, React will see the scheduled update as a noop and bailout.
27318 // Shallow cloning props works as a workaround for now to bypass the bailout check.
27319
27320 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
27321 scheduleWork(fiber, Sync);
27322 }
27323 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
27324
27325
27326 overrideProps = function (fiber, path, value) {
27327 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
27328
27329 if (fiber.alternate) {
27330 fiber.alternate.pendingProps = fiber.pendingProps;
27331 }
27332
27333 scheduleWork(fiber, Sync);
27334 };
27335
27336 scheduleUpdate = function (fiber) {
27337 scheduleWork(fiber, Sync);
27338 };
27339
27340 setSuspenseHandler = function (newShouldSuspendImpl) {
27341 shouldSuspendImpl = newShouldSuspendImpl;
27342 };
27343}
27344
27345function injectIntoDevTools(devToolsConfig) {
27346 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
27347 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
27348 return injectInternals(_assign({}, devToolsConfig, {
27349 overrideHookState: overrideHookState,
27350 overrideProps: overrideProps,
27351 setSuspenseHandler: setSuspenseHandler,
27352 scheduleUpdate: scheduleUpdate,
27353 currentDispatcherRef: ReactCurrentDispatcher,
27354 findHostInstanceByFiber: function (fiber) {
27355 var hostFiber = findCurrentHostFiber(fiber);
27356
27357 if (hostFiber === null) {
27358 return null;
27359 }
27360
27361 return hostFiber.stateNode;
27362 },
27363 findFiberByHostInstance: function (instance) {
27364 if (!findFiberByHostInstance) {
27365 // Might not be implemented by the renderer.
27366 return null;
27367 }
27368
27369 return findFiberByHostInstance(instance);
27370 },
27371 // React Refresh
27372 findHostInstancesForRefresh: findHostInstancesForRefresh,
27373 scheduleRefresh: scheduleRefresh,
27374 scheduleRoot: scheduleRoot,
27375 setRefreshHandler: setRefreshHandler,
27376 // Enables DevTools to append owner stacks to error messages in DEV mode.
27377 getCurrentFiber: function () {
27378 return current;
27379 }
27380 }));
27381}
27382
27383// This file intentionally does *not* have the Flow annotation.
27384// Don't add it. See `./inline-typed.js` for an explanation.
27385
27386function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
27387implementation) {
27388 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
27389 return {
27390 // This tag allow us to uniquely identify this as a React Portal
27391 $$typeof: REACT_PORTAL_TYPE,
27392 key: key == null ? null : '' + key,
27393 children: children,
27394 containerInfo: containerInfo,
27395 implementation: implementation
27396 };
27397}
27398
27399// TODO: this is special because it gets imported during build.
27400
27401var ReactVersion = '16.10.2';
27402
27403// TODO: This type is shared between the reconciler and ReactDOM, but will
27404// eventually be lifted out to the renderer.
27405setAttemptSynchronousHydration(attemptSynchronousHydration$1);
27406var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
27407var topLevelUpdateWarnings;
27408var warnOnInvalidCallback;
27409var didWarnAboutUnstableCreatePortal = false;
27410
27411{
27412 if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
27413 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
27414 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
27415 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');
27416 }
27417
27418 topLevelUpdateWarnings = function (container) {
27419 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
27420 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
27421
27422 if (hostInstance) {
27423 !(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;
27424 }
27425 }
27426
27427 var isRootRenderedBySomeReact = !!container._reactRootContainer;
27428 var rootEl = getReactRootElementInContainer(container);
27429 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
27430 !(!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;
27431 !(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;
27432 };
27433
27434 warnOnInvalidCallback = function (callback, callerName) {
27435 !(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;
27436 };
27437}
27438
27439setRestoreImplementation(restoreControlledState$$1);
27440
27441function ReactBatch(root) {
27442 var expirationTime = computeUniqueAsyncExpiration();
27443 this._expirationTime = expirationTime;
27444 this._root = root;
27445 this._next = null;
27446 this._callbacks = null;
27447 this._didComplete = false;
27448 this._hasChildren = false;
27449 this._children = null;
27450 this._defer = true;
27451}
27452
27453ReactBatch.prototype.render = function (children) {
27454 var _this = this;
27455
27456 (function () {
27457 if (!_this._defer) {
27458 {
27459 throw ReactError(Error("batch.render: Cannot render a batch that already committed."));
27460 }
27461 }
27462 })();
27463
27464 this._hasChildren = true;
27465 this._children = children;
27466 var internalRoot = this._root._internalRoot;
27467 var expirationTime = this._expirationTime;
27468 var work = new ReactWork();
27469 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, null, work._onCommit);
27470 return work;
27471};
27472
27473ReactBatch.prototype.then = function (onComplete) {
27474 if (this._didComplete) {
27475 onComplete();
27476 return;
27477 }
27478
27479 var callbacks = this._callbacks;
27480
27481 if (callbacks === null) {
27482 callbacks = this._callbacks = [];
27483 }
27484
27485 callbacks.push(onComplete);
27486};
27487
27488ReactBatch.prototype.commit = function () {
27489 var _this2 = this;
27490
27491 var internalRoot = this._root._internalRoot;
27492 var firstBatch = internalRoot.firstBatch;
27493
27494 (function () {
27495 if (!(_this2._defer && firstBatch !== null)) {
27496 {
27497 throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27498 }
27499 }
27500 })();
27501
27502 if (!this._hasChildren) {
27503 // This batch is empty. Return.
27504 this._next = null;
27505 this._defer = false;
27506 return;
27507 }
27508
27509 var expirationTime = this._expirationTime; // Ensure this is the first batch in the list.
27510
27511 if (firstBatch !== this) {
27512 // This batch is not the earliest batch. We need to move it to the front.
27513 // Update its expiration time to be the expiration time of the earliest
27514 // batch, so that we can flush it without flushing the other batches.
27515 if (this._hasChildren) {
27516 expirationTime = this._expirationTime = firstBatch._expirationTime; // Rendering this batch again ensures its children will be the final state
27517 // when we flush (updates are processed in insertion order: last
27518 // update wins).
27519 // TODO: This forces a restart. Should we print a warning?
27520
27521 this.render(this._children);
27522 } // Remove the batch from the list.
27523
27524
27525 var previous = null;
27526 var batch = firstBatch;
27527
27528 while (batch !== this) {
27529 previous = batch;
27530 batch = batch._next;
27531 }
27532
27533 (function () {
27534 if (!(previous !== null)) {
27535 {
27536 throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27537 }
27538 }
27539 })();
27540
27541 previous._next = batch._next; // Add it to the front.
27542
27543 this._next = firstBatch;
27544 firstBatch = internalRoot.firstBatch = this;
27545 } // Synchronously flush all the work up to this batch's expiration time.
27546
27547
27548 this._defer = false;
27549 flushRoot(internalRoot, expirationTime); // Pop the batch from the list.
27550
27551 var next = this._next;
27552 this._next = null;
27553 firstBatch = internalRoot.firstBatch = next; // Append the next earliest batch's children to the update queue.
27554
27555 if (firstBatch !== null && firstBatch._hasChildren) {
27556 firstBatch.render(firstBatch._children);
27557 }
27558};
27559
27560ReactBatch.prototype._onComplete = function () {
27561 if (this._didComplete) {
27562 return;
27563 }
27564
27565 this._didComplete = true;
27566 var callbacks = this._callbacks;
27567
27568 if (callbacks === null) {
27569 return;
27570 } // TODO: Error handling.
27571
27572
27573 for (var i = 0; i < callbacks.length; i++) {
27574 var _callback = callbacks[i];
27575
27576 _callback();
27577 }
27578};
27579
27580function ReactWork() {
27581 this._callbacks = null;
27582 this._didCommit = false; // TODO: Avoid need to bind by replacing callbacks in the update queue with
27583 // list of Work objects.
27584
27585 this._onCommit = this._onCommit.bind(this);
27586}
27587
27588ReactWork.prototype.then = function (onCommit) {
27589 if (this._didCommit) {
27590 onCommit();
27591 return;
27592 }
27593
27594 var callbacks = this._callbacks;
27595
27596 if (callbacks === null) {
27597 callbacks = this._callbacks = [];
27598 }
27599
27600 callbacks.push(onCommit);
27601};
27602
27603ReactWork.prototype._onCommit = function () {
27604 if (this._didCommit) {
27605 return;
27606 }
27607
27608 this._didCommit = true;
27609 var callbacks = this._callbacks;
27610
27611 if (callbacks === null) {
27612 return;
27613 } // TODO: Error handling.
27614
27615
27616 for (var i = 0; i < callbacks.length; i++) {
27617 var _callback2 = callbacks[i];
27618
27619 (function () {
27620 if (!(typeof _callback2 === 'function')) {
27621 {
27622 throw ReactError(Error("Invalid argument passed as callback. Expected a function. Instead received: " + _callback2));
27623 }
27624 }
27625 })();
27626
27627 _callback2();
27628 }
27629};
27630
27631function createRootImpl(container, tag, options) {
27632 // Tag is either LegacyRoot or Concurrent Root
27633 var hydrate = options != null && options.hydrate === true;
27634 var hydrationCallbacks = options != null && options.hydrationOptions || null;
27635 var root = createContainer(container, tag, hydrate, hydrationCallbacks);
27636 markContainerAsRoot(root.current, container);
27637
27638 if (hydrate && tag !== LegacyRoot) {
27639 var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
27640 eagerlyTrapReplayableEvents(doc);
27641 }
27642
27643 return root;
27644}
27645
27646function ReactSyncRoot(container, tag, options) {
27647 this._internalRoot = createRootImpl(container, tag, options);
27648}
27649
27650function ReactRoot(container, options) {
27651 this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
27652}
27653
27654ReactRoot.prototype.render = ReactSyncRoot.prototype.render = function (children, callback) {
27655 var root = this._internalRoot;
27656 var work = new ReactWork();
27657 callback = callback === undefined ? null : callback;
27658
27659 {
27660 warnOnInvalidCallback(callback, 'render');
27661 }
27662
27663 if (callback !== null) {
27664 work.then(callback);
27665 }
27666
27667 updateContainer(children, root, null, work._onCommit);
27668 return work;
27669};
27670
27671ReactRoot.prototype.unmount = ReactSyncRoot.prototype.unmount = function (callback) {
27672 var root = this._internalRoot;
27673 var work = new ReactWork();
27674 callback = callback === undefined ? null : callback;
27675
27676 {
27677 warnOnInvalidCallback(callback, 'render');
27678 }
27679
27680 if (callback !== null) {
27681 work.then(callback);
27682 }
27683
27684 updateContainer(null, root, null, work._onCommit);
27685 return work;
27686}; // Sync roots cannot create batches. Only concurrent ones.
27687
27688
27689ReactRoot.prototype.createBatch = function () {
27690 var batch = new ReactBatch(this);
27691 var expirationTime = batch._expirationTime;
27692 var internalRoot = this._internalRoot;
27693 var firstBatch = internalRoot.firstBatch;
27694
27695 if (firstBatch === null) {
27696 internalRoot.firstBatch = batch;
27697 batch._next = null;
27698 } else {
27699 // Insert sorted by expiration time then insertion order
27700 var insertAfter = null;
27701 var insertBefore = firstBatch;
27702
27703 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
27704 insertAfter = insertBefore;
27705 insertBefore = insertBefore._next;
27706 }
27707
27708 batch._next = insertBefore;
27709
27710 if (insertAfter !== null) {
27711 insertAfter._next = batch;
27712 }
27713 }
27714
27715 return batch;
27716};
27717/**
27718 * True if the supplied DOM node is a valid node element.
27719 *
27720 * @param {?DOMElement} node The candidate DOM node.
27721 * @return {boolean} True if the DOM is a valid DOM node.
27722 * @internal
27723 */
27724
27725
27726function isValidContainer(node) {
27727 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 '));
27728}
27729
27730function getReactRootElementInContainer(container) {
27731 if (!container) {
27732 return null;
27733 }
27734
27735 if (container.nodeType === DOCUMENT_NODE) {
27736 return container.documentElement;
27737 } else {
27738 return container.firstChild;
27739 }
27740}
27741
27742function shouldHydrateDueToLegacyHeuristic(container) {
27743 var rootElement = getReactRootElementInContainer(container);
27744 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
27745}
27746
27747setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
27748var warnedAboutHydrateAPI = false;
27749
27750function legacyCreateRootFromDOMContainer(container, forceHydrate) {
27751 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
27752
27753 if (!shouldHydrate) {
27754 var warned = false;
27755 var rootSibling;
27756
27757 while (rootSibling = container.lastChild) {
27758 {
27759 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
27760 warned = true;
27761 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.');
27762 }
27763 }
27764
27765 container.removeChild(rootSibling);
27766 }
27767 }
27768
27769 {
27770 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
27771 warnedAboutHydrateAPI = true;
27772 lowPriorityWarningWithoutStack$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.');
27773 }
27774 } // Legacy roots are not batched.
27775
27776
27777 return new ReactSyncRoot(container, LegacyRoot, shouldHydrate ? {
27778 hydrate: true
27779 } : undefined);
27780}
27781
27782function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
27783 {
27784 topLevelUpdateWarnings(container);
27785 warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
27786 } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
27787 // member of intersection type." Whyyyyyy.
27788
27789
27790 var root = container._reactRootContainer;
27791 var fiberRoot;
27792
27793 if (!root) {
27794 // Initial mount
27795 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
27796 fiberRoot = root._internalRoot;
27797
27798 if (typeof callback === 'function') {
27799 var originalCallback = callback;
27800
27801 callback = function () {
27802 var instance = getPublicRootInstance(fiberRoot);
27803 originalCallback.call(instance);
27804 };
27805 } // Initial mount should not be batched.
27806
27807
27808 unbatchedUpdates(function () {
27809 updateContainer(children, fiberRoot, parentComponent, callback);
27810 });
27811 } else {
27812 fiberRoot = root._internalRoot;
27813
27814 if (typeof callback === 'function') {
27815 var _originalCallback = callback;
27816
27817 callback = function () {
27818 var instance = getPublicRootInstance(fiberRoot);
27819
27820 _originalCallback.call(instance);
27821 };
27822 } // Update
27823
27824
27825 updateContainer(children, fiberRoot, parentComponent, callback);
27826 }
27827
27828 return getPublicRootInstance(fiberRoot);
27829}
27830
27831function createPortal$$1(children, container) {
27832 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
27833
27834 (function () {
27835 if (!isValidContainer(container)) {
27836 {
27837 throw ReactError(Error("Target container is not a DOM element."));
27838 }
27839 }
27840 })(); // TODO: pass ReactDOM portal implementation as third argument
27841
27842
27843 return createPortal$1(children, container, null, key);
27844}
27845
27846var ReactDOM = {
27847 createPortal: createPortal$$1,
27848 findDOMNode: function (componentOrElement) {
27849 {
27850 var owner = ReactCurrentOwner.current;
27851
27852 if (owner !== null && owner.stateNode !== null) {
27853 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
27854 !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;
27855 owner.stateNode._warnedAboutRefsInRender = true;
27856 }
27857 }
27858
27859 if (componentOrElement == null) {
27860 return null;
27861 }
27862
27863 if (componentOrElement.nodeType === ELEMENT_NODE) {
27864 return componentOrElement;
27865 }
27866
27867 {
27868 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
27869 }
27870
27871 return findHostInstance(componentOrElement);
27872 },
27873 hydrate: function (element, container, callback) {
27874 (function () {
27875 if (!isValidContainer(container)) {
27876 {
27877 throw ReactError(Error("Target container is not a DOM element."));
27878 }
27879 }
27880 })();
27881
27882 {
27883 !!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;
27884 } // TODO: throw or warn if we couldn't hydrate?
27885
27886
27887 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
27888 },
27889 render: function (element, container, callback) {
27890 (function () {
27891 if (!isValidContainer(container)) {
27892 {
27893 throw ReactError(Error("Target container is not a DOM element."));
27894 }
27895 }
27896 })();
27897
27898 {
27899 !!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;
27900 }
27901
27902 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
27903 },
27904 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
27905 (function () {
27906 if (!isValidContainer(containerNode)) {
27907 {
27908 throw ReactError(Error("Target container is not a DOM element."));
27909 }
27910 }
27911 })();
27912
27913 (function () {
27914 if (!(parentComponent != null && has$1(parentComponent))) {
27915 {
27916 throw ReactError(Error("parentComponent must be a valid React Component"));
27917 }
27918 }
27919 })();
27920
27921 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
27922 },
27923 unmountComponentAtNode: function (container) {
27924 (function () {
27925 if (!isValidContainer(container)) {
27926 {
27927 throw ReactError(Error("unmountComponentAtNode(...): Target container is not a DOM element."));
27928 }
27929 }
27930 })();
27931
27932 {
27933 !!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;
27934 }
27935
27936 if (container._reactRootContainer) {
27937 {
27938 var rootEl = getReactRootElementInContainer(container);
27939 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
27940 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
27941 } // Unmount should not be batched.
27942
27943
27944 unbatchedUpdates(function () {
27945 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
27946 container._reactRootContainer = null;
27947 });
27948 }); // If you call unmountComponentAtNode twice in quick succession, you'll
27949 // get `true` twice. That's probably fine?
27950
27951 return true;
27952 } else {
27953 {
27954 var _rootEl = getReactRootElementInContainer(container);
27955
27956 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
27957
27958 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
27959 !!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;
27960 }
27961
27962 return false;
27963 }
27964 },
27965 // Temporary alias since we already shipped React 16 RC with it.
27966 // TODO: remove in React 17.
27967 unstable_createPortal: function () {
27968 if (!didWarnAboutUnstableCreatePortal) {
27969 didWarnAboutUnstableCreatePortal = true;
27970 lowPriorityWarningWithoutStack$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.');
27971 }
27972
27973 return createPortal$$1.apply(void 0, arguments);
27974 },
27975 unstable_batchedUpdates: batchedUpdates$1,
27976 // TODO remove this legacy method, unstable_discreteUpdates replaces it
27977 unstable_interactiveUpdates: function (fn, a, b, c) {
27978 flushDiscreteUpdates();
27979 return discreteUpdates$1(fn, a, b, c);
27980 },
27981 unstable_discreteUpdates: discreteUpdates$1,
27982 unstable_flushDiscreteUpdates: flushDiscreteUpdates,
27983 flushSync: flushSync,
27984 unstable_createRoot: createRoot,
27985 unstable_createSyncRoot: createSyncRoot,
27986 unstable_flushControlled: flushControlled,
27987 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
27988 // Keep in sync with ReactDOMUnstableNativeDependencies.js
27989 // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
27990 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
27991 }
27992};
27993
27994function createRoot(container, options) {
27995 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
27996
27997 (function () {
27998 if (!isValidContainer(container)) {
27999 {
28000 throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
28001 }
28002 }
28003 })();
28004
28005 warnIfReactDOMContainerInDEV(container);
28006 return new ReactRoot(container, options);
28007}
28008
28009function createSyncRoot(container, options) {
28010 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
28011
28012 (function () {
28013 if (!isValidContainer(container)) {
28014 {
28015 throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
28016 }
28017 }
28018 })();
28019
28020 warnIfReactDOMContainerInDEV(container);
28021 return new ReactSyncRoot(container, BatchedRoot, options);
28022}
28023
28024function warnIfReactDOMContainerInDEV(container) {
28025 {
28026 !!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;
28027 container._reactHasBeenPassedToCreateRootDEV = true;
28028 }
28029}
28030
28031if (enableStableConcurrentModeAPIs) {
28032 ReactDOM.createRoot = createRoot;
28033 ReactDOM.createSyncRoot = createSyncRoot;
28034}
28035
28036var foundDevTools = injectIntoDevTools({
28037 findFiberByHostInstance: getClosestInstanceFromNode,
28038 bundleType: 1,
28039 version: ReactVersion,
28040 rendererPackageName: 'react-dom'
28041});
28042
28043{
28044 if (!foundDevTools && canUseDOM && window.top === window.self) {
28045 // If we're in Chrome or Firefox, provide a download link if not installed.
28046 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
28047 var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
28048
28049 if (/^(https?|file):$/.test(protocol)) {
28050 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');
28051 }
28052 }
28053 }
28054}
28055
28056
28057
28058var ReactDOM$2 = Object.freeze({
28059 default: ReactDOM
28060});
28061
28062var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
28063
28064// TODO: decide on the top-level export form.
28065// This is hacky but makes it work with both Rollup and Jest.
28066
28067
28068var reactDom = ReactDOM$3.default || ReactDOM$3;
28069
28070return reactDom;
28071
28072})));