UNPKG

978 kBJavaScriptView Raw
1/** @license React v16.10.0
2 * react-dom.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactDOM = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18// Do not require this module directly! Use 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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget);
896
897 if (extractedEvents) {
898 events = accumulateInto(events, extractedEvents);
899 }
900 }
901 }
902
903 return events;
904}
905
906function runExtractedPluginEventsInBatch(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
907 var events = extractPluginEvents(topLevelType, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget);
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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, bookKeeping.eventSystemFlags, targetInst, nativeEvent, eventTarget);
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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, eventSystemFlags, targetInst, nativeEvent, nativeEventTarget) {
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 (function () {
18067 if (!suspenseInstance) {
18068 {
18069 throw ReactError(Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."));
18070 }
18071 }
18072 })();
18073
18074 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
18075}
18076
18077function popToNextHostParent(fiber) {
18078 var parent = fiber.return;
18079
18080 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
18081 parent = parent.return;
18082 }
18083
18084 hydrationParentFiber = parent;
18085}
18086
18087function popHydrationState(fiber) {
18088 if (!supportsHydration) {
18089 return false;
18090 }
18091
18092 if (fiber !== hydrationParentFiber) {
18093 // We're deeper than the current hydration context, inside an inserted
18094 // tree.
18095 return false;
18096 }
18097
18098 if (!isHydrating) {
18099 // If we're not currently hydrating but we're in a hydration context, then
18100 // we were an insertion and now need to pop up reenter hydration of our
18101 // siblings.
18102 popToNextHostParent(fiber);
18103 isHydrating = true;
18104 return false;
18105 }
18106
18107 var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
18108 // We only do this deeper than head and body since they tend to have random
18109 // other nodes in them. We also ignore components with pure text content in
18110 // side of them.
18111 // TODO: Better heuristic.
18112
18113 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
18114 var nextInstance = nextHydratableInstance;
18115
18116 while (nextInstance) {
18117 deleteHydratableInstance(fiber, nextInstance);
18118 nextInstance = getNextHydratableSibling(nextInstance);
18119 }
18120 }
18121
18122 popToNextHostParent(fiber);
18123
18124 if (fiber.tag === SuspenseComponent) {
18125 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
18126 } else {
18127 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
18128 }
18129
18130 return true;
18131}
18132
18133function resetHydrationState() {
18134 if (!supportsHydration) {
18135 return;
18136 }
18137
18138 hydrationParentFiber = null;
18139 nextHydratableInstance = null;
18140 isHydrating = false;
18141}
18142
18143var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
18144var didReceiveUpdate = false;
18145var didWarnAboutBadClass;
18146var didWarnAboutModulePatternComponent;
18147var didWarnAboutContextTypeOnFunctionComponent;
18148var didWarnAboutGetDerivedStateOnFunctionComponent;
18149var didWarnAboutFunctionRefs;
18150var didWarnAboutReassigningProps;
18151var didWarnAboutMaxDuration;
18152var didWarnAboutRevealOrder;
18153var didWarnAboutTailOptions;
18154var didWarnAboutDefaultPropsOnFunctionComponent;
18155
18156{
18157 didWarnAboutBadClass = {};
18158 didWarnAboutModulePatternComponent = {};
18159 didWarnAboutContextTypeOnFunctionComponent = {};
18160 didWarnAboutGetDerivedStateOnFunctionComponent = {};
18161 didWarnAboutFunctionRefs = {};
18162 didWarnAboutReassigningProps = false;
18163 didWarnAboutMaxDuration = false;
18164 didWarnAboutRevealOrder = {};
18165 didWarnAboutTailOptions = {};
18166 didWarnAboutDefaultPropsOnFunctionComponent = {};
18167}
18168
18169function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18170 if (current$$1 === null) {
18171 // If this is a fresh new component that hasn't been rendered yet, we
18172 // won't update its child set by applying minimal side-effects. Instead,
18173 // we will add them all to the child before it gets rendered. That means
18174 // we can optimize this reconciliation pass by not tracking side-effects.
18175 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18176 } else {
18177 // If the current child is the same as the work in progress, it means that
18178 // we haven't yet started any work on these children. Therefore, we use
18179 // the clone algorithm to create a copy of all the current children.
18180 // If we had any progressed work already, that is invalid at this point so
18181 // let's throw it out.
18182 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
18183 }
18184}
18185
18186function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18187 // This function is fork of reconcileChildren. It's used in cases where we
18188 // want to reconcile without matching against the existing set. This has the
18189 // effect of all current children being unmounted; even if the type and key
18190 // are the same, the old child is unmounted and a new child is created.
18191 //
18192 // To do this, we're going to go through the reconcile algorithm twice. In
18193 // the first pass, we schedule a deletion for all the current children by
18194 // passing null.
18195 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
18196 // pass null in place of where we usually pass the current child set. This has
18197 // the effect of remounting all children regardless of whether their their
18198 // identity matches.
18199
18200 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18201}
18202
18203function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18204 // TODO: current can be non-null here even if the component
18205 // hasn't yet mounted. This happens after the first render suspends.
18206 // We'll need to figure out if this is fine or can cause issues.
18207 {
18208 if (workInProgress.type !== workInProgress.elementType) {
18209 // Lazy component props can't be validated in createElement
18210 // because they're only guaranteed to be resolved here.
18211 var innerPropTypes = Component.propTypes;
18212
18213 if (innerPropTypes) {
18214 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18215 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18216 }
18217 }
18218 }
18219
18220 var render = Component.render;
18221 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
18222
18223 var nextChildren;
18224 prepareToReadContext(workInProgress, renderExpirationTime);
18225
18226 {
18227 ReactCurrentOwner$3.current = workInProgress;
18228 setCurrentPhase('render');
18229 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18230
18231 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18232 // Only double-render components with Hooks
18233 if (workInProgress.memoizedState !== null) {
18234 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18235 }
18236 }
18237
18238 setCurrentPhase(null);
18239 }
18240
18241 if (current$$1 !== null && !didReceiveUpdate) {
18242 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18243 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18244 } // React DevTools reads this flag.
18245
18246
18247 workInProgress.effectTag |= PerformedWork;
18248 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18249 return workInProgress.child;
18250}
18251
18252function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18253 if (current$$1 === null) {
18254 var type = Component.type;
18255
18256 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
18257 Component.defaultProps === undefined) {
18258 var resolvedType = type;
18259
18260 {
18261 resolvedType = resolveFunctionForHotReloading(type);
18262 } // If this is a plain function component without default props,
18263 // and with only the default shallow comparison, we upgrade it
18264 // to a SimpleMemoComponent to allow fast path updates.
18265
18266
18267 workInProgress.tag = SimpleMemoComponent;
18268 workInProgress.type = resolvedType;
18269
18270 {
18271 validateFunctionComponentInDev(workInProgress, type);
18272 }
18273
18274 return updateSimpleMemoComponent(current$$1, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
18275 }
18276
18277 {
18278 var innerPropTypes = type.propTypes;
18279
18280 if (innerPropTypes) {
18281 // Inner memo component props aren't currently validated in createElement.
18282 // We could move it there, but we'd still need this for lazy code path.
18283 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18284 'prop', getComponentName(type), getCurrentFiberStackInDev);
18285 }
18286 }
18287
18288 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
18289 child.ref = workInProgress.ref;
18290 child.return = workInProgress;
18291 workInProgress.child = child;
18292 return child;
18293 }
18294
18295 {
18296 var _type = Component.type;
18297 var _innerPropTypes = _type.propTypes;
18298
18299 if (_innerPropTypes) {
18300 // Inner memo component props aren't currently validated in createElement.
18301 // We could move it there, but we'd still need this for lazy code path.
18302 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
18303 'prop', getComponentName(_type), getCurrentFiberStackInDev);
18304 }
18305 }
18306
18307 var currentChild = current$$1.child; // This is always exactly one child
18308
18309 if (updateExpirationTime < renderExpirationTime) {
18310 // This will be the props with resolved defaultProps,
18311 // unlike current.memoizedProps which will be the unresolved ones.
18312 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
18313
18314 var compare = Component.compare;
18315 compare = compare !== null ? compare : shallowEqual;
18316
18317 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
18318 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18319 }
18320 } // React DevTools reads this flag.
18321
18322
18323 workInProgress.effectTag |= PerformedWork;
18324 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
18325 newChild.ref = workInProgress.ref;
18326 newChild.return = workInProgress;
18327 workInProgress.child = newChild;
18328 return newChild;
18329}
18330
18331function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18332 // TODO: current can be non-null here even if the component
18333 // hasn't yet mounted. This happens when the inner render suspends.
18334 // We'll need to figure out if this is fine or can cause issues.
18335 {
18336 if (workInProgress.type !== workInProgress.elementType) {
18337 // Lazy component props can't be validated in createElement
18338 // because they're only guaranteed to be resolved here.
18339 var outerMemoType = workInProgress.elementType;
18340
18341 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
18342 // We warn when you define propTypes on lazy()
18343 // so let's just skip over it to find memo() outer wrapper.
18344 // Inner props for memo are validated later.
18345 outerMemoType = refineResolvedLazyComponent(outerMemoType);
18346 }
18347
18348 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
18349
18350 if (outerPropTypes) {
18351 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
18352 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
18353 } // Inner propTypes will be validated in the function component path.
18354
18355 }
18356 }
18357
18358 if (current$$1 !== null) {
18359 var prevProps = current$$1.memoizedProps;
18360
18361 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload:
18362 workInProgress.type === current$$1.type)) {
18363 didReceiveUpdate = false;
18364
18365 if (updateExpirationTime < renderExpirationTime) {
18366 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18367 }
18368 }
18369 }
18370
18371 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18372}
18373
18374function updateFragment(current$$1, workInProgress, renderExpirationTime) {
18375 var nextChildren = workInProgress.pendingProps;
18376 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18377 return workInProgress.child;
18378}
18379
18380function updateMode(current$$1, workInProgress, renderExpirationTime) {
18381 var nextChildren = workInProgress.pendingProps.children;
18382 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18383 return workInProgress.child;
18384}
18385
18386function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
18387 if (enableProfilerTimer) {
18388 workInProgress.effectTag |= Update;
18389 }
18390
18391 var nextProps = workInProgress.pendingProps;
18392 var nextChildren = nextProps.children;
18393 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18394 return workInProgress.child;
18395}
18396
18397function markRef(current$$1, workInProgress) {
18398 var ref = workInProgress.ref;
18399
18400 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
18401 // Schedule a Ref effect
18402 workInProgress.effectTag |= Ref;
18403 }
18404}
18405
18406function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18407 {
18408 if (workInProgress.type !== workInProgress.elementType) {
18409 // Lazy component props can't be validated in createElement
18410 // because they're only guaranteed to be resolved here.
18411 var innerPropTypes = Component.propTypes;
18412
18413 if (innerPropTypes) {
18414 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18415 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18416 }
18417 }
18418 }
18419
18420 var context;
18421
18422 if (!disableLegacyContext) {
18423 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
18424 context = getMaskedContext(workInProgress, unmaskedContext);
18425 }
18426
18427 var nextChildren;
18428 prepareToReadContext(workInProgress, renderExpirationTime);
18429
18430 {
18431 ReactCurrentOwner$3.current = workInProgress;
18432 setCurrentPhase('render');
18433 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18434
18435 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18436 // Only double-render components with Hooks
18437 if (workInProgress.memoizedState !== null) {
18438 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18439 }
18440 }
18441
18442 setCurrentPhase(null);
18443 }
18444
18445 if (current$$1 !== null && !didReceiveUpdate) {
18446 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18447 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18448 } // React DevTools reads this flag.
18449
18450
18451 workInProgress.effectTag |= PerformedWork;
18452 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18453 return workInProgress.child;
18454}
18455
18456function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18457 {
18458 if (workInProgress.type !== workInProgress.elementType) {
18459 // Lazy component props can't be validated in createElement
18460 // because they're only guaranteed to be resolved here.
18461 var innerPropTypes = Component.propTypes;
18462
18463 if (innerPropTypes) {
18464 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18465 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18466 }
18467 }
18468 } // Push context providers early to prevent context stack mismatches.
18469 // During mounting we don't know the child context yet as the instance doesn't exist.
18470 // We will invalidate the child context in finishClassComponent() right after rendering.
18471
18472
18473 var hasContext;
18474
18475 if (isContextProvider(Component)) {
18476 hasContext = true;
18477 pushContextProvider(workInProgress);
18478 } else {
18479 hasContext = false;
18480 }
18481
18482 prepareToReadContext(workInProgress, renderExpirationTime);
18483 var instance = workInProgress.stateNode;
18484 var shouldUpdate;
18485
18486 if (instance === null) {
18487 if (current$$1 !== null) {
18488 // An class component without an instance only mounts if it suspended
18489 // inside a non- concurrent tree, in an inconsistent state. We want to
18490 // tree it like a new mount, even though an empty version of it already
18491 // committed. Disconnect the alternate pointers.
18492 current$$1.alternate = null;
18493 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18494
18495 workInProgress.effectTag |= Placement;
18496 } // In the initial pass we might need to construct the instance.
18497
18498
18499 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18500 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18501 shouldUpdate = true;
18502 } else if (current$$1 === null) {
18503 // In a resume, we'll already have an instance we can reuse.
18504 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18505 } else {
18506 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18507 }
18508
18509 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
18510
18511 {
18512 var inst = workInProgress.stateNode;
18513
18514 if (inst.props !== nextProps) {
18515 !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;
18516 didWarnAboutReassigningProps = true;
18517 }
18518 }
18519
18520 return nextUnitOfWork;
18521}
18522
18523function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
18524 // Refs should update even if shouldComponentUpdate returns false
18525 markRef(current$$1, workInProgress);
18526 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
18527
18528 if (!shouldUpdate && !didCaptureError) {
18529 // Context providers should defer to sCU for rendering
18530 if (hasContext) {
18531 invalidateContextProvider(workInProgress, Component, false);
18532 }
18533
18534 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18535 }
18536
18537 var instance = workInProgress.stateNode; // Rerender
18538
18539 ReactCurrentOwner$3.current = workInProgress;
18540 var nextChildren;
18541
18542 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
18543 // If we captured an error, but getDerivedStateFrom catch is not defined,
18544 // unmount all the children. componentDidCatch will schedule an update to
18545 // re-render a fallback. This is temporary until we migrate everyone to
18546 // the new API.
18547 // TODO: Warn in a future release.
18548 nextChildren = null;
18549
18550 if (enableProfilerTimer) {
18551 stopProfilerTimerIfRunning(workInProgress);
18552 }
18553 } else {
18554 {
18555 setCurrentPhase('render');
18556 nextChildren = instance.render();
18557
18558 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18559 instance.render();
18560 }
18561
18562 setCurrentPhase(null);
18563 }
18564 } // React DevTools reads this flag.
18565
18566
18567 workInProgress.effectTag |= PerformedWork;
18568
18569 if (current$$1 !== null && didCaptureError) {
18570 // If we're recovering from an error, reconcile without reusing any of
18571 // the existing children. Conceptually, the normal children and the children
18572 // that are shown on error are two different sets, so we shouldn't reuse
18573 // normal children even if their identities match.
18574 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
18575 } else {
18576 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18577 } // Memoize state using the values we just used to render.
18578 // TODO: Restructure so we never read values from the instance.
18579
18580
18581 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
18582
18583 if (hasContext) {
18584 invalidateContextProvider(workInProgress, Component, true);
18585 }
18586
18587 return workInProgress.child;
18588}
18589
18590function pushHostRootContext(workInProgress) {
18591 var root = workInProgress.stateNode;
18592
18593 if (root.pendingContext) {
18594 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
18595 } else if (root.context) {
18596 // Should always be set
18597 pushTopLevelContextObject(workInProgress, root.context, false);
18598 }
18599
18600 pushHostContainer(workInProgress, root.containerInfo);
18601}
18602
18603function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
18604 pushHostRootContext(workInProgress);
18605 var updateQueue = workInProgress.updateQueue;
18606
18607 (function () {
18608 if (!(updateQueue !== null)) {
18609 {
18610 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."));
18611 }
18612 }
18613 })();
18614
18615 var nextProps = workInProgress.pendingProps;
18616 var prevState = workInProgress.memoizedState;
18617 var prevChildren = prevState !== null ? prevState.element : null;
18618 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
18619 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
18620 // being called "element".
18621
18622 var nextChildren = nextState.element;
18623
18624 if (nextChildren === prevChildren) {
18625 // If the state is the same as before, that's a bailout because we had
18626 // no work that expires at this time.
18627 resetHydrationState();
18628 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18629 }
18630
18631 var root = workInProgress.stateNode;
18632
18633 if (root.hydrate && enterHydrationState(workInProgress)) {
18634 // If we don't have any current children this might be the first pass.
18635 // We always try to hydrate. If this isn't a hydration pass there won't
18636 // be any children to hydrate which is effectively the same thing as
18637 // not hydrating.
18638 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18639 workInProgress.child = child;
18640 var node = child;
18641
18642 while (node) {
18643 // Mark each child as hydrating. This is a fast path to know whether this
18644 // tree is part of a hydrating tree. This is used to determine if a child
18645 // node has fully mounted yet, and for scheduling event replaying.
18646 // Conceptually this is similar to Placement in that a new subtree is
18647 // inserted into the React tree here. It just happens to not need DOM
18648 // mutations because it already exists.
18649 node.effectTag = node.effectTag & ~Placement | Hydrating;
18650 node = node.sibling;
18651 }
18652 } else {
18653 // Otherwise reset hydration state in case we aborted and resumed another
18654 // root.
18655 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18656 resetHydrationState();
18657 }
18658
18659 return workInProgress.child;
18660}
18661
18662function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
18663 pushHostContext(workInProgress);
18664
18665 if (current$$1 === null) {
18666 tryToClaimNextHydratableInstance(workInProgress);
18667 }
18668
18669 var type = workInProgress.type;
18670 var nextProps = workInProgress.pendingProps;
18671 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
18672 var nextChildren = nextProps.children;
18673 var isDirectTextChild = shouldSetTextContent(type, nextProps);
18674
18675 if (isDirectTextChild) {
18676 // We special case a direct text child of a host node. This is a common
18677 // case. We won't handle it as a reified child. We will instead handle
18678 // this in the host environment that also have access to this prop. That
18679 // avoids allocating another HostText fiber and traversing it.
18680 nextChildren = null;
18681 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
18682 // If we're switching from a direct text child to a normal child, or to
18683 // empty, we need to schedule the text content to be reset.
18684 workInProgress.effectTag |= ContentReset;
18685 }
18686
18687 markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden.
18688
18689 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
18690 if (enableSchedulerTracing) {
18691 markSpawnedWork(Never);
18692 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
18693
18694
18695 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
18696 return null;
18697 }
18698
18699 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18700 return workInProgress.child;
18701}
18702
18703function updateHostText(current$$1, workInProgress) {
18704 if (current$$1 === null) {
18705 tryToClaimNextHydratableInstance(workInProgress);
18706 } // Nothing to do here. This is terminal. We'll do the completion step
18707 // immediately after.
18708
18709
18710 return null;
18711}
18712
18713function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
18714 if (_current !== null) {
18715 // An lazy component only mounts if it suspended inside a non-
18716 // concurrent tree, in an inconsistent state. We want to treat it like
18717 // a new mount, even though an empty version of it already committed.
18718 // Disconnect the alternate pointers.
18719 _current.alternate = null;
18720 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18721
18722 workInProgress.effectTag |= Placement;
18723 }
18724
18725 var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
18726 // Cancel and resume right after we know the tag.
18727
18728 cancelWorkTimer(workInProgress);
18729 var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
18730
18731 workInProgress.type = Component;
18732 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
18733 startWorkTimer(workInProgress);
18734 var resolvedProps = resolveDefaultProps(Component, props);
18735 var child;
18736
18737 switch (resolvedTag) {
18738 case FunctionComponent:
18739 {
18740 {
18741 validateFunctionComponentInDev(workInProgress, Component);
18742 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
18743 }
18744
18745 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18746 break;
18747 }
18748
18749 case ClassComponent:
18750 {
18751 {
18752 workInProgress.type = Component = resolveClassForHotReloading(Component);
18753 }
18754
18755 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18756 break;
18757 }
18758
18759 case ForwardRef:
18760 {
18761 {
18762 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
18763 }
18764
18765 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18766 break;
18767 }
18768
18769 case MemoComponent:
18770 {
18771 {
18772 if (workInProgress.type !== workInProgress.elementType) {
18773 var outerPropTypes = Component.propTypes;
18774
18775 if (outerPropTypes) {
18776 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
18777 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18778 }
18779 }
18780 }
18781
18782 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
18783 updateExpirationTime, renderExpirationTime);
18784 break;
18785 }
18786
18787 default:
18788 {
18789 var hint = '';
18790
18791 {
18792 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
18793 hint = ' Did you wrap a component in React.lazy() more than once?';
18794 }
18795 } // This message intentionally doesn't mention ForwardRef or MemoComponent
18796 // because the fact that it's a separate type of work is an
18797 // implementation detail.
18798
18799
18800 (function () {
18801 {
18802 {
18803 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));
18804 }
18805 }
18806 })();
18807 }
18808 }
18809
18810 return child;
18811}
18812
18813function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
18814 if (_current !== null) {
18815 // An incomplete component only mounts if it suspended inside a non-
18816 // concurrent tree, in an inconsistent state. We want to treat it like
18817 // a new mount, even though an empty version of it already committed.
18818 // Disconnect the alternate pointers.
18819 _current.alternate = null;
18820 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18821
18822 workInProgress.effectTag |= Placement;
18823 } // Promote the fiber to a class and try rendering again.
18824
18825
18826 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
18827 // Push context providers early to prevent context stack mismatches.
18828 // During mounting we don't know the child context yet as the instance doesn't exist.
18829 // We will invalidate the child context in finishClassComponent() right after rendering.
18830
18831 var hasContext;
18832
18833 if (isContextProvider(Component)) {
18834 hasContext = true;
18835 pushContextProvider(workInProgress);
18836 } else {
18837 hasContext = false;
18838 }
18839
18840 prepareToReadContext(workInProgress, renderExpirationTime);
18841 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18842 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18843 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18844}
18845
18846function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
18847 if (_current !== null) {
18848 // An indeterminate component only mounts if it suspended inside a non-
18849 // concurrent tree, in an inconsistent state. We want to treat it like
18850 // a new mount, even though an empty version of it already committed.
18851 // Disconnect the alternate pointers.
18852 _current.alternate = null;
18853 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18854
18855 workInProgress.effectTag |= Placement;
18856 }
18857
18858 var props = workInProgress.pendingProps;
18859 var context;
18860
18861 if (!disableLegacyContext) {
18862 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
18863 context = getMaskedContext(workInProgress, unmaskedContext);
18864 }
18865
18866 prepareToReadContext(workInProgress, renderExpirationTime);
18867 var value;
18868
18869 {
18870 if (Component.prototype && typeof Component.prototype.render === 'function') {
18871 var componentName = getComponentName(Component) || 'Unknown';
18872
18873 if (!didWarnAboutBadClass[componentName]) {
18874 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);
18875 didWarnAboutBadClass[componentName] = true;
18876 }
18877 }
18878
18879 if (workInProgress.mode & StrictMode) {
18880 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
18881 }
18882
18883 ReactCurrentOwner$3.current = workInProgress;
18884 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18885 } // React DevTools reads this flag.
18886
18887
18888 workInProgress.effectTag |= PerformedWork;
18889
18890 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
18891 {
18892 var _componentName = getComponentName(Component) || 'Unknown';
18893
18894 if (!didWarnAboutModulePatternComponent[_componentName]) {
18895 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);
18896 didWarnAboutModulePatternComponent[_componentName] = true;
18897 }
18898 } // Proceed under the assumption that this is a class instance
18899
18900
18901 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
18902
18903 resetHooks(); // Push context providers early to prevent context stack mismatches.
18904 // During mounting we don't know the child context yet as the instance doesn't exist.
18905 // We will invalidate the child context in finishClassComponent() right after rendering.
18906
18907 var hasContext = false;
18908
18909 if (isContextProvider(Component)) {
18910 hasContext = true;
18911 pushContextProvider(workInProgress);
18912 } else {
18913 hasContext = false;
18914 }
18915
18916 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
18917 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
18918
18919 if (typeof getDerivedStateFromProps === 'function') {
18920 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
18921 }
18922
18923 adoptClassInstance(workInProgress, value);
18924 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
18925 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18926 } else {
18927 // Proceed under the assumption that this is a function component
18928 workInProgress.tag = FunctionComponent;
18929
18930 {
18931 if (disableLegacyContext && Component.contextTypes) {
18932 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentName(Component) || 'Unknown');
18933 }
18934
18935 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18936 // Only double-render components with Hooks
18937 if (workInProgress.memoizedState !== null) {
18938 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18939 }
18940 }
18941 }
18942
18943 reconcileChildren(null, workInProgress, value, renderExpirationTime);
18944
18945 {
18946 validateFunctionComponentInDev(workInProgress, Component);
18947 }
18948
18949 return workInProgress.child;
18950 }
18951}
18952
18953function validateFunctionComponentInDev(workInProgress, Component) {
18954 if (Component) {
18955 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
18956 }
18957
18958 if (workInProgress.ref !== null) {
18959 var info = '';
18960 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
18961
18962 if (ownerName) {
18963 info += '\n\nCheck the render method of `' + ownerName + '`.';
18964 }
18965
18966 var warningKey = ownerName || workInProgress._debugID || '';
18967 var debugSource = workInProgress._debugSource;
18968
18969 if (debugSource) {
18970 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
18971 }
18972
18973 if (!didWarnAboutFunctionRefs[warningKey]) {
18974 didWarnAboutFunctionRefs[warningKey] = true;
18975 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);
18976 }
18977 }
18978
18979 if (warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined) {
18980 var componentName = getComponentName(Component) || 'Unknown';
18981
18982 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
18983 warningWithoutStack$1(false, '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
18984 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
18985 }
18986 }
18987
18988 if (typeof Component.getDerivedStateFromProps === 'function') {
18989 var _componentName2 = getComponentName(Component) || 'Unknown';
18990
18991 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
18992 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', _componentName2);
18993 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
18994 }
18995 }
18996
18997 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
18998 var _componentName3 = getComponentName(Component) || 'Unknown';
18999
19000 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
19001 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName3);
19002 didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
19003 }
19004 }
19005}
19006
19007var SUSPENDED_MARKER = {
19008 dehydrated: null,
19009 retryTime: Never
19010};
19011
19012function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) {
19013 // If the context is telling us that we should show a fallback, and we're not
19014 // already showing content, then we should show the fallback instead.
19015 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current$$1 === null || current$$1.memoizedState !== null);
19016}
19017
19018function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
19019 var mode = workInProgress.mode;
19020 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
19021
19022 {
19023 if (shouldSuspend(workInProgress)) {
19024 workInProgress.effectTag |= DidCapture;
19025 }
19026 }
19027
19028 var suspenseContext = suspenseStackCursor.current;
19029 var nextDidTimeout = false;
19030 var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
19031
19032 if (didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress)) {
19033 // Something in this boundary's subtree already suspended. Switch to
19034 // rendering the fallback children.
19035 nextDidTimeout = true;
19036 workInProgress.effectTag &= ~DidCapture;
19037 } else {
19038 // Attempting the main content
19039 if (current$$1 === null || current$$1.memoizedState !== null) {
19040 // This is a new mount or this boundary is already showing a fallback state.
19041 // Mark this subtree context as having at least one invisible parent that could
19042 // handle the fallback state.
19043 // Boundaries without fallbacks or should be avoided are not considered since
19044 // they cannot handle preferred fallback states.
19045 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
19046 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
19047 }
19048 }
19049 }
19050
19051 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19052 pushSuspenseContext(workInProgress, suspenseContext);
19053
19054 {
19055 if ('maxDuration' in nextProps) {
19056 if (!didWarnAboutMaxDuration) {
19057 didWarnAboutMaxDuration = true;
19058 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
19059 }
19060 }
19061 } // This next part is a bit confusing. If the children timeout, we switch to
19062 // showing the fallback children in place of the "primary" children.
19063 // However, we don't want to delete the primary children because then their
19064 // state will be lost (both the React state and the host state, e.g.
19065 // uncontrolled form inputs). Instead we keep them mounted and hide them.
19066 // Both the fallback children AND the primary children are rendered at the
19067 // same time. Once the primary children are un-suspended, we can delete
19068 // the fallback children — don't need to preserve their state.
19069 //
19070 // The two sets of children are siblings in the host environment, but
19071 // semantically, for purposes of reconciliation, they are two separate sets.
19072 // So we store them using two fragment fibers.
19073 //
19074 // However, we want to avoid allocating extra fibers for every placeholder.
19075 // They're only necessary when the children time out, because that's the
19076 // only time when both sets are mounted.
19077 //
19078 // So, the extra fragment fibers are only used if the children time out.
19079 // Otherwise, we render the primary children directly. This requires some
19080 // custom reconciliation logic to preserve the state of the primary
19081 // children. It's essentially a very basic form of re-parenting.
19082
19083
19084 if (current$$1 === null) {
19085 if (enableSuspenseServerRenderer) {
19086 // If we're currently hydrating, try to hydrate this boundary.
19087 // But only if this has a fallback.
19088 if (nextProps.fallback !== undefined) {
19089 tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
19090
19091 var suspenseState = workInProgress.memoizedState;
19092
19093 if (suspenseState !== null) {
19094 var dehydrated = suspenseState.dehydrated;
19095
19096 if (dehydrated !== null) {
19097 return mountDehydratedSuspenseComponent(workInProgress, dehydrated, renderExpirationTime);
19098 }
19099 }
19100 }
19101 } // This is the initial mount. This branch is pretty simple because there's
19102 // no previous state that needs to be preserved.
19103
19104
19105 if (nextDidTimeout) {
19106 // Mount separate fragments for primary and fallback children.
19107 var nextFallbackChildren = nextProps.fallback;
19108 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
19109 primaryChildFragment.return = workInProgress;
19110
19111 if ((workInProgress.mode & BatchedMode) === NoMode) {
19112 // Outside of batched mode, we commit the effects from the
19113 // partially completed, timed-out tree, too.
19114 var progressedState = workInProgress.memoizedState;
19115 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
19116 primaryChildFragment.child = progressedPrimaryChild;
19117 var progressedChild = progressedPrimaryChild;
19118
19119 while (progressedChild !== null) {
19120 progressedChild.return = primaryChildFragment;
19121 progressedChild = progressedChild.sibling;
19122 }
19123 }
19124
19125 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
19126 fallbackChildFragment.return = workInProgress;
19127 primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
19128 // fallback children.
19129
19130 workInProgress.memoizedState = SUSPENDED_MARKER;
19131 workInProgress.child = primaryChildFragment;
19132 return fallbackChildFragment;
19133 } else {
19134 // Mount the primary children without an intermediate fragment fiber.
19135 var nextPrimaryChildren = nextProps.children;
19136 workInProgress.memoizedState = null;
19137 return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
19138 }
19139 } else {
19140 // This is an update. This branch is more complicated because we need to
19141 // ensure the state of the primary children is preserved.
19142 var prevState = current$$1.memoizedState;
19143
19144 if (prevState !== null) {
19145 if (enableSuspenseServerRenderer) {
19146 var _dehydrated = prevState.dehydrated;
19147
19148 if (_dehydrated !== null) {
19149 if (!didSuspend) {
19150 return updateDehydratedSuspenseComponent(current$$1, workInProgress, _dehydrated, prevState, renderExpirationTime);
19151 } else if (workInProgress.memoizedState !== null) {
19152 // Something suspended and we should still be in dehydrated mode.
19153 // Leave the existing child in place.
19154 workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there
19155 // but the normal suspense pass doesn't.
19156
19157 workInProgress.effectTag |= DidCapture;
19158 return null;
19159 } else {
19160 // Suspended but we should no longer be in dehydrated mode.
19161 // Therefore we now have to render the fallback. Wrap the children
19162 // in a fragment fiber to keep them separate from the fallback
19163 // children.
19164 var _nextFallbackChildren = nextProps.fallback;
19165
19166 var _primaryChildFragment = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19167 // going to render this fragment.
19168 null, mode, NoWork, null);
19169
19170 _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child
19171 // that we're not going to hydrate.
19172
19173 _primaryChildFragment.child = null;
19174
19175 if ((workInProgress.mode & BatchedMode) === NoMode) {
19176 // Outside of batched mode, we commit the effects from the
19177 // partially completed, timed-out tree, too.
19178 var _progressedChild = _primaryChildFragment.child = workInProgress.child;
19179
19180 while (_progressedChild !== null) {
19181 _progressedChild.return = _primaryChildFragment;
19182 _progressedChild = _progressedChild.sibling;
19183 }
19184 } else {
19185 // We will have dropped the effect list which contains the deletion.
19186 // We need to reconcile to delete the current child.
19187 reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
19188 } // Because primaryChildFragment is a new fiber that we're inserting as the
19189 // parent of a new tree, we need to set its treeBaseDuration.
19190
19191
19192 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19193 // treeBaseDuration is the sum of all the child tree base durations.
19194 var treeBaseDuration = 0;
19195 var hiddenChild = _primaryChildFragment.child;
19196
19197 while (hiddenChild !== null) {
19198 treeBaseDuration += hiddenChild.treeBaseDuration;
19199 hiddenChild = hiddenChild.sibling;
19200 }
19201
19202 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
19203 } // Create a fragment from the fallback children, too.
19204
19205
19206 var _fallbackChildFragment = createFiberFromFragment(_nextFallbackChildren, mode, renderExpirationTime, null);
19207
19208 _fallbackChildFragment.return = workInProgress;
19209 _primaryChildFragment.sibling = _fallbackChildFragment;
19210 _fallbackChildFragment.effectTag |= Placement;
19211 _primaryChildFragment.childExpirationTime = NoWork;
19212 workInProgress.memoizedState = SUSPENDED_MARKER;
19213 workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the
19214 // fallback children.
19215
19216 return _fallbackChildFragment;
19217 }
19218 }
19219 } // The current tree already timed out. That means each child set is
19220 // wrapped in a fragment fiber.
19221
19222
19223 var currentPrimaryChildFragment = current$$1.child;
19224 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
19225
19226 if (nextDidTimeout) {
19227 // Still timed out. Reuse the current primary children by cloning
19228 // its fragment. We're going to skip over these entirely.
19229 var _nextFallbackChildren2 = nextProps.fallback;
19230
19231 var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
19232
19233 _primaryChildFragment2.return = workInProgress;
19234
19235 if ((workInProgress.mode & BatchedMode) === NoMode) {
19236 // Outside of batched mode, we commit the effects from the
19237 // partially completed, timed-out tree, too.
19238 var _progressedState = workInProgress.memoizedState;
19239
19240 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
19241
19242 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
19243 _primaryChildFragment2.child = _progressedPrimaryChild;
19244 var _progressedChild2 = _progressedPrimaryChild;
19245
19246 while (_progressedChild2 !== null) {
19247 _progressedChild2.return = _primaryChildFragment2;
19248 _progressedChild2 = _progressedChild2.sibling;
19249 }
19250 }
19251 } // Because primaryChildFragment is a new fiber that we're inserting as the
19252 // parent of a new tree, we need to set its treeBaseDuration.
19253
19254
19255 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19256 // treeBaseDuration is the sum of all the child tree base durations.
19257 var _treeBaseDuration = 0;
19258 var _hiddenChild = _primaryChildFragment2.child;
19259
19260 while (_hiddenChild !== null) {
19261 _treeBaseDuration += _hiddenChild.treeBaseDuration;
19262 _hiddenChild = _hiddenChild.sibling;
19263 }
19264
19265 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
19266 } // Clone the fallback child fragment, too. These we'll continue
19267 // working on.
19268
19269
19270 var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2, currentFallbackChildFragment.expirationTime);
19271
19272 _fallbackChildFragment2.return = workInProgress;
19273 _primaryChildFragment2.sibling = _fallbackChildFragment2;
19274 _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19275 // fallback children.
19276
19277 workInProgress.memoizedState = SUSPENDED_MARKER;
19278 workInProgress.child = _primaryChildFragment2;
19279 return _fallbackChildFragment2;
19280 } else {
19281 // No longer suspended. Switch back to showing the primary children,
19282 // and remove the intermediate fragment fiber.
19283 var _nextPrimaryChildren = nextProps.children;
19284 var currentPrimaryChild = currentPrimaryChildFragment.child;
19285 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
19286 // children. Wait until the complete phase, after we've confirmed the
19287 // fallback is no longer needed.
19288 // TODO: Would it be better to store the fallback fragment on
19289 // the stateNode?
19290 // Continue rendering the children, like we normally do.
19291
19292 workInProgress.memoizedState = null;
19293 return workInProgress.child = primaryChild;
19294 }
19295 } else {
19296 // The current tree has not already timed out. That means the primary
19297 // children are not wrapped in a fragment fiber.
19298 var _currentPrimaryChild = current$$1.child;
19299
19300 if (nextDidTimeout) {
19301 // Timed out. Wrap the children in a fragment fiber to keep them
19302 // separate from the fallback children.
19303 var _nextFallbackChildren3 = nextProps.fallback;
19304
19305 var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19306 // going to render this fragment.
19307 null, mode, NoWork, null);
19308
19309 _primaryChildFragment3.return = workInProgress;
19310 _primaryChildFragment3.child = _currentPrimaryChild;
19311
19312 if (_currentPrimaryChild !== null) {
19313 _currentPrimaryChild.return = _primaryChildFragment3;
19314 } // Even though we're creating a new fiber, there are no new children,
19315 // because we're reusing an already mounted tree. So we don't need to
19316 // schedule a placement.
19317 // primaryChildFragment.effectTag |= Placement;
19318
19319
19320 if ((workInProgress.mode & BatchedMode) === NoMode) {
19321 // Outside of batched mode, we commit the effects from the
19322 // partially completed, timed-out tree, too.
19323 var _progressedState2 = workInProgress.memoizedState;
19324
19325 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
19326
19327 _primaryChildFragment3.child = _progressedPrimaryChild2;
19328 var _progressedChild3 = _progressedPrimaryChild2;
19329
19330 while (_progressedChild3 !== null) {
19331 _progressedChild3.return = _primaryChildFragment3;
19332 _progressedChild3 = _progressedChild3.sibling;
19333 }
19334 } // Because primaryChildFragment is a new fiber that we're inserting as the
19335 // parent of a new tree, we need to set its treeBaseDuration.
19336
19337
19338 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19339 // treeBaseDuration is the sum of all the child tree base durations.
19340 var _treeBaseDuration2 = 0;
19341 var _hiddenChild2 = _primaryChildFragment3.child;
19342
19343 while (_hiddenChild2 !== null) {
19344 _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
19345 _hiddenChild2 = _hiddenChild2.sibling;
19346 }
19347
19348 _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
19349 } // Create a fragment from the fallback children, too.
19350
19351
19352 var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
19353
19354 _fallbackChildFragment3.return = workInProgress;
19355 _primaryChildFragment3.sibling = _fallbackChildFragment3;
19356 _fallbackChildFragment3.effectTag |= Placement;
19357 _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19358 // fallback children.
19359
19360 workInProgress.memoizedState = SUSPENDED_MARKER;
19361 workInProgress.child = _primaryChildFragment3;
19362 return _fallbackChildFragment3;
19363 } else {
19364 // Still haven't timed out. Continue rendering the children, like we
19365 // normally do.
19366 workInProgress.memoizedState = null;
19367 var _nextPrimaryChildren2 = nextProps.children;
19368 return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
19369 }
19370 }
19371 }
19372}
19373
19374function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
19375 // We're now not suspended nor dehydrated.
19376 workInProgress.memoizedState = null; // Retry with the full children.
19377
19378 var nextProps = workInProgress.pendingProps;
19379 var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and
19380 // that the old child gets a Deletion effect.
19381 // We could also call forceUnmountCurrentAndReconcile.
19382
19383 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19384 return workInProgress.child;
19385}
19386
19387function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderExpirationTime) {
19388 // During the first pass, we'll bail out and not drill into the children.
19389 // Instead, we'll leave the content in place and try to hydrate it later.
19390 if ((workInProgress.mode & BatchedMode) === NoMode) {
19391 {
19392 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.');
19393 }
19394
19395 workInProgress.expirationTime = Sync;
19396 } else if (isSuspenseInstanceFallback(suspenseInstance)) {
19397 // This is a client-only boundary. Since we won't get any content from the server
19398 // for this, we need to schedule that at a higher priority based on when it would
19399 // have timed out. In theory we could render it in this pass but it would have the
19400 // wrong priority associated with it and will prevent hydration of parent path.
19401 // Instead, we'll leave work left on it to render it in a separate commit.
19402 // TODO This time should be the time at which the server rendered response that is
19403 // a parent to this boundary was displayed. However, since we currently don't have
19404 // a protocol to transfer that time, we'll just estimate it by using the current
19405 // time. This will mean that Suspense timeouts are slightly shifted to later than
19406 // they should be.
19407 var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content.
19408
19409 var newExpirationTime = computeAsyncExpiration(serverDisplayTime);
19410
19411 if (enableSchedulerTracing) {
19412 markSpawnedWork(newExpirationTime);
19413 }
19414
19415 workInProgress.expirationTime = newExpirationTime;
19416 } else {
19417 // We'll continue hydrating the rest at offscreen priority since we'll already
19418 // be showing the right content coming from the server, it is no rush.
19419 workInProgress.expirationTime = Never;
19420
19421 if (enableSchedulerTracing) {
19422 markSpawnedWork(Never);
19423 }
19424 }
19425
19426 return null;
19427}
19428
19429function updateDehydratedSuspenseComponent(current$$1, workInProgress, suspenseInstance, suspenseState, renderExpirationTime) {
19430 // We should never be hydrating at this point because it is the first pass,
19431 // but after we've already committed once.
19432 warnIfHydrating();
19433
19434 if ((workInProgress.mode & BatchedMode) === NoMode) {
19435 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19436 }
19437
19438 if (isSuspenseInstanceFallback(suspenseInstance)) {
19439 // This boundary is in a permanent fallback state. In this case, we'll never
19440 // get an update and we'll never be able to hydrate the final content. Let's just try the
19441 // client side render instead.
19442 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19443 } // We use childExpirationTime to indicate that a child might depend on context, so if
19444 // any context has changed, we need to treat is as if the input might have changed.
19445
19446
19447 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
19448
19449 if (didReceiveUpdate || hasContextChanged$$1) {
19450 // This boundary has changed since the first render. This means that we are now unable to
19451 // hydrate it. We might still be able to hydrate it using an earlier expiration time, if
19452 // we are rendering at lower expiration than sync.
19453 if (renderExpirationTime < Sync) {
19454 if (suspenseState.retryTime <= renderExpirationTime) {
19455 // This render is even higher pri than we've seen before, let's try again
19456 // at even higher pri.
19457 var attemptHydrationAtExpirationTime = renderExpirationTime + 1;
19458 suspenseState.retryTime = attemptHydrationAtExpirationTime;
19459 scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render.
19460 } else {// We have already tried to ping at a higher priority than we're rendering with
19461 // so if we got here, we must have failed to hydrate at those levels. We must
19462 // now give up. Instead, we're going to delete the whole subtree and instead inject
19463 // a new real Suspense boundary to take its place, which may render content
19464 // or fallback. This might suspend for a while and if it does we might still have
19465 // an opportunity to hydrate before this pass commits.
19466 }
19467 } // If we have scheduled higher pri work above, this will probably just abort the render
19468 // since we now have higher priority work, but in case it doesn't, we need to prepare to
19469 // render something, if we time out. Even if that requires us to delete everything and
19470 // skip hydration.
19471 // Delay having to do this as long as the suspense timeout allows us.
19472
19473
19474 renderDidSuspendDelayIfPossible();
19475 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19476 } else if (isSuspenseInstancePending(suspenseInstance)) {
19477 // This component is still pending more data from the server, so we can't hydrate its
19478 // content. We treat it as if this component suspended itself. It might seem as if
19479 // we could just try to render it client-side instead. However, this will perform a
19480 // lot of unnecessary work and is unlikely to complete since it often will suspend
19481 // on missing data anyway. Additionally, the server might be able to render more
19482 // than we can on the client yet. In that case we'd end up with more fallback states
19483 // on the client than if we just leave it alone. If the server times out or errors
19484 // these should update this boundary to the permanent Fallback state instead.
19485 // Mark it as having captured (i.e. suspended).
19486 workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
19487
19488 workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result.
19489
19490 registerSuspenseInstanceRetry(suspenseInstance, retryDehydratedSuspenseBoundary.bind(null, current$$1));
19491 return null;
19492 } else {
19493 // This is the first attempt.
19494 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance);
19495 var nextProps = workInProgress.pendingProps;
19496 var nextChildren = nextProps.children;
19497 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19498 var node = child;
19499
19500 while (node) {
19501 // Mark each child as hydrating. This is a fast path to know whether this
19502 // tree is part of a hydrating tree. This is used to determine if a child
19503 // node has fully mounted yet, and for scheduling event replaying.
19504 // Conceptually this is similar to Placement in that a new subtree is
19505 // inserted into the React tree here. It just happens to not need DOM
19506 // mutations because it already exists.
19507 node.effectTag |= Hydrating;
19508 node = node.sibling;
19509 }
19510
19511 workInProgress.child = child;
19512 return workInProgress.child;
19513 }
19514}
19515
19516function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
19517 // Mark any Suspense boundaries with fallbacks as having work to do.
19518 // If they were previously forced into fallbacks, they may now be able
19519 // to unblock.
19520 var node = firstChild;
19521
19522 while (node !== null) {
19523 if (node.tag === SuspenseComponent) {
19524 var state = node.memoizedState;
19525
19526 if (state !== null) {
19527 if (node.expirationTime < renderExpirationTime) {
19528 node.expirationTime = renderExpirationTime;
19529 }
19530
19531 var alternate = node.alternate;
19532
19533 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
19534 alternate.expirationTime = renderExpirationTime;
19535 }
19536
19537 scheduleWorkOnParentPath(node.return, renderExpirationTime);
19538 }
19539 } else if (node.child !== null) {
19540 node.child.return = node;
19541 node = node.child;
19542 continue;
19543 }
19544
19545 if (node === workInProgress) {
19546 return;
19547 }
19548
19549 while (node.sibling === null) {
19550 if (node.return === null || node.return === workInProgress) {
19551 return;
19552 }
19553
19554 node = node.return;
19555 }
19556
19557 node.sibling.return = node.return;
19558 node = node.sibling;
19559 }
19560}
19561
19562function findLastContentRow(firstChild) {
19563 // This is going to find the last row among these children that is already
19564 // showing content on the screen, as opposed to being in fallback state or
19565 // new. If a row has multiple Suspense boundaries, any of them being in the
19566 // fallback state, counts as the whole row being in a fallback state.
19567 // Note that the "rows" will be workInProgress, but any nested children
19568 // will still be current since we haven't rendered them yet. The mounted
19569 // order may not be the same as the new order. We use the new order.
19570 var row = firstChild;
19571 var lastContentRow = null;
19572
19573 while (row !== null) {
19574 var currentRow = row.alternate; // New rows can't be content rows.
19575
19576 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19577 lastContentRow = row;
19578 }
19579
19580 row = row.sibling;
19581 }
19582
19583 return lastContentRow;
19584}
19585
19586function validateRevealOrder(revealOrder) {
19587 {
19588 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
19589 didWarnAboutRevealOrder[revealOrder] = true;
19590
19591 if (typeof revealOrder === 'string') {
19592 switch (revealOrder.toLowerCase()) {
19593 case 'together':
19594 case 'forwards':
19595 case 'backwards':
19596 {
19597 warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
19598 break;
19599 }
19600
19601 case 'forward':
19602 case 'backward':
19603 {
19604 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());
19605 break;
19606 }
19607
19608 default:
19609 warning$1(false, '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19610 break;
19611 }
19612 } else {
19613 warning$1(false, '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19614 }
19615 }
19616 }
19617}
19618
19619function validateTailOptions(tailMode, revealOrder) {
19620 {
19621 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
19622 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
19623 didWarnAboutTailOptions[tailMode] = true;
19624 warning$1(false, '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
19625 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
19626 didWarnAboutTailOptions[tailMode] = true;
19627 warning$1(false, '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
19628 }
19629 }
19630 }
19631}
19632
19633function validateSuspenseListNestedChild(childSlot, index) {
19634 {
19635 var isArray = Array.isArray(childSlot);
19636 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
19637
19638 if (isArray || isIterable) {
19639 var type = isArray ? 'array' : 'iterable';
19640 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);
19641 return false;
19642 }
19643 }
19644
19645 return true;
19646}
19647
19648function validateSuspenseListChildren(children, revealOrder) {
19649 {
19650 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
19651 if (Array.isArray(children)) {
19652 for (var i = 0; i < children.length; i++) {
19653 if (!validateSuspenseListNestedChild(children[i], i)) {
19654 return;
19655 }
19656 }
19657 } else {
19658 var iteratorFn = getIteratorFn(children);
19659
19660 if (typeof iteratorFn === 'function') {
19661 var childrenIterator = iteratorFn.call(children);
19662
19663 if (childrenIterator) {
19664 var step = childrenIterator.next();
19665 var _i = 0;
19666
19667 for (; !step.done; step = childrenIterator.next()) {
19668 if (!validateSuspenseListNestedChild(step.value, _i)) {
19669 return;
19670 }
19671
19672 _i++;
19673 }
19674 }
19675 } else {
19676 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);
19677 }
19678 }
19679 }
19680 }
19681}
19682
19683function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
19684 var renderState = workInProgress.memoizedState;
19685
19686 if (renderState === null) {
19687 workInProgress.memoizedState = {
19688 isBackwards: isBackwards,
19689 rendering: null,
19690 last: lastContentRow,
19691 tail: tail,
19692 tailExpiration: 0,
19693 tailMode: tailMode
19694 };
19695 } else {
19696 // We can reuse the existing object from previous renders.
19697 renderState.isBackwards = isBackwards;
19698 renderState.rendering = null;
19699 renderState.last = lastContentRow;
19700 renderState.tail = tail;
19701 renderState.tailExpiration = 0;
19702 renderState.tailMode = tailMode;
19703 }
19704} // This can end up rendering this component multiple passes.
19705// The first pass splits the children fibers into two sets. A head and tail.
19706// We first render the head. If anything is in fallback state, we do another
19707// pass through beginWork to rerender all children (including the tail) with
19708// the force suspend context. If the first render didn't have anything in
19709// in fallback state. Then we render each row in the tail one-by-one.
19710// That happens in the completeWork phase without going back to beginWork.
19711
19712
19713function updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime) {
19714 var nextProps = workInProgress.pendingProps;
19715 var revealOrder = nextProps.revealOrder;
19716 var tailMode = nextProps.tail;
19717 var newChildren = nextProps.children;
19718 validateRevealOrder(revealOrder);
19719 validateTailOptions(tailMode, revealOrder);
19720 validateSuspenseListChildren(newChildren, revealOrder);
19721 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19722 var suspenseContext = suspenseStackCursor.current;
19723 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
19724
19725 if (shouldForceFallback) {
19726 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
19727 workInProgress.effectTag |= DidCapture;
19728 } else {
19729 var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect;
19730
19731 if (didSuspendBefore) {
19732 // If we previously forced a fallback, we need to schedule work
19733 // on any nested boundaries to let them know to try to render
19734 // again. This is the same as context updating.
19735 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
19736 }
19737
19738 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19739 }
19740
19741 pushSuspenseContext(workInProgress, suspenseContext);
19742
19743 if ((workInProgress.mode & BatchedMode) === NoMode) {
19744 // Outside of batched mode, SuspenseList doesn't work so we just
19745 // use make it a noop by treating it as the default revealOrder.
19746 workInProgress.memoizedState = null;
19747 } else {
19748 switch (revealOrder) {
19749 case 'forwards':
19750 {
19751 var lastContentRow = findLastContentRow(workInProgress.child);
19752 var tail;
19753
19754 if (lastContentRow === null) {
19755 // The whole list is part of the tail.
19756 // TODO: We could fast path by just rendering the tail now.
19757 tail = workInProgress.child;
19758 workInProgress.child = null;
19759 } else {
19760 // Disconnect the tail rows after the content row.
19761 // We're going to render them separately later.
19762 tail = lastContentRow.sibling;
19763 lastContentRow.sibling = null;
19764 }
19765
19766 initSuspenseListRenderState(workInProgress, false, // isBackwards
19767 tail, lastContentRow, tailMode);
19768 break;
19769 }
19770
19771 case 'backwards':
19772 {
19773 // We're going to find the first row that has existing content.
19774 // At the same time we're going to reverse the list of everything
19775 // we pass in the meantime. That's going to be our tail in reverse
19776 // order.
19777 var _tail = null;
19778 var row = workInProgress.child;
19779 workInProgress.child = null;
19780
19781 while (row !== null) {
19782 var currentRow = row.alternate; // New rows can't be content rows.
19783
19784 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19785 // This is the beginning of the main content.
19786 workInProgress.child = row;
19787 break;
19788 }
19789
19790 var nextRow = row.sibling;
19791 row.sibling = _tail;
19792 _tail = row;
19793 row = nextRow;
19794 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
19795
19796
19797 initSuspenseListRenderState(workInProgress, true, // isBackwards
19798 _tail, null, // last
19799 tailMode);
19800 break;
19801 }
19802
19803 case 'together':
19804 {
19805 initSuspenseListRenderState(workInProgress, false, // isBackwards
19806 null, // tail
19807 null, // last
19808 undefined);
19809 break;
19810 }
19811
19812 default:
19813 {
19814 // The default reveal order is the same as not having
19815 // a boundary.
19816 workInProgress.memoizedState = null;
19817 }
19818 }
19819 }
19820
19821 return workInProgress.child;
19822}
19823
19824function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
19825 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19826 var nextChildren = workInProgress.pendingProps;
19827
19828 if (current$$1 === null) {
19829 // Portals are special because we don't append the children during mount
19830 // but at commit. Therefore we need to track insertions which the normal
19831 // flow doesn't do during mount. This doesn't happen at the root because
19832 // the root always starts with a "current" with a null child.
19833 // TODO: Consider unifying this with how the root works.
19834 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19835 } else {
19836 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19837 }
19838
19839 return workInProgress.child;
19840}
19841
19842function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
19843 var providerType = workInProgress.type;
19844 var context = providerType._context;
19845 var newProps = workInProgress.pendingProps;
19846 var oldProps = workInProgress.memoizedProps;
19847 var newValue = newProps.value;
19848
19849 {
19850 var providerPropTypes = workInProgress.type.propTypes;
19851
19852 if (providerPropTypes) {
19853 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
19854 }
19855 }
19856
19857 pushProvider(workInProgress, newValue);
19858
19859 if (oldProps !== null) {
19860 var oldValue = oldProps.value;
19861 var changedBits = calculateChangedBits(context, newValue, oldValue);
19862
19863 if (changedBits === 0) {
19864 // No change. Bailout early if children are the same.
19865 if (oldProps.children === newProps.children && !hasContextChanged()) {
19866 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
19867 }
19868 } else {
19869 // The context value changed. Search for matching consumers and schedule
19870 // them to update.
19871 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
19872 }
19873 }
19874
19875 var newChildren = newProps.children;
19876 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19877 return workInProgress.child;
19878}
19879
19880var hasWarnedAboutUsingContextAsConsumer = false;
19881
19882function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
19883 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
19884 // DEV mode, we create a separate object for Context.Consumer that acts
19885 // like a proxy to Context. This proxy object adds unnecessary code in PROD
19886 // so we use the old behaviour (Context.Consumer references Context) to
19887 // reduce size and overhead. The separate object references context via
19888 // a property called "_context", which also gives us the ability to check
19889 // in DEV mode if this property exists or not and warn if it does not.
19890
19891 {
19892 if (context._context === undefined) {
19893 // This may be because it's a Context (rather than a Consumer).
19894 // Or it may be because it's older React where they're the same thing.
19895 // We only want to warn if we're sure it's a new React.
19896 if (context !== context.Consumer) {
19897 if (!hasWarnedAboutUsingContextAsConsumer) {
19898 hasWarnedAboutUsingContextAsConsumer = true;
19899 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?');
19900 }
19901 }
19902 } else {
19903 context = context._context;
19904 }
19905 }
19906
19907 var newProps = workInProgress.pendingProps;
19908 var render = newProps.children;
19909
19910 {
19911 !(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;
19912 }
19913
19914 prepareToReadContext(workInProgress, renderExpirationTime);
19915 var newValue = readContext(context, newProps.unstable_observedBits);
19916 var newChildren;
19917
19918 {
19919 ReactCurrentOwner$3.current = workInProgress;
19920 setCurrentPhase('render');
19921 newChildren = render(newValue);
19922 setCurrentPhase(null);
19923 } // React DevTools reads this flag.
19924
19925
19926 workInProgress.effectTag |= PerformedWork;
19927 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19928 return workInProgress.child;
19929}
19930
19931function updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime) {
19932 var fundamentalImpl = workInProgress.type.impl;
19933
19934 if (fundamentalImpl.reconcileChildren === false) {
19935 return null;
19936 }
19937
19938 var nextProps = workInProgress.pendingProps;
19939 var nextChildren = nextProps.children;
19940 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19941 return workInProgress.child;
19942}
19943
19944function updateScopeComponent(current$$1, workInProgress, renderExpirationTime) {
19945 var nextProps = workInProgress.pendingProps;
19946 var nextChildren = nextProps.children;
19947 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19948 return workInProgress.child;
19949}
19950
19951function markWorkInProgressReceivedUpdate() {
19952 didReceiveUpdate = true;
19953}
19954
19955function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
19956 cancelWorkTimer(workInProgress);
19957
19958 if (current$$1 !== null) {
19959 // Reuse previous dependencies
19960 workInProgress.dependencies = current$$1.dependencies;
19961 }
19962
19963 if (enableProfilerTimer) {
19964 // Don't update "base" render times for bailouts.
19965 stopProfilerTimerIfRunning(workInProgress);
19966 }
19967
19968 var updateExpirationTime = workInProgress.expirationTime;
19969
19970 if (updateExpirationTime !== NoWork) {
19971 markUnprocessedUpdateTime(updateExpirationTime);
19972 } // Check if the children have any pending work.
19973
19974
19975 var childExpirationTime = workInProgress.childExpirationTime;
19976
19977 if (childExpirationTime < renderExpirationTime) {
19978 // The children don't have any work either. We can skip them.
19979 // TODO: Once we add back resuming, we should check if the children are
19980 // a work-in-progress set. If so, we need to transfer their effects.
19981 return null;
19982 } else {
19983 // This fiber doesn't have work, but its subtree does. Clone the child
19984 // fibers and continue.
19985 cloneChildFibers(current$$1, workInProgress);
19986 return workInProgress.child;
19987 }
19988}
19989
19990function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
19991 {
19992 var returnFiber = oldWorkInProgress.return;
19993
19994 if (returnFiber === null) {
19995 throw new Error('Cannot swap the root fiber.');
19996 } // Disconnect from the old current.
19997 // It will get deleted.
19998
19999
20000 current$$1.alternate = null;
20001 oldWorkInProgress.alternate = null; // Connect to the new tree.
20002
20003 newWorkInProgress.index = oldWorkInProgress.index;
20004 newWorkInProgress.sibling = oldWorkInProgress.sibling;
20005 newWorkInProgress.return = oldWorkInProgress.return;
20006 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
20007
20008 if (oldWorkInProgress === returnFiber.child) {
20009 returnFiber.child = newWorkInProgress;
20010 } else {
20011 var prevSibling = returnFiber.child;
20012
20013 if (prevSibling === null) {
20014 throw new Error('Expected parent to have a child.');
20015 }
20016
20017 while (prevSibling.sibling !== oldWorkInProgress) {
20018 prevSibling = prevSibling.sibling;
20019
20020 if (prevSibling === null) {
20021 throw new Error('Expected to find the previous sibling.');
20022 }
20023 }
20024
20025 prevSibling.sibling = newWorkInProgress;
20026 } // Delete the old fiber and place the new one.
20027 // Since the old fiber is disconnected, we have to schedule it manually.
20028
20029
20030 var last = returnFiber.lastEffect;
20031
20032 if (last !== null) {
20033 last.nextEffect = current$$1;
20034 returnFiber.lastEffect = current$$1;
20035 } else {
20036 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
20037 }
20038
20039 current$$1.nextEffect = null;
20040 current$$1.effectTag = Deletion;
20041 newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
20042
20043 return newWorkInProgress;
20044 }
20045}
20046
20047function beginWork$1(current$$1, workInProgress, renderExpirationTime) {
20048 var updateExpirationTime = workInProgress.expirationTime;
20049
20050 {
20051 if (workInProgress._debugNeedsRemount && current$$1 !== null) {
20052 // This will restart the begin phase with a new fiber.
20053 return remountFiber(current$$1, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
20054 }
20055 }
20056
20057 if (current$$1 !== null) {
20058 var oldProps = current$$1.memoizedProps;
20059 var newProps = workInProgress.pendingProps;
20060
20061 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
20062 workInProgress.type !== current$$1.type)) {
20063 // If props or context changed, mark the fiber as having performed work.
20064 // This may be unset if the props are determined to be equal later (memo).
20065 didReceiveUpdate = true;
20066 } else if (updateExpirationTime < renderExpirationTime) {
20067 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
20068 // the begin phase. There's still some bookkeeping we that needs to be done
20069 // in this optimized path, mostly pushing stuff onto the stack.
20070
20071 switch (workInProgress.tag) {
20072 case HostRoot:
20073 pushHostRootContext(workInProgress);
20074 resetHydrationState();
20075 break;
20076
20077 case HostComponent:
20078 pushHostContext(workInProgress);
20079
20080 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
20081 if (enableSchedulerTracing) {
20082 markSpawnedWork(Never);
20083 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
20084
20085
20086 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
20087 return null;
20088 }
20089
20090 break;
20091
20092 case ClassComponent:
20093 {
20094 var Component = workInProgress.type;
20095
20096 if (isContextProvider(Component)) {
20097 pushContextProvider(workInProgress);
20098 }
20099
20100 break;
20101 }
20102
20103 case HostPortal:
20104 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
20105 break;
20106
20107 case ContextProvider:
20108 {
20109 var newValue = workInProgress.memoizedProps.value;
20110 pushProvider(workInProgress, newValue);
20111 break;
20112 }
20113
20114 case Profiler:
20115 if (enableProfilerTimer) {
20116 workInProgress.effectTag |= Update;
20117 }
20118
20119 break;
20120
20121 case SuspenseComponent:
20122 {
20123 var state = workInProgress.memoizedState;
20124
20125 if (state !== null) {
20126 if (enableSuspenseServerRenderer) {
20127 if (state.dehydrated !== null) {
20128 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
20129 // been unsuspended it has committed as a resolved Suspense component.
20130 // If it needs to be retried, it should have work scheduled on it.
20131
20132 workInProgress.effectTag |= DidCapture;
20133 break;
20134 }
20135 } // If this boundary is currently timed out, we need to decide
20136 // whether to retry the primary children, or to skip over it and
20137 // go straight to the fallback. Check the priority of the primary
20138 // child fragment.
20139
20140
20141 var primaryChildFragment = workInProgress.child;
20142 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
20143
20144 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
20145 // The primary children have pending work. Use the normal path
20146 // to attempt to render the primary children again.
20147 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20148 } else {
20149 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
20150 // priority. Bailout.
20151
20152 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20153
20154 if (child !== null) {
20155 // The fallback children have pending work. Skip over the
20156 // primary children and work on the fallback.
20157 return child.sibling;
20158 } else {
20159 return null;
20160 }
20161 }
20162 } else {
20163 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
20164 }
20165
20166 break;
20167 }
20168
20169 case SuspenseListComponent:
20170 {
20171 var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect;
20172 var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20173
20174 if (didSuspendBefore) {
20175 if (hasChildWork) {
20176 // If something was in fallback state last time, and we have all the
20177 // same children then we're still in progressive loading state.
20178 // Something might get unblocked by state updates or retries in the
20179 // tree which will affect the tail. So we need to use the normal
20180 // path to compute the correct tail.
20181 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20182 } // If none of the children had any work, that means that none of
20183 // them got retried so they'll still be blocked in the same way
20184 // as before. We can fast bail out.
20185
20186
20187 workInProgress.effectTag |= DidCapture;
20188 } // If nothing suspended before and we're rendering the same children,
20189 // then the tail doesn't matter. Anything new that suspends will work
20190 // in the "together" mode, so we can continue from the state we had.
20191
20192
20193 var renderState = workInProgress.memoizedState;
20194
20195 if (renderState !== null) {
20196 // Reset to the "together" mode in case we've started a different
20197 // update in the past but didn't complete it.
20198 renderState.rendering = null;
20199 renderState.tail = null;
20200 }
20201
20202 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
20203
20204 if (hasChildWork) {
20205 break;
20206 } else {
20207 // If none of the children had any work, that means that none of
20208 // them got retried so they'll still be blocked in the same way
20209 // as before. We can fast bail out.
20210 return null;
20211 }
20212 }
20213 }
20214
20215 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20216 } else {
20217 // An update was scheduled on this fiber, but there are no new props
20218 // nor legacy context. Set this to false. If an update queue or context
20219 // consumer produces a changed value, it will set this to true. Otherwise,
20220 // the component will assume the children have not changed and bail out.
20221 didReceiveUpdate = false;
20222 }
20223 } else {
20224 didReceiveUpdate = false;
20225 } // Before entering the begin phase, clear the expiration time.
20226
20227
20228 workInProgress.expirationTime = NoWork;
20229
20230 switch (workInProgress.tag) {
20231 case IndeterminateComponent:
20232 {
20233 return mountIndeterminateComponent(current$$1, workInProgress, workInProgress.type, renderExpirationTime);
20234 }
20235
20236 case LazyComponent:
20237 {
20238 var elementType = workInProgress.elementType;
20239 return mountLazyComponent(current$$1, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
20240 }
20241
20242 case FunctionComponent:
20243 {
20244 var _Component = workInProgress.type;
20245 var unresolvedProps = workInProgress.pendingProps;
20246 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
20247 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
20248 }
20249
20250 case ClassComponent:
20251 {
20252 var _Component2 = workInProgress.type;
20253 var _unresolvedProps = workInProgress.pendingProps;
20254
20255 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
20256
20257 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
20258 }
20259
20260 case HostRoot:
20261 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
20262
20263 case HostComponent:
20264 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
20265
20266 case HostText:
20267 return updateHostText(current$$1, workInProgress);
20268
20269 case SuspenseComponent:
20270 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20271
20272 case HostPortal:
20273 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
20274
20275 case ForwardRef:
20276 {
20277 var type = workInProgress.type;
20278 var _unresolvedProps2 = workInProgress.pendingProps;
20279
20280 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
20281
20282 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
20283 }
20284
20285 case Fragment:
20286 return updateFragment(current$$1, workInProgress, renderExpirationTime);
20287
20288 case Mode:
20289 return updateMode(current$$1, workInProgress, renderExpirationTime);
20290
20291 case Profiler:
20292 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
20293
20294 case ContextProvider:
20295 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
20296
20297 case ContextConsumer:
20298 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
20299
20300 case MemoComponent:
20301 {
20302 var _type2 = workInProgress.type;
20303 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
20304
20305 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
20306
20307 {
20308 if (workInProgress.type !== workInProgress.elementType) {
20309 var outerPropTypes = _type2.propTypes;
20310
20311 if (outerPropTypes) {
20312 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
20313 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
20314 }
20315 }
20316 }
20317
20318 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
20319 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
20320 }
20321
20322 case SimpleMemoComponent:
20323 {
20324 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
20325 }
20326
20327 case IncompleteClassComponent:
20328 {
20329 var _Component3 = workInProgress.type;
20330 var _unresolvedProps4 = workInProgress.pendingProps;
20331
20332 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
20333
20334 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
20335 }
20336
20337 case SuspenseListComponent:
20338 {
20339 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20340 }
20341
20342 case FundamentalComponent:
20343 {
20344 if (enableFundamentalAPI) {
20345 return updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime);
20346 }
20347
20348 break;
20349 }
20350
20351 case ScopeComponent:
20352 {
20353 if (enableScopeAPI) {
20354 return updateScopeComponent(current$$1, workInProgress, renderExpirationTime);
20355 }
20356
20357 break;
20358 }
20359 }
20360
20361 (function () {
20362 {
20363 {
20364 throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
20365 }
20366 }
20367 })();
20368}
20369
20370function createFundamentalStateInstance(currentFiber, props, impl, state) {
20371 return {
20372 currentFiber: currentFiber,
20373 impl: impl,
20374 instance: null,
20375 prevProps: null,
20376 props: props,
20377 state: state
20378 };
20379}
20380
20381function isFiberSuspenseAndTimedOut(fiber) {
20382 return fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
20383}
20384
20385function getSuspenseFallbackChild(fiber) {
20386 return fiber.child.sibling.child;
20387}
20388
20389function collectScopedNodes(node, fn, scopedNodes) {
20390 if (enableScopeAPI) {
20391 if (node.tag === HostComponent) {
20392 var _type = node.type,
20393 memoizedProps = node.memoizedProps;
20394
20395 if (fn(_type, memoizedProps) === true) {
20396 scopedNodes.push(getPublicInstance(node.stateNode));
20397 }
20398 }
20399
20400 var child = node.child;
20401
20402 if (isFiberSuspenseAndTimedOut(node)) {
20403 child = getSuspenseFallbackChild(node);
20404 }
20405
20406 if (child !== null) {
20407 collectScopedNodesFromChildren(child, fn, scopedNodes);
20408 }
20409 }
20410}
20411
20412function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) {
20413 var child = startingChild;
20414
20415 while (child !== null) {
20416 collectScopedNodes(child, fn, scopedNodes);
20417 child = child.sibling;
20418 }
20419}
20420
20421function collectNearestScopeMethods(node, scope, childrenScopes) {
20422 if (isValidScopeNode(node, scope)) {
20423 childrenScopes.push(node.stateNode.methods);
20424 } else {
20425 var child = node.child;
20426
20427 if (isFiberSuspenseAndTimedOut(node)) {
20428 child = getSuspenseFallbackChild(node);
20429 }
20430
20431 if (child !== null) {
20432 collectNearestChildScopeMethods(child, scope, childrenScopes);
20433 }
20434 }
20435}
20436
20437function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) {
20438 var child = startingChild;
20439
20440 while (child !== null) {
20441 collectNearestScopeMethods(child, scope, childrenScopes);
20442 child = child.sibling;
20443 }
20444}
20445
20446function isValidScopeNode(node, scope) {
20447 return node.tag === ScopeComponent && node.type === scope;
20448}
20449
20450function createScopeMethods(scope, instance) {
20451 var fn = scope.fn;
20452 return {
20453 getChildren: function () {
20454 var currentFiber = instance.fiber;
20455 var child = currentFiber.child;
20456 var childrenScopes = [];
20457
20458 if (child !== null) {
20459 collectNearestChildScopeMethods(child, scope, childrenScopes);
20460 }
20461
20462 return childrenScopes.length === 0 ? null : childrenScopes;
20463 },
20464 getChildrenFromRoot: function () {
20465 var currentFiber = instance.fiber;
20466 var node = currentFiber;
20467
20468 while (node !== null) {
20469 var parent = node.return;
20470
20471 if (parent === null) {
20472 break;
20473 }
20474
20475 node = parent;
20476
20477 if (node.tag === ScopeComponent && node.type === scope) {
20478 break;
20479 }
20480 }
20481
20482 var childrenScopes = [];
20483 collectNearestChildScopeMethods(node.child, scope, childrenScopes);
20484 return childrenScopes.length === 0 ? null : childrenScopes;
20485 },
20486 getParent: function () {
20487 var node = instance.fiber.return;
20488
20489 while (node !== null) {
20490 if (node.tag === ScopeComponent && node.type === scope) {
20491 return node.stateNode.methods;
20492 }
20493
20494 node = node.return;
20495 }
20496
20497 return null;
20498 },
20499 getProps: function () {
20500 var currentFiber = instance.fiber;
20501 return currentFiber.memoizedProps;
20502 },
20503 getScopedNodes: function () {
20504 var currentFiber = instance.fiber;
20505 var child = currentFiber.child;
20506 var scopedNodes = [];
20507
20508 if (child !== null) {
20509 collectScopedNodesFromChildren(child, fn, scopedNodes);
20510 }
20511
20512 return scopedNodes.length === 0 ? null : scopedNodes;
20513 }
20514 };
20515}
20516
20517function markUpdate(workInProgress) {
20518 // Tag the fiber with an update effect. This turns a Placement into
20519 // a PlacementAndUpdate.
20520 workInProgress.effectTag |= Update;
20521}
20522
20523function markRef$1(workInProgress) {
20524 workInProgress.effectTag |= Ref;
20525}
20526
20527var appendAllChildren;
20528var updateHostContainer;
20529var updateHostComponent$1;
20530var updateHostText$1;
20531
20532if (supportsMutation) {
20533 // Mutation mode
20534 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20535 // We only have the top Fiber that was created but we need recurse down its
20536 // children to find all the terminal nodes.
20537 var node = workInProgress.child;
20538
20539 while (node !== null) {
20540 if (node.tag === HostComponent || node.tag === HostText) {
20541 appendInitialChild(parent, node.stateNode);
20542 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20543 appendInitialChild(parent, node.stateNode.instance);
20544 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20545 // down its children. Instead, we'll get insertions from each child in
20546 // the portal directly.
20547 } else if (node.child !== null) {
20548 node.child.return = node;
20549 node = node.child;
20550 continue;
20551 }
20552
20553 if (node === workInProgress) {
20554 return;
20555 }
20556
20557 while (node.sibling === null) {
20558 if (node.return === null || node.return === workInProgress) {
20559 return;
20560 }
20561
20562 node = node.return;
20563 }
20564
20565 node.sibling.return = node.return;
20566 node = node.sibling;
20567 }
20568 };
20569
20570 updateHostContainer = function (workInProgress) {// Noop
20571 };
20572
20573 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20574 // If we have an alternate, that means this is an update and we need to
20575 // schedule a side-effect to do the updates.
20576 var oldProps = current.memoizedProps;
20577
20578 if (oldProps === newProps) {
20579 // In mutation mode, this is sufficient for a bailout because
20580 // we won't touch this node even if children changed.
20581 return;
20582 } // If we get updated because one of our children updated, we don't
20583 // have newProps so we'll have to reuse them.
20584 // TODO: Split the update API as separate for the props vs. children.
20585 // Even better would be if children weren't special cased at all tho.
20586
20587
20588 var instance = workInProgress.stateNode;
20589 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
20590 // component is hitting the resume path. Figure out why. Possibly
20591 // related to `hidden`.
20592
20593 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
20594
20595 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
20596 // is a new ref we mark this as an update. All the work is done in commitWork.
20597
20598 if (updatePayload) {
20599 markUpdate(workInProgress);
20600 }
20601 };
20602
20603 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20604 // If the text differs, mark it as an update. All the work in done in commitWork.
20605 if (oldText !== newText) {
20606 markUpdate(workInProgress);
20607 }
20608 };
20609} else if (supportsPersistence) {
20610 // Persistent host tree mode
20611 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20612 // We only have the top Fiber that was created but we need recurse down its
20613 // children to find all the terminal nodes.
20614 var node = workInProgress.child;
20615
20616 while (node !== null) {
20617 // eslint-disable-next-line no-labels
20618 branches: if (node.tag === HostComponent) {
20619 var instance = node.stateNode;
20620
20621 if (needsVisibilityToggle && isHidden) {
20622 // This child is inside a timed out tree. Hide it.
20623 var props = node.memoizedProps;
20624 var type = node.type;
20625 instance = cloneHiddenInstance(instance, type, props, node);
20626 }
20627
20628 appendInitialChild(parent, instance);
20629 } else if (node.tag === HostText) {
20630 var _instance = node.stateNode;
20631
20632 if (needsVisibilityToggle && isHidden) {
20633 // This child is inside a timed out tree. Hide it.
20634 var text = node.memoizedProps;
20635 _instance = cloneHiddenTextInstance(_instance, text, node);
20636 }
20637
20638 appendInitialChild(parent, _instance);
20639 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20640 var _instance2 = node.stateNode.instance;
20641
20642 if (needsVisibilityToggle && isHidden) {
20643 // This child is inside a timed out tree. Hide it.
20644 var _props = node.memoizedProps;
20645 var _type = node.type;
20646 _instance2 = cloneHiddenInstance(_instance2, _type, _props, node);
20647 }
20648
20649 appendInitialChild(parent, _instance2);
20650 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20651 // down its children. Instead, we'll get insertions from each child in
20652 // the portal directly.
20653 } else if (node.tag === SuspenseComponent) {
20654 if ((node.effectTag & Update) !== NoEffect) {
20655 // Need to toggle the visibility of the primary children.
20656 var newIsHidden = node.memoizedState !== null;
20657
20658 if (newIsHidden) {
20659 var primaryChildParent = node.child;
20660
20661 if (primaryChildParent !== null) {
20662 if (primaryChildParent.child !== null) {
20663 primaryChildParent.child.return = primaryChildParent;
20664 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
20665 }
20666
20667 var fallbackChildParent = primaryChildParent.sibling;
20668
20669 if (fallbackChildParent !== null) {
20670 fallbackChildParent.return = node;
20671 node = fallbackChildParent;
20672 continue;
20673 }
20674 }
20675 }
20676 }
20677
20678 if (node.child !== null) {
20679 // Continue traversing like normal
20680 node.child.return = node;
20681 node = node.child;
20682 continue;
20683 }
20684 } else if (node.child !== null) {
20685 node.child.return = node;
20686 node = node.child;
20687 continue;
20688 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20689
20690
20691 node = node;
20692
20693 if (node === workInProgress) {
20694 return;
20695 }
20696
20697 while (node.sibling === null) {
20698 if (node.return === null || node.return === workInProgress) {
20699 return;
20700 }
20701
20702 node = node.return;
20703 }
20704
20705 node.sibling.return = node.return;
20706 node = node.sibling;
20707 }
20708 }; // An unfortunate fork of appendAllChildren because we have two different parent types.
20709
20710
20711 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
20712 // We only have the top Fiber that was created but we need recurse down its
20713 // children to find all the terminal nodes.
20714 var node = workInProgress.child;
20715
20716 while (node !== null) {
20717 // eslint-disable-next-line no-labels
20718 branches: if (node.tag === HostComponent) {
20719 var instance = node.stateNode;
20720
20721 if (needsVisibilityToggle && isHidden) {
20722 // This child is inside a timed out tree. Hide it.
20723 var props = node.memoizedProps;
20724 var type = node.type;
20725 instance = cloneHiddenInstance(instance, type, props, node);
20726 }
20727
20728 appendChildToContainerChildSet(containerChildSet, instance);
20729 } else if (node.tag === HostText) {
20730 var _instance3 = node.stateNode;
20731
20732 if (needsVisibilityToggle && isHidden) {
20733 // This child is inside a timed out tree. Hide it.
20734 var text = node.memoizedProps;
20735 _instance3 = cloneHiddenTextInstance(_instance3, text, node);
20736 }
20737
20738 appendChildToContainerChildSet(containerChildSet, _instance3);
20739 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20740 var _instance4 = node.stateNode.instance;
20741
20742 if (needsVisibilityToggle && isHidden) {
20743 // This child is inside a timed out tree. Hide it.
20744 var _props2 = node.memoizedProps;
20745 var _type2 = node.type;
20746 _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node);
20747 }
20748
20749 appendChildToContainerChildSet(containerChildSet, _instance4);
20750 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20751 // down its children. Instead, we'll get insertions from each child in
20752 // the portal directly.
20753 } else if (node.tag === SuspenseComponent) {
20754 if ((node.effectTag & Update) !== NoEffect) {
20755 // Need to toggle the visibility of the primary children.
20756 var newIsHidden = node.memoizedState !== null;
20757
20758 if (newIsHidden) {
20759 var primaryChildParent = node.child;
20760
20761 if (primaryChildParent !== null) {
20762 if (primaryChildParent.child !== null) {
20763 primaryChildParent.child.return = primaryChildParent;
20764 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
20765 }
20766
20767 var fallbackChildParent = primaryChildParent.sibling;
20768
20769 if (fallbackChildParent !== null) {
20770 fallbackChildParent.return = node;
20771 node = fallbackChildParent;
20772 continue;
20773 }
20774 }
20775 }
20776 }
20777
20778 if (node.child !== null) {
20779 // Continue traversing like normal
20780 node.child.return = node;
20781 node = node.child;
20782 continue;
20783 }
20784 } else if (node.child !== null) {
20785 node.child.return = node;
20786 node = node.child;
20787 continue;
20788 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20789
20790
20791 node = node;
20792
20793 if (node === workInProgress) {
20794 return;
20795 }
20796
20797 while (node.sibling === null) {
20798 if (node.return === null || node.return === workInProgress) {
20799 return;
20800 }
20801
20802 node = node.return;
20803 }
20804
20805 node.sibling.return = node.return;
20806 node = node.sibling;
20807 }
20808 };
20809
20810 updateHostContainer = function (workInProgress) {
20811 var portalOrRoot = workInProgress.stateNode;
20812 var childrenUnchanged = workInProgress.firstEffect === null;
20813
20814 if (childrenUnchanged) {// No changes, just reuse the existing instance.
20815 } else {
20816 var container = portalOrRoot.containerInfo;
20817 var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set.
20818
20819 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
20820 portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container.
20821
20822 markUpdate(workInProgress);
20823 finalizeContainerChildren(container, newChildSet);
20824 }
20825 };
20826
20827 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20828 var currentInstance = current.stateNode;
20829 var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates.
20830 // This guarantees that we can reuse all of them.
20831
20832 var childrenUnchanged = workInProgress.firstEffect === null;
20833
20834 if (childrenUnchanged && oldProps === newProps) {
20835 // No changes, just reuse the existing instance.
20836 // Note that this might release a previous clone.
20837 workInProgress.stateNode = currentInstance;
20838 return;
20839 }
20840
20841 var recyclableInstance = workInProgress.stateNode;
20842 var currentHostContext = getHostContext();
20843 var updatePayload = null;
20844
20845 if (oldProps !== newProps) {
20846 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
20847 }
20848
20849 if (childrenUnchanged && updatePayload === null) {
20850 // No changes, just reuse the existing instance.
20851 // Note that this might release a previous clone.
20852 workInProgress.stateNode = currentInstance;
20853 return;
20854 }
20855
20856 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
20857
20858 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
20859 markUpdate(workInProgress);
20860 }
20861
20862 workInProgress.stateNode = newInstance;
20863
20864 if (childrenUnchanged) {
20865 // If there are no other effects in this tree, we need to flag this node as having one.
20866 // Even though we're not going to use it for anything.
20867 // Otherwise parents won't know that there are new children to propagate upwards.
20868 markUpdate(workInProgress);
20869 } else {
20870 // If children might have changed, we have to add them all to the set.
20871 appendAllChildren(newInstance, workInProgress, false, false);
20872 }
20873 };
20874
20875 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20876 if (oldText !== newText) {
20877 // If the text content differs, we'll create a new text instance for it.
20878 var rootContainerInstance = getRootHostContainer();
20879 var currentHostContext = getHostContext();
20880 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.
20881 // This lets the parents know that at least one of their children has changed.
20882
20883 markUpdate(workInProgress);
20884 }
20885 };
20886} else {
20887 // No host operations
20888 updateHostContainer = function (workInProgress) {// Noop
20889 };
20890
20891 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop
20892 };
20893
20894 updateHostText$1 = function (current, workInProgress, oldText, newText) {// Noop
20895 };
20896}
20897
20898function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
20899 switch (renderState.tailMode) {
20900 case 'hidden':
20901 {
20902 // Any insertions at the end of the tail list after this point
20903 // should be invisible. If there are already mounted boundaries
20904 // anything before them are not considered for collapsing.
20905 // Therefore we need to go through the whole tail to find if
20906 // there are any.
20907 var tailNode = renderState.tail;
20908 var lastTailNode = null;
20909
20910 while (tailNode !== null) {
20911 if (tailNode.alternate !== null) {
20912 lastTailNode = tailNode;
20913 }
20914
20915 tailNode = tailNode.sibling;
20916 } // Next we're simply going to delete all insertions after the
20917 // last rendered item.
20918
20919
20920 if (lastTailNode === null) {
20921 // All remaining items in the tail are insertions.
20922 renderState.tail = null;
20923 } else {
20924 // Detach the insertion after the last node that was already
20925 // inserted.
20926 lastTailNode.sibling = null;
20927 }
20928
20929 break;
20930 }
20931
20932 case 'collapsed':
20933 {
20934 // Any insertions at the end of the tail list after this point
20935 // should be invisible. If there are already mounted boundaries
20936 // anything before them are not considered for collapsing.
20937 // Therefore we need to go through the whole tail to find if
20938 // there are any.
20939 var _tailNode = renderState.tail;
20940 var _lastTailNode = null;
20941
20942 while (_tailNode !== null) {
20943 if (_tailNode.alternate !== null) {
20944 _lastTailNode = _tailNode;
20945 }
20946
20947 _tailNode = _tailNode.sibling;
20948 } // Next we're simply going to delete all insertions after the
20949 // last rendered item.
20950
20951
20952 if (_lastTailNode === null) {
20953 // All remaining items in the tail are insertions.
20954 if (!hasRenderedATailFallback && renderState.tail !== null) {
20955 // We suspended during the head. We want to show at least one
20956 // row at the tail. So we'll keep on and cut off the rest.
20957 renderState.tail.sibling = null;
20958 } else {
20959 renderState.tail = null;
20960 }
20961 } else {
20962 // Detach the insertion after the last node that was already
20963 // inserted.
20964 _lastTailNode.sibling = null;
20965 }
20966
20967 break;
20968 }
20969 }
20970}
20971
20972function completeWork(current, workInProgress, renderExpirationTime) {
20973 var newProps = workInProgress.pendingProps;
20974
20975 switch (workInProgress.tag) {
20976 case IndeterminateComponent:
20977 break;
20978
20979 case LazyComponent:
20980 break;
20981
20982 case SimpleMemoComponent:
20983 case FunctionComponent:
20984 break;
20985
20986 case ClassComponent:
20987 {
20988 var Component = workInProgress.type;
20989
20990 if (isContextProvider(Component)) {
20991 popContext(workInProgress);
20992 }
20993
20994 break;
20995 }
20996
20997 case HostRoot:
20998 {
20999 popHostContainer(workInProgress);
21000 popTopLevelContextObject(workInProgress);
21001 var fiberRoot = workInProgress.stateNode;
21002
21003 if (fiberRoot.pendingContext) {
21004 fiberRoot.context = fiberRoot.pendingContext;
21005 fiberRoot.pendingContext = null;
21006 }
21007
21008 if (current === null || current.child === null) {
21009 // If we hydrated, pop so that we can delete any remaining children
21010 // that weren't hydrated.
21011 var wasHydrated = popHydrationState(workInProgress);
21012
21013 if (wasHydrated) {
21014 // If we hydrated, then we'll need to schedule an update for
21015 // the commit side-effects on the root.
21016 markUpdate(workInProgress);
21017 }
21018 }
21019
21020 updateHostContainer(workInProgress);
21021 break;
21022 }
21023
21024 case HostComponent:
21025 {
21026 popHostContext(workInProgress);
21027 var rootContainerInstance = getRootHostContainer();
21028 var type = workInProgress.type;
21029
21030 if (current !== null && workInProgress.stateNode != null) {
21031 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
21032
21033 if (enableFlareAPI) {
21034 var prevListeners = current.memoizedProps.listeners;
21035 var nextListeners = newProps.listeners;
21036
21037 if (prevListeners !== nextListeners) {
21038 markUpdate(workInProgress);
21039 }
21040 }
21041
21042 if (current.ref !== workInProgress.ref) {
21043 markRef$1(workInProgress);
21044 }
21045 } else {
21046 if (!newProps) {
21047 (function () {
21048 if (!(workInProgress.stateNode !== null)) {
21049 {
21050 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."));
21051 }
21052 }
21053 })(); // This can happen when we abort work.
21054
21055
21056 break;
21057 }
21058
21059 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
21060 // "stack" as the parent. Then append children as we go in beginWork
21061 // or completeWork depending on we want to add then top->down or
21062 // bottom->up. Top->down is faster in IE11.
21063
21064 var _wasHydrated = popHydrationState(workInProgress);
21065
21066 if (_wasHydrated) {
21067 // TODO: Move this and createInstance step into the beginPhase
21068 // to consolidate.
21069 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
21070 // If changes to the hydrated node needs to be applied at the
21071 // commit-phase we mark this as such.
21072 markUpdate(workInProgress);
21073 }
21074
21075 if (enableFlareAPI) {
21076 var listeners = newProps.listeners;
21077
21078 if (listeners != null) {
21079 updateEventListeners(listeners, workInProgress, rootContainerInstance);
21080 }
21081 }
21082 } else {
21083 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
21084 appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
21085
21086 workInProgress.stateNode = instance;
21087
21088 if (enableFlareAPI) {
21089 var _listeners = newProps.listeners;
21090
21091 if (_listeners != null) {
21092 updateEventListeners(_listeners, workInProgress, rootContainerInstance);
21093 }
21094 } // Certain renderers require commit-time effects for initial mount.
21095 // (eg DOM renderer supports auto-focus for certain elements).
21096 // Make sure such renderers get scheduled for later work.
21097
21098
21099 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
21100 markUpdate(workInProgress);
21101 }
21102 }
21103
21104 if (workInProgress.ref !== null) {
21105 // If there is a ref on a host node we need to schedule a callback
21106 markRef$1(workInProgress);
21107 }
21108 }
21109
21110 break;
21111 }
21112
21113 case HostText:
21114 {
21115 var newText = newProps;
21116
21117 if (current && workInProgress.stateNode != null) {
21118 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
21119 // to schedule a side-effect to do the updates.
21120
21121 updateHostText$1(current, workInProgress, oldText, newText);
21122 } else {
21123 if (typeof newText !== 'string') {
21124 (function () {
21125 if (!(workInProgress.stateNode !== null)) {
21126 {
21127 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."));
21128 }
21129 }
21130 })(); // This can happen when we abort work.
21131
21132 }
21133
21134 var _rootContainerInstance = getRootHostContainer();
21135
21136 var _currentHostContext = getHostContext();
21137
21138 var _wasHydrated2 = popHydrationState(workInProgress);
21139
21140 if (_wasHydrated2) {
21141 if (prepareToHydrateHostTextInstance(workInProgress)) {
21142 markUpdate(workInProgress);
21143 }
21144 } else {
21145 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
21146 }
21147 }
21148
21149 break;
21150 }
21151
21152 case ForwardRef:
21153 break;
21154
21155 case SuspenseComponent:
21156 {
21157 popSuspenseContext(workInProgress);
21158 var nextState = workInProgress.memoizedState;
21159
21160 if (enableSuspenseServerRenderer) {
21161 if (nextState !== null && nextState.dehydrated !== null) {
21162 if (current === null) {
21163 var _wasHydrated3 = popHydrationState(workInProgress);
21164
21165 (function () {
21166 if (!_wasHydrated3) {
21167 {
21168 throw ReactError(Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."));
21169 }
21170 }
21171 })();
21172
21173 prepareToHydrateHostSuspenseInstance(workInProgress);
21174
21175 if (enableSchedulerTracing) {
21176 markSpawnedWork(Never);
21177 }
21178
21179 return null;
21180 } else {
21181 // We should never have been in a hydration state if we didn't have a current.
21182 // However, in some of those paths, we might have reentered a hydration state
21183 // and then we might be inside a hydration state. In that case, we'll need to
21184 // exit out of it.
21185 resetHydrationState();
21186
21187 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
21188 // This boundary did not suspend so it's now hydrated and unsuspended.
21189 workInProgress.memoizedState = null;
21190 } // If nothing suspended, we need to schedule an effect to mark this boundary
21191 // as having hydrated so events know that they're free be invoked.
21192 // It's also a signal to replay events and the suspense callback.
21193 // If something suspended, schedule an effect to attach retry listeners.
21194 // So we might as well always mark this.
21195
21196
21197 workInProgress.effectTag |= Update;
21198 return null;
21199 }
21200 }
21201 }
21202
21203 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
21204 // Something suspended. Re-render with the fallback children.
21205 workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
21206
21207 return workInProgress;
21208 }
21209
21210 var nextDidTimeout = nextState !== null;
21211 var prevDidTimeout = false;
21212
21213 if (current === null) {
21214 // In cases where we didn't find a suitable hydration boundary we never
21215 // put this in dehydrated mode, but we still need to pop the hydration
21216 // state since we might be inside the insertion tree.
21217 popHydrationState(workInProgress);
21218 } else {
21219 var prevState = current.memoizedState;
21220 prevDidTimeout = prevState !== null;
21221
21222 if (!nextDidTimeout && prevState !== null) {
21223 // We just switched from the fallback to the normal children.
21224 // Delete the fallback.
21225 // TODO: Would it be better to store the fallback fragment on
21226 // the stateNode during the begin phase?
21227 var currentFallbackChild = current.child.sibling;
21228
21229 if (currentFallbackChild !== null) {
21230 // Deletions go at the beginning of the return fiber's effect list
21231 var first = workInProgress.firstEffect;
21232
21233 if (first !== null) {
21234 workInProgress.firstEffect = currentFallbackChild;
21235 currentFallbackChild.nextEffect = first;
21236 } else {
21237 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
21238 currentFallbackChild.nextEffect = null;
21239 }
21240
21241 currentFallbackChild.effectTag = Deletion;
21242 }
21243 }
21244 }
21245
21246 if (nextDidTimeout && !prevDidTimeout) {
21247 // If this subtreee is running in batched mode we can suspend,
21248 // otherwise we won't suspend.
21249 // TODO: This will still suspend a synchronous tree if anything
21250 // in the concurrent tree already suspended during this render.
21251 // This is a known bug.
21252 if ((workInProgress.mode & BatchedMode) !== NoMode) {
21253 // TODO: Move this back to throwException because this is too late
21254 // if this is a large tree which is common for initial loads. We
21255 // don't know if we should restart a render or not until we get
21256 // this marker, and this is too late.
21257 // If this render already had a ping or lower pri updates,
21258 // and this is the first time we know we're going to suspend we
21259 // should be able to immediately restart from within throwException.
21260 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
21261
21262 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
21263 // If this was in an invisible tree or a new render, then showing
21264 // this boundary is ok.
21265 renderDidSuspend();
21266 } else {
21267 // Otherwise, we're going to have to hide content so we should
21268 // suspend for longer if possible.
21269 renderDidSuspendDelayIfPossible();
21270 }
21271 }
21272 }
21273
21274 if (supportsPersistence) {
21275 // TODO: Only schedule updates if not prevDidTimeout.
21276 if (nextDidTimeout) {
21277 // If this boundary just timed out, schedule an effect to attach a
21278 // retry listener to the proimse. This flag is also used to hide the
21279 // primary children.
21280 workInProgress.effectTag |= Update;
21281 }
21282 }
21283
21284 if (supportsMutation) {
21285 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
21286 if (nextDidTimeout || prevDidTimeout) {
21287 // If this boundary just timed out, schedule an effect to attach a
21288 // retry listener to the proimse. This flag is also used to hide the
21289 // primary children. In mutation mode, we also need the flag to
21290 // *unhide* children that were previously hidden, so check if the
21291 // is currently timed out, too.
21292 workInProgress.effectTag |= Update;
21293 }
21294 }
21295
21296 if (enableSuspenseCallback && workInProgress.updateQueue !== null && workInProgress.memoizedProps.suspenseCallback != null) {
21297 // Always notify the callback
21298 workInProgress.effectTag |= Update;
21299 }
21300
21301 break;
21302 }
21303
21304 case Fragment:
21305 break;
21306
21307 case Mode:
21308 break;
21309
21310 case Profiler:
21311 break;
21312
21313 case HostPortal:
21314 popHostContainer(workInProgress);
21315 updateHostContainer(workInProgress);
21316 break;
21317
21318 case ContextProvider:
21319 // Pop provider fiber
21320 popProvider(workInProgress);
21321 break;
21322
21323 case ContextConsumer:
21324 break;
21325
21326 case MemoComponent:
21327 break;
21328
21329 case IncompleteClassComponent:
21330 {
21331 // Same as class component case. I put it down here so that the tags are
21332 // sequential to ensure this switch is compiled to a jump table.
21333 var _Component = workInProgress.type;
21334
21335 if (isContextProvider(_Component)) {
21336 popContext(workInProgress);
21337 }
21338
21339 break;
21340 }
21341
21342 case SuspenseListComponent:
21343 {
21344 popSuspenseContext(workInProgress);
21345 var renderState = workInProgress.memoizedState;
21346
21347 if (renderState === null) {
21348 // We're running in the default, "independent" mode. We don't do anything
21349 // in this mode.
21350 break;
21351 }
21352
21353 var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
21354 var renderedTail = renderState.rendering;
21355
21356 if (renderedTail === null) {
21357 // We just rendered the head.
21358 if (!didSuspendAlready) {
21359 // This is the first pass. We need to figure out if anything is still
21360 // suspended in the rendered set.
21361 // If new content unsuspended, but there's still some content that
21362 // didn't. Then we need to do a second pass that forces everything
21363 // to keep showing their fallbacks.
21364 // We might be suspended if something in this render pass suspended, or
21365 // something in the previous committed pass suspended. Otherwise,
21366 // there's no chance so we can skip the expensive call to
21367 // findFirstSuspended.
21368 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
21369
21370 if (!cannotBeSuspended) {
21371 var row = workInProgress.child;
21372
21373 while (row !== null) {
21374 var suspended = findFirstSuspended(row);
21375
21376 if (suspended !== null) {
21377 didSuspendAlready = true;
21378 workInProgress.effectTag |= DidCapture;
21379 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
21380 // part of the second pass. In that case nothing will subscribe to
21381 // its thennables. Instead, we'll transfer its thennables to the
21382 // SuspenseList so that it can retry if they resolve.
21383 // There might be multiple of these in the list but since we're
21384 // going to wait for all of them anyway, it doesn't really matter
21385 // which ones gets to ping. In theory we could get clever and keep
21386 // track of how many dependencies remain but it gets tricky because
21387 // in the meantime, we can add/remove/change items and dependencies.
21388 // We might bail out of the loop before finding any but that
21389 // doesn't matter since that means that the other boundaries that
21390 // we did find already has their listeners attached.
21391
21392 var newThennables = suspended.updateQueue;
21393
21394 if (newThennables !== null) {
21395 workInProgress.updateQueue = newThennables;
21396 workInProgress.effectTag |= Update;
21397 } // Rerender the whole list, but this time, we'll force fallbacks
21398 // to stay in place.
21399 // Reset the effect list before doing the second pass since that's now invalid.
21400
21401
21402 workInProgress.firstEffect = workInProgress.lastEffect = null; // Reset the child fibers to their original state.
21403
21404 resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
21405 // rerender the children.
21406
21407 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
21408 return workInProgress.child;
21409 }
21410
21411 row = row.sibling;
21412 }
21413 }
21414 } else {
21415 cutOffTailIfNeeded(renderState, false);
21416 } // Next we're going to render the tail.
21417
21418 } else {
21419 // Append the rendered row to the child list.
21420 if (!didSuspendAlready) {
21421 var _suspended = findFirstSuspended(renderedTail);
21422
21423 if (_suspended !== null) {
21424 workInProgress.effectTag |= DidCapture;
21425 didSuspendAlready = true;
21426 cutOffTailIfNeeded(renderState, true); // This might have been modified.
21427
21428 if (renderState.tail === null && renderState.tailMode === 'hidden') {
21429 // We need to delete the row we just rendered.
21430 // Ensure we transfer the update queue to the parent.
21431 var _newThennables = _suspended.updateQueue;
21432
21433 if (_newThennables !== null) {
21434 workInProgress.updateQueue = _newThennables;
21435 workInProgress.effectTag |= Update;
21436 } // Reset the effect list to what it w as before we rendered this
21437 // child. The nested children have already appended themselves.
21438
21439
21440 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
21441
21442 if (lastEffect !== null) {
21443 lastEffect.nextEffect = null;
21444 } // We're done.
21445
21446
21447 return null;
21448 }
21449 } else if (now() > renderState.tailExpiration && renderExpirationTime > Never) {
21450 // We have now passed our CPU deadline and we'll just give up further
21451 // attempts to render the main content and only render fallbacks.
21452 // The assumption is that this is usually faster.
21453 workInProgress.effectTag |= DidCapture;
21454 didSuspendAlready = true;
21455 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
21456 // to get it started back up to attempt the next item. If we can show
21457 // them, then they really have the same priority as this render.
21458 // So we'll pick it back up the very next render pass once we've had
21459 // an opportunity to yield for paint.
21460
21461 var nextPriority = renderExpirationTime - 1;
21462 workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
21463
21464 if (enableSchedulerTracing) {
21465 markSpawnedWork(nextPriority);
21466 }
21467 }
21468 }
21469
21470 if (renderState.isBackwards) {
21471 // The effect list of the backwards tail will have been added
21472 // to the end. This breaks the guarantee that life-cycles fire in
21473 // sibling order but that isn't a strong guarantee promised by React.
21474 // Especially since these might also just pop in during future commits.
21475 // Append to the beginning of the list.
21476 renderedTail.sibling = workInProgress.child;
21477 workInProgress.child = renderedTail;
21478 } else {
21479 var previousSibling = renderState.last;
21480
21481 if (previousSibling !== null) {
21482 previousSibling.sibling = renderedTail;
21483 } else {
21484 workInProgress.child = renderedTail;
21485 }
21486
21487 renderState.last = renderedTail;
21488 }
21489 }
21490
21491 if (renderState.tail !== null) {
21492 // We still have tail rows to render.
21493 if (renderState.tailExpiration === 0) {
21494 // Heuristic for how long we're willing to spend rendering rows
21495 // until we just give up and show what we have so far.
21496 var TAIL_EXPIRATION_TIMEOUT_MS = 500;
21497 renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
21498 } // Pop a row.
21499
21500
21501 var next = renderState.tail;
21502 renderState.rendering = next;
21503 renderState.tail = next.sibling;
21504 renderState.lastEffect = workInProgress.lastEffect;
21505 next.sibling = null; // Restore the context.
21506 // TODO: We can probably just avoid popping it instead and only
21507 // setting it the first time we go from not suspended to suspended.
21508
21509 var suspenseContext = suspenseStackCursor.current;
21510
21511 if (didSuspendAlready) {
21512 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21513 } else {
21514 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21515 }
21516
21517 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
21518
21519 return next;
21520 }
21521
21522 break;
21523 }
21524
21525 case FundamentalComponent:
21526 {
21527 if (enableFundamentalAPI) {
21528 var fundamentalImpl = workInProgress.type.impl;
21529 var fundamentalInstance = workInProgress.stateNode;
21530
21531 if (fundamentalInstance === null) {
21532 var getInitialState = fundamentalImpl.getInitialState;
21533 var fundamentalState;
21534
21535 if (getInitialState !== undefined) {
21536 fundamentalState = getInitialState(newProps);
21537 }
21538
21539 fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(workInProgress, newProps, fundamentalImpl, fundamentalState || {});
21540
21541 var _instance5 = getFundamentalComponentInstance(fundamentalInstance);
21542
21543 fundamentalInstance.instance = _instance5;
21544
21545 if (fundamentalImpl.reconcileChildren === false) {
21546 return null;
21547 }
21548
21549 appendAllChildren(_instance5, workInProgress, false, false);
21550 mountFundamentalComponent(fundamentalInstance);
21551 } else {
21552 // We fire update in commit phase
21553 var prevProps = fundamentalInstance.props;
21554 fundamentalInstance.prevProps = prevProps;
21555 fundamentalInstance.props = newProps;
21556 fundamentalInstance.currentFiber = workInProgress;
21557
21558 if (supportsPersistence) {
21559 var _instance6 = cloneFundamentalInstance(fundamentalInstance);
21560
21561 fundamentalInstance.instance = _instance6;
21562 appendAllChildren(_instance6, workInProgress, false, false);
21563 }
21564
21565 var shouldUpdate = shouldUpdateFundamentalComponent(fundamentalInstance);
21566
21567 if (shouldUpdate) {
21568 markUpdate(workInProgress);
21569 }
21570 }
21571 }
21572
21573 break;
21574 }
21575
21576 case ScopeComponent:
21577 {
21578 if (enableScopeAPI) {
21579 if (current === null) {
21580 var _type3 = workInProgress.type;
21581 var scopeInstance = {
21582 fiber: workInProgress,
21583 methods: null
21584 };
21585 workInProgress.stateNode = scopeInstance;
21586 scopeInstance.methods = createScopeMethods(_type3, scopeInstance);
21587
21588 if (enableFlareAPI) {
21589 var _listeners2 = newProps.listeners;
21590
21591 if (_listeners2 != null) {
21592 var _rootContainerInstance2 = getRootHostContainer();
21593
21594 updateEventListeners(_listeners2, workInProgress, _rootContainerInstance2);
21595 }
21596 }
21597
21598 if (workInProgress.ref !== null) {
21599 markRef$1(workInProgress);
21600 markUpdate(workInProgress);
21601 }
21602 } else {
21603 if (enableFlareAPI) {
21604 var _prevListeners = current.memoizedProps.listeners;
21605 var _nextListeners = newProps.listeners;
21606
21607 if (_prevListeners !== _nextListeners || workInProgress.ref !== null) {
21608 markUpdate(workInProgress);
21609 }
21610 } else {
21611 if (workInProgress.ref !== null) {
21612 markUpdate(workInProgress);
21613 }
21614 }
21615
21616 if (current.ref !== workInProgress.ref) {
21617 markRef$1(workInProgress);
21618 }
21619 }
21620 }
21621
21622 break;
21623 }
21624
21625 default:
21626 (function () {
21627 {
21628 {
21629 throw ReactError(Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue."));
21630 }
21631 }
21632 })();
21633
21634 }
21635
21636 return null;
21637}
21638
21639function unwindWork(workInProgress, renderExpirationTime) {
21640 switch (workInProgress.tag) {
21641 case ClassComponent:
21642 {
21643 var Component = workInProgress.type;
21644
21645 if (isContextProvider(Component)) {
21646 popContext(workInProgress);
21647 }
21648
21649 var effectTag = workInProgress.effectTag;
21650
21651 if (effectTag & ShouldCapture) {
21652 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
21653 return workInProgress;
21654 }
21655
21656 return null;
21657 }
21658
21659 case HostRoot:
21660 {
21661 popHostContainer(workInProgress);
21662 popTopLevelContextObject(workInProgress);
21663 var _effectTag = workInProgress.effectTag;
21664
21665 (function () {
21666 if (!((_effectTag & DidCapture) === NoEffect)) {
21667 {
21668 throw ReactError(Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue."));
21669 }
21670 }
21671 })();
21672
21673 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
21674 return workInProgress;
21675 }
21676
21677 case HostComponent:
21678 {
21679 // TODO: popHydrationState
21680 popHostContext(workInProgress);
21681 return null;
21682 }
21683
21684 case SuspenseComponent:
21685 {
21686 popSuspenseContext(workInProgress);
21687
21688 if (enableSuspenseServerRenderer) {
21689 var suspenseState = workInProgress.memoizedState;
21690
21691 if (suspenseState !== null && suspenseState.dehydrated !== null) {
21692 (function () {
21693 if (!(workInProgress.alternate !== null)) {
21694 {
21695 throw ReactError(Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."));
21696 }
21697 }
21698 })();
21699
21700 resetHydrationState();
21701 }
21702 }
21703
21704 var _effectTag2 = workInProgress.effectTag;
21705
21706 if (_effectTag2 & ShouldCapture) {
21707 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
21708
21709 return workInProgress;
21710 }
21711
21712 return null;
21713 }
21714
21715 case SuspenseListComponent:
21716 {
21717 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
21718 // caught by a nested boundary. If not, it should bubble through.
21719
21720 return null;
21721 }
21722
21723 case HostPortal:
21724 popHostContainer(workInProgress);
21725 return null;
21726
21727 case ContextProvider:
21728 popProvider(workInProgress);
21729 return null;
21730
21731 default:
21732 return null;
21733 }
21734}
21735
21736function unwindInterruptedWork(interruptedWork) {
21737 switch (interruptedWork.tag) {
21738 case ClassComponent:
21739 {
21740 var childContextTypes = interruptedWork.type.childContextTypes;
21741
21742 if (childContextTypes !== null && childContextTypes !== undefined) {
21743 popContext(interruptedWork);
21744 }
21745
21746 break;
21747 }
21748
21749 case HostRoot:
21750 {
21751 popHostContainer(interruptedWork);
21752 popTopLevelContextObject(interruptedWork);
21753 break;
21754 }
21755
21756 case HostComponent:
21757 {
21758 popHostContext(interruptedWork);
21759 break;
21760 }
21761
21762 case HostPortal:
21763 popHostContainer(interruptedWork);
21764 break;
21765
21766 case SuspenseComponent:
21767 popSuspenseContext(interruptedWork);
21768 break;
21769
21770 case SuspenseListComponent:
21771 popSuspenseContext(interruptedWork);
21772 break;
21773
21774 case ContextProvider:
21775 popProvider(interruptedWork);
21776 break;
21777
21778 default:
21779 break;
21780 }
21781}
21782
21783function createCapturedValue(value, source) {
21784 // If the value is an error, call this function immediately after it is thrown
21785 // so the stack is accurate.
21786 return {
21787 value: value,
21788 source: source,
21789 stack: getStackByFiberInDevAndProd(source)
21790 };
21791}
21792
21793// This module is forked in different environments.
21794// By default, return `true` to log errors to the console.
21795// Forks can return `false` if this isn't desirable.
21796function showErrorDialog(capturedError) {
21797 return true;
21798}
21799
21800function logCapturedError(capturedError) {
21801 var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging.
21802 // This enables renderers like ReactNative to better manage redbox behavior.
21803
21804 if (logError === false) {
21805 return;
21806 }
21807
21808 var error = capturedError.error;
21809
21810 {
21811 var componentName = capturedError.componentName,
21812 componentStack = capturedError.componentStack,
21813 errorBoundaryName = capturedError.errorBoundaryName,
21814 errorBoundaryFound = capturedError.errorBoundaryFound,
21815 willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
21816 // `preventDefault()` in window `error` handler.
21817 // We record this information as an expando on the error.
21818
21819 if (error != null && error._suppressLogging) {
21820 if (errorBoundaryFound && willRetry) {
21821 // The error is recoverable and was silenced.
21822 // Ignore it and don't print the stack addendum.
21823 // This is handy for testing error boundaries without noise.
21824 return;
21825 } // The error is fatal. Since the silencing might have
21826 // been accidental, we'll surface it anyway.
21827 // However, the browser would have silenced the original error
21828 // so we'll print it first, and then print the stack addendum.
21829
21830
21831 console.error(error); // For a more detailed description of this block, see:
21832 // https://github.com/facebook/react/pull/13384
21833 }
21834
21835 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
21836 var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
21837
21838 if (errorBoundaryFound && errorBoundaryName) {
21839 if (willRetry) {
21840 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
21841 } else {
21842 errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
21843 }
21844 } else {
21845 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.';
21846 }
21847
21848 var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
21849 // We don't include the original error message and JS stack because the browser
21850 // has already printed it. Even if the application swallows the error, it is still
21851 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
21852
21853 console.error(combinedMessage);
21854 }
21855}
21856
21857var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
21858
21859{
21860 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
21861}
21862
21863var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
21864function logError(boundary, errorInfo) {
21865 var source = errorInfo.source;
21866 var stack = errorInfo.stack;
21867
21868 if (stack === null && source !== null) {
21869 stack = getStackByFiberInDevAndProd(source);
21870 }
21871
21872 var capturedError = {
21873 componentName: source !== null ? getComponentName(source.type) : null,
21874 componentStack: stack !== null ? stack : '',
21875 error: errorInfo.value,
21876 errorBoundary: null,
21877 errorBoundaryName: null,
21878 errorBoundaryFound: false,
21879 willRetry: false
21880 };
21881
21882 if (boundary !== null && boundary.tag === ClassComponent) {
21883 capturedError.errorBoundary = boundary.stateNode;
21884 capturedError.errorBoundaryName = getComponentName(boundary.type);
21885 capturedError.errorBoundaryFound = true;
21886 capturedError.willRetry = true;
21887 }
21888
21889 try {
21890 logCapturedError(capturedError);
21891 } catch (e) {
21892 // This method must not throw, or React internal state will get messed up.
21893 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
21894 // we want to report this error outside of the normal stack as a last resort.
21895 // https://github.com/facebook/react/issues/13188
21896 setTimeout(function () {
21897 throw e;
21898 });
21899 }
21900}
21901
21902var callComponentWillUnmountWithTimer = function (current$$1, instance) {
21903 startPhaseTimer(current$$1, 'componentWillUnmount');
21904 instance.props = current$$1.memoizedProps;
21905 instance.state = current$$1.memoizedState;
21906 instance.componentWillUnmount();
21907 stopPhaseTimer();
21908}; // Capture errors so they don't interrupt unmounting.
21909
21910
21911function safelyCallComponentWillUnmount(current$$1, instance) {
21912 {
21913 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
21914
21915 if (hasCaughtError()) {
21916 var unmountError = clearCaughtError();
21917 captureCommitPhaseError(current$$1, unmountError);
21918 }
21919 }
21920}
21921
21922function safelyDetachRef(current$$1) {
21923 var ref = current$$1.ref;
21924
21925 if (ref !== null) {
21926 if (typeof ref === 'function') {
21927 {
21928 invokeGuardedCallback(null, ref, null, null);
21929
21930 if (hasCaughtError()) {
21931 var refError = clearCaughtError();
21932 captureCommitPhaseError(current$$1, refError);
21933 }
21934 }
21935 } else {
21936 ref.current = null;
21937 }
21938 }
21939}
21940
21941function safelyCallDestroy(current$$1, destroy) {
21942 {
21943 invokeGuardedCallback(null, destroy, null);
21944
21945 if (hasCaughtError()) {
21946 var error = clearCaughtError();
21947 captureCommitPhaseError(current$$1, error);
21948 }
21949 }
21950}
21951
21952function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
21953 switch (finishedWork.tag) {
21954 case FunctionComponent:
21955 case ForwardRef:
21956 case SimpleMemoComponent:
21957 {
21958 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
21959 return;
21960 }
21961
21962 case ClassComponent:
21963 {
21964 if (finishedWork.effectTag & Snapshot) {
21965 if (current$$1 !== null) {
21966 var prevProps = current$$1.memoizedProps;
21967 var prevState = current$$1.memoizedState;
21968 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
21969 var instance = finishedWork.stateNode; // We could update instance props and state here,
21970 // but instead we rely on them being set during last render.
21971 // TODO: revisit this when we implement resuming.
21972
21973 {
21974 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21975 !(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;
21976 !(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;
21977 }
21978 }
21979
21980 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
21981
21982 {
21983 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
21984
21985 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
21986 didWarnSet.add(finishedWork.type);
21987 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
21988 }
21989 }
21990
21991 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
21992 stopPhaseTimer();
21993 }
21994 }
21995
21996 return;
21997 }
21998
21999 case HostRoot:
22000 case HostComponent:
22001 case HostText:
22002 case HostPortal:
22003 case IncompleteClassComponent:
22004 // Nothing to do for these component types
22005 return;
22006
22007 default:
22008 {
22009 (function () {
22010 {
22011 {
22012 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."));
22013 }
22014 }
22015 })();
22016 }
22017 }
22018}
22019
22020function commitHookEffectList(unmountTag, mountTag, finishedWork) {
22021 var updateQueue = finishedWork.updateQueue;
22022 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
22023
22024 if (lastEffect !== null) {
22025 var firstEffect = lastEffect.next;
22026 var effect = firstEffect;
22027
22028 do {
22029 if ((effect.tag & unmountTag) !== NoEffect$1) {
22030 // Unmount
22031 var destroy = effect.destroy;
22032 effect.destroy = undefined;
22033
22034 if (destroy !== undefined) {
22035 destroy();
22036 }
22037 }
22038
22039 if ((effect.tag & mountTag) !== NoEffect$1) {
22040 // Mount
22041 var create = effect.create;
22042 effect.destroy = create();
22043
22044 {
22045 var _destroy = effect.destroy;
22046
22047 if (_destroy !== undefined && typeof _destroy !== 'function') {
22048 var addendum = void 0;
22049
22050 if (_destroy === null) {
22051 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
22052 } else if (typeof _destroy.then === 'function') {
22053 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';
22054 } else {
22055 addendum = ' You returned: ' + _destroy;
22056 }
22057
22058 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
22059 }
22060 }
22061 }
22062
22063 effect = effect.next;
22064 } while (effect !== firstEffect);
22065 }
22066}
22067
22068function commitPassiveHookEffects(finishedWork) {
22069 if ((finishedWork.effectTag & Passive) !== NoEffect) {
22070 switch (finishedWork.tag) {
22071 case FunctionComponent:
22072 case ForwardRef:
22073 case SimpleMemoComponent:
22074 {
22075 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
22076 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
22077 break;
22078 }
22079
22080 default:
22081 break;
22082 }
22083 }
22084}
22085
22086function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
22087 switch (finishedWork.tag) {
22088 case FunctionComponent:
22089 case ForwardRef:
22090 case SimpleMemoComponent:
22091 {
22092 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
22093 break;
22094 }
22095
22096 case ClassComponent:
22097 {
22098 var instance = finishedWork.stateNode;
22099
22100 if (finishedWork.effectTag & Update) {
22101 if (current$$1 === null) {
22102 startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
22103 // but instead we rely on them being set during last render.
22104 // TODO: revisit this when we implement resuming.
22105
22106 {
22107 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22108 !(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;
22109 !(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;
22110 }
22111 }
22112
22113 instance.componentDidMount();
22114 stopPhaseTimer();
22115 } else {
22116 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
22117 var prevState = current$$1.memoizedState;
22118 startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
22119 // but instead we rely on them being set during last render.
22120 // TODO: revisit this when we implement resuming.
22121
22122 {
22123 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22124 !(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;
22125 !(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;
22126 }
22127 }
22128
22129 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
22130 stopPhaseTimer();
22131 }
22132 }
22133
22134 var updateQueue = finishedWork.updateQueue;
22135
22136 if (updateQueue !== null) {
22137 {
22138 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22139 !(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;
22140 !(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;
22141 }
22142 } // We could update instance props and state here,
22143 // but instead we rely on them being set during last render.
22144 // TODO: revisit this when we implement resuming.
22145
22146
22147 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
22148 }
22149
22150 return;
22151 }
22152
22153 case HostRoot:
22154 {
22155 var _updateQueue = finishedWork.updateQueue;
22156
22157 if (_updateQueue !== null) {
22158 var _instance = null;
22159
22160 if (finishedWork.child !== null) {
22161 switch (finishedWork.child.tag) {
22162 case HostComponent:
22163 _instance = getPublicInstance(finishedWork.child.stateNode);
22164 break;
22165
22166 case ClassComponent:
22167 _instance = finishedWork.child.stateNode;
22168 break;
22169 }
22170 }
22171
22172 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
22173 }
22174
22175 return;
22176 }
22177
22178 case HostComponent:
22179 {
22180 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
22181 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
22182 // These effects should only be committed when components are first mounted,
22183 // aka when there is no current/alternate.
22184
22185 if (current$$1 === null && finishedWork.effectTag & Update) {
22186 var type = finishedWork.type;
22187 var props = finishedWork.memoizedProps;
22188 commitMount(_instance2, type, props, finishedWork);
22189 }
22190
22191 return;
22192 }
22193
22194 case HostText:
22195 {
22196 // We have no life-cycles associated with text.
22197 return;
22198 }
22199
22200 case HostPortal:
22201 {
22202 // We have no life-cycles associated with portals.
22203 return;
22204 }
22205
22206 case Profiler:
22207 {
22208 if (enableProfilerTimer) {
22209 var onRender = finishedWork.memoizedProps.onRender;
22210
22211 if (typeof onRender === 'function') {
22212 if (enableSchedulerTracing) {
22213 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
22214 } else {
22215 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
22216 }
22217 }
22218 }
22219
22220 return;
22221 }
22222
22223 case SuspenseComponent:
22224 {
22225 commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
22226 return;
22227 }
22228
22229 case SuspenseListComponent:
22230 case IncompleteClassComponent:
22231 case FundamentalComponent:
22232 case ScopeComponent:
22233 return;
22234
22235 default:
22236 {
22237 (function () {
22238 {
22239 {
22240 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."));
22241 }
22242 }
22243 })();
22244 }
22245 }
22246}
22247
22248function hideOrUnhideAllChildren(finishedWork, isHidden) {
22249 if (supportsMutation) {
22250 // We only have the top Fiber that was inserted but we need to recurse down its
22251 // children to find all the terminal nodes.
22252 var node = finishedWork;
22253
22254 while (true) {
22255 if (node.tag === HostComponent) {
22256 var instance = node.stateNode;
22257
22258 if (isHidden) {
22259 hideInstance(instance);
22260 } else {
22261 unhideInstance(node.stateNode, node.memoizedProps);
22262 }
22263 } else if (node.tag === HostText) {
22264 var _instance3 = node.stateNode;
22265
22266 if (isHidden) {
22267 hideTextInstance(_instance3);
22268 } else {
22269 unhideTextInstance(_instance3, node.memoizedProps);
22270 }
22271 } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
22272 // Found a nested Suspense component that timed out. Skip over the
22273 // primary child fragment, which should remain hidden.
22274 var fallbackChildFragment = node.child.sibling;
22275 fallbackChildFragment.return = node;
22276 node = fallbackChildFragment;
22277 continue;
22278 } else if (node.child !== null) {
22279 node.child.return = node;
22280 node = node.child;
22281 continue;
22282 }
22283
22284 if (node === finishedWork) {
22285 return;
22286 }
22287
22288 while (node.sibling === null) {
22289 if (node.return === null || node.return === finishedWork) {
22290 return;
22291 }
22292
22293 node = node.return;
22294 }
22295
22296 node.sibling.return = node.return;
22297 node = node.sibling;
22298 }
22299 }
22300}
22301
22302function commitAttachRef(finishedWork) {
22303 var ref = finishedWork.ref;
22304
22305 if (ref !== null) {
22306 var instance = finishedWork.stateNode;
22307 var instanceToUse;
22308
22309 switch (finishedWork.tag) {
22310 case HostComponent:
22311 instanceToUse = getPublicInstance(instance);
22312 break;
22313
22314 default:
22315 instanceToUse = instance;
22316 } // Moved outside to ensure DCE works with this flag
22317
22318
22319 if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
22320 instanceToUse = instance.methods;
22321 }
22322
22323 if (typeof ref === 'function') {
22324 ref(instanceToUse);
22325 } else {
22326 {
22327 if (!ref.hasOwnProperty('current')) {
22328 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
22329 }
22330 }
22331
22332 ref.current = instanceToUse;
22333 }
22334 }
22335}
22336
22337function commitDetachRef(current$$1) {
22338 var currentRef = current$$1.ref;
22339
22340 if (currentRef !== null) {
22341 if (typeof currentRef === 'function') {
22342 currentRef(null);
22343 } else {
22344 currentRef.current = null;
22345 }
22346 }
22347} // User-originating errors (lifecycles and refs) should not interrupt
22348// deletion, so don't let them throw. Host-originating errors should
22349// interrupt deletion, so it's okay
22350
22351
22352function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) {
22353 onCommitUnmount(current$$1);
22354
22355 switch (current$$1.tag) {
22356 case FunctionComponent:
22357 case ForwardRef:
22358 case MemoComponent:
22359 case SimpleMemoComponent:
22360 {
22361 var updateQueue = current$$1.updateQueue;
22362
22363 if (updateQueue !== null) {
22364 var lastEffect = updateQueue.lastEffect;
22365
22366 if (lastEffect !== null) {
22367 var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive
22368 // effect hook is called during the synchronous commit phase. This is
22369 // a concession to implementation complexity. Calling it in the
22370 // passive effect phase (like they usually are, when dependencies
22371 // change during an update) would require either traversing the
22372 // children of the deleted fiber again, or including unmount effects
22373 // as part of the fiber effect list.
22374 //
22375 // Because this is during the sync commit phase, we need to change
22376 // the priority.
22377 //
22378 // TODO: Reconsider this implementation trade off.
22379
22380 var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
22381 runWithPriority$2(priorityLevel, function () {
22382 var effect = firstEffect;
22383
22384 do {
22385 var destroy = effect.destroy;
22386
22387 if (destroy !== undefined) {
22388 safelyCallDestroy(current$$1, destroy);
22389 }
22390
22391 effect = effect.next;
22392 } while (effect !== firstEffect);
22393 });
22394 }
22395 }
22396
22397 break;
22398 }
22399
22400 case ClassComponent:
22401 {
22402 safelyDetachRef(current$$1);
22403 var instance = current$$1.stateNode;
22404
22405 if (typeof instance.componentWillUnmount === 'function') {
22406 safelyCallComponentWillUnmount(current$$1, instance);
22407 }
22408
22409 return;
22410 }
22411
22412 case HostComponent:
22413 {
22414 if (enableFlareAPI) {
22415 var dependencies = current$$1.dependencies;
22416
22417 if (dependencies !== null) {
22418 var respondersMap = dependencies.responders;
22419
22420 if (respondersMap !== null) {
22421 var responderInstances = Array.from(respondersMap.values());
22422
22423 for (var i = 0, length = responderInstances.length; i < length; i++) {
22424 var responderInstance = responderInstances[i];
22425 unmountResponderInstance(responderInstance);
22426 }
22427
22428 dependencies.responders = null;
22429 }
22430 }
22431 }
22432
22433 safelyDetachRef(current$$1);
22434 return;
22435 }
22436
22437 case HostPortal:
22438 {
22439 // TODO: this is recursive.
22440 // We are also not using this parent because
22441 // the portal will get pushed immediately.
22442 if (supportsMutation) {
22443 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22444 } else if (supportsPersistence) {
22445 emptyPortalContainer(current$$1);
22446 }
22447
22448 return;
22449 }
22450
22451 case FundamentalComponent:
22452 {
22453 if (enableFundamentalAPI) {
22454 var fundamentalInstance = current$$1.stateNode;
22455
22456 if (fundamentalInstance !== null) {
22457 unmountFundamentalComponent(fundamentalInstance);
22458 current$$1.stateNode = null;
22459 }
22460 }
22461
22462 return;
22463 }
22464
22465 case DehydratedFragment:
22466 {
22467 if (enableSuspenseCallback) {
22468 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22469
22470 if (hydrationCallbacks !== null) {
22471 var onDeleted = hydrationCallbacks.onDeleted;
22472
22473 if (onDeleted) {
22474 onDeleted(current$$1.stateNode);
22475 }
22476 }
22477 }
22478
22479 return;
22480 }
22481
22482 case ScopeComponent:
22483 {
22484 if (enableScopeAPI) {
22485 safelyDetachRef(current$$1);
22486 }
22487 }
22488 }
22489}
22490
22491function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
22492 // While we're inside a removed host node we don't want to call
22493 // removeChild on the inner nodes because they're removed by the top
22494 // call anyway. We also want to call componentWillUnmount on all
22495 // composites before this host node is removed from the tree. Therefore
22496 // we do an inner loop while we're still inside the host node.
22497 var node = root;
22498
22499 while (true) {
22500 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
22501 // Skip portals because commitUnmount() currently visits them recursively.
22502
22503 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
22504 // If we don't use mutation we drill down into portals here instead.
22505 !supportsMutation || node.tag !== HostPortal)) {
22506 node.child.return = node;
22507 node = node.child;
22508 continue;
22509 }
22510
22511 if (node === root) {
22512 return;
22513 }
22514
22515 while (node.sibling === null) {
22516 if (node.return === null || node.return === root) {
22517 return;
22518 }
22519
22520 node = node.return;
22521 }
22522
22523 node.sibling.return = node.return;
22524 node = node.sibling;
22525 }
22526}
22527
22528function detachFiber(current$$1) {
22529 var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
22530 // should clear the child pointer of the parent alternate to let this
22531 // get GC:ed but we don't know which for sure which parent is the current
22532 // one so we'll settle for GC:ing the subtree of this child. This child
22533 // itself will be GC:ed when the parent updates the next time.
22534
22535 current$$1.return = null;
22536 current$$1.child = null;
22537 current$$1.memoizedState = null;
22538 current$$1.updateQueue = null;
22539 current$$1.dependencies = null;
22540 current$$1.alternate = null;
22541 current$$1.firstEffect = null;
22542 current$$1.lastEffect = null;
22543 current$$1.pendingProps = null;
22544 current$$1.memoizedProps = null;
22545
22546 if (alternate !== null) {
22547 detachFiber(alternate);
22548 }
22549}
22550
22551function emptyPortalContainer(current$$1) {
22552 if (!supportsPersistence) {
22553 return;
22554 }
22555
22556 var portal = current$$1.stateNode;
22557 var containerInfo = portal.containerInfo;
22558 var emptyChildSet = createContainerChildSet(containerInfo);
22559 replaceContainerChildren(containerInfo, emptyChildSet);
22560}
22561
22562function commitContainer(finishedWork) {
22563 if (!supportsPersistence) {
22564 return;
22565 }
22566
22567 switch (finishedWork.tag) {
22568 case ClassComponent:
22569 case HostComponent:
22570 case HostText:
22571 case FundamentalComponent:
22572 {
22573 return;
22574 }
22575
22576 case HostRoot:
22577 case HostPortal:
22578 {
22579 var portalOrRoot = finishedWork.stateNode;
22580 var containerInfo = portalOrRoot.containerInfo,
22581 pendingChildren = portalOrRoot.pendingChildren;
22582 replaceContainerChildren(containerInfo, pendingChildren);
22583 return;
22584 }
22585
22586 default:
22587 {
22588 (function () {
22589 {
22590 {
22591 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."));
22592 }
22593 }
22594 })();
22595 }
22596 }
22597}
22598
22599function getHostParentFiber(fiber) {
22600 var parent = fiber.return;
22601
22602 while (parent !== null) {
22603 if (isHostParent(parent)) {
22604 return parent;
22605 }
22606
22607 parent = parent.return;
22608 }
22609
22610 (function () {
22611 {
22612 {
22613 throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22614 }
22615 }
22616 })();
22617}
22618
22619function isHostParent(fiber) {
22620 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
22621}
22622
22623function getHostSibling(fiber) {
22624 // We're going to search forward into the tree until we find a sibling host
22625 // node. Unfortunately, if multiple insertions are done in a row we have to
22626 // search past them. This leads to exponential search for the next sibling.
22627 // TODO: Find a more efficient way to do this.
22628 var node = fiber;
22629
22630 siblings: while (true) {
22631 // If we didn't find anything, let's try the next sibling.
22632 while (node.sibling === null) {
22633 if (node.return === null || isHostParent(node.return)) {
22634 // If we pop out of the root or hit the parent the fiber we are the
22635 // last sibling.
22636 return null;
22637 }
22638
22639 node = node.return;
22640 }
22641
22642 node.sibling.return = node.return;
22643 node = node.sibling;
22644
22645 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
22646 // If it is not host node and, we might have a host node inside it.
22647 // Try to search down until we find one.
22648 if (node.effectTag & Placement) {
22649 // If we don't have a child, try the siblings instead.
22650 continue siblings;
22651 } // If we don't have a child, try the siblings instead.
22652 // We also skip portals because they are not part of this host tree.
22653
22654
22655 if (node.child === null || node.tag === HostPortal) {
22656 continue siblings;
22657 } else {
22658 node.child.return = node;
22659 node = node.child;
22660 }
22661 } // Check if this host node is stable or about to be placed.
22662
22663
22664 if (!(node.effectTag & Placement)) {
22665 // Found it!
22666 return node.stateNode;
22667 }
22668 }
22669}
22670
22671function commitPlacement(finishedWork) {
22672 if (!supportsMutation) {
22673 return;
22674 } // Recursively insert all host nodes into the parent.
22675
22676
22677 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
22678
22679 var parent;
22680 var isContainer;
22681 var parentStateNode = parentFiber.stateNode;
22682
22683 switch (parentFiber.tag) {
22684 case HostComponent:
22685 parent = parentStateNode;
22686 isContainer = false;
22687 break;
22688
22689 case HostRoot:
22690 parent = parentStateNode.containerInfo;
22691 isContainer = true;
22692 break;
22693
22694 case HostPortal:
22695 parent = parentStateNode.containerInfo;
22696 isContainer = true;
22697 break;
22698
22699 case FundamentalComponent:
22700 if (enableFundamentalAPI) {
22701 parent = parentStateNode.instance;
22702 isContainer = false;
22703 }
22704
22705 // eslint-disable-next-line-no-fallthrough
22706
22707 default:
22708 (function () {
22709 {
22710 {
22711 throw ReactError(Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."));
22712 }
22713 }
22714 })();
22715
22716 }
22717
22718 if (parentFiber.effectTag & ContentReset) {
22719 // Reset the text content of the parent before doing any insertions
22720 resetTextContent(parent); // Clear ContentReset from the effect tag
22721
22722 parentFiber.effectTag &= ~ContentReset;
22723 }
22724
22725 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
22726 // children to find all the terminal nodes.
22727
22728 var node = finishedWork;
22729
22730 while (true) {
22731 var isHost = node.tag === HostComponent || node.tag === HostText;
22732
22733 if (isHost || enableFundamentalAPI && node.tag === FundamentalComponent) {
22734 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
22735
22736 if (before) {
22737 if (isContainer) {
22738 insertInContainerBefore(parent, stateNode, before);
22739 } else {
22740 insertBefore(parent, stateNode, before);
22741 }
22742 } else {
22743 if (isContainer) {
22744 appendChildToContainer(parent, stateNode);
22745 } else {
22746 appendChild(parent, stateNode);
22747 }
22748 }
22749 } else if (node.tag === HostPortal) {// If the insertion itself is a portal, then we don't want to traverse
22750 // down its children. Instead, we'll get insertions from each child in
22751 // the portal directly.
22752 } else if (node.child !== null) {
22753 node.child.return = node;
22754 node = node.child;
22755 continue;
22756 }
22757
22758 if (node === finishedWork) {
22759 return;
22760 }
22761
22762 while (node.sibling === null) {
22763 if (node.return === null || node.return === finishedWork) {
22764 return;
22765 }
22766
22767 node = node.return;
22768 }
22769
22770 node.sibling.return = node.return;
22771 node = node.sibling;
22772 }
22773}
22774
22775function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) {
22776 // We only have the top Fiber that was deleted but we need to recurse down its
22777 // children to find all the terminal nodes.
22778 var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not
22779 // currentParentIsValid.
22780
22781 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
22782
22783 var currentParent;
22784 var currentParentIsContainer;
22785
22786 while (true) {
22787 if (!currentParentIsValid) {
22788 var parent = node.return;
22789
22790 findParent: while (true) {
22791 (function () {
22792 if (!(parent !== null)) {
22793 {
22794 throw ReactError(Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."));
22795 }
22796 }
22797 })();
22798
22799 var parentStateNode = parent.stateNode;
22800
22801 switch (parent.tag) {
22802 case HostComponent:
22803 currentParent = parentStateNode;
22804 currentParentIsContainer = false;
22805 break findParent;
22806
22807 case HostRoot:
22808 currentParent = parentStateNode.containerInfo;
22809 currentParentIsContainer = true;
22810 break findParent;
22811
22812 case HostPortal:
22813 currentParent = parentStateNode.containerInfo;
22814 currentParentIsContainer = true;
22815 break findParent;
22816
22817 case FundamentalComponent:
22818 if (enableFundamentalAPI) {
22819 currentParent = parentStateNode.instance;
22820 currentParentIsContainer = false;
22821 }
22822
22823 }
22824
22825 parent = parent.return;
22826 }
22827
22828 currentParentIsValid = true;
22829 }
22830
22831 if (node.tag === HostComponent || node.tag === HostText) {
22832 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22833 // node from the tree.
22834
22835 if (currentParentIsContainer) {
22836 removeChildFromContainer(currentParent, node.stateNode);
22837 } else {
22838 removeChild(currentParent, node.stateNode);
22839 } // Don't visit children because we already visited them.
22840
22841 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
22842 var fundamentalNode = node.stateNode.instance;
22843 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22844 // node from the tree.
22845
22846 if (currentParentIsContainer) {
22847 removeChildFromContainer(currentParent, fundamentalNode);
22848 } else {
22849 removeChild(currentParent, fundamentalNode);
22850 }
22851 } else if (enableSuspenseServerRenderer && node.tag === DehydratedFragment) {
22852 if (enableSuspenseCallback) {
22853 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22854
22855 if (hydrationCallbacks !== null) {
22856 var onDeleted = hydrationCallbacks.onDeleted;
22857
22858 if (onDeleted) {
22859 onDeleted(node.stateNode);
22860 }
22861 }
22862 } // Delete the dehydrated suspense boundary and all of its content.
22863
22864
22865 if (currentParentIsContainer) {
22866 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
22867 } else {
22868 clearSuspenseBoundary(currentParent, node.stateNode);
22869 }
22870 } else if (node.tag === HostPortal) {
22871 if (node.child !== null) {
22872 // When we go into a portal, it becomes the parent to remove from.
22873 // We will reassign it back when we pop the portal on the way up.
22874 currentParent = node.stateNode.containerInfo;
22875 currentParentIsContainer = true; // Visit children because portals might contain host components.
22876
22877 node.child.return = node;
22878 node = node.child;
22879 continue;
22880 }
22881 } else {
22882 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
22883
22884 if (node.child !== null) {
22885 node.child.return = node;
22886 node = node.child;
22887 continue;
22888 }
22889 }
22890
22891 if (node === current$$1) {
22892 return;
22893 }
22894
22895 while (node.sibling === null) {
22896 if (node.return === null || node.return === current$$1) {
22897 return;
22898 }
22899
22900 node = node.return;
22901
22902 if (node.tag === HostPortal) {
22903 // When we go out of the portal, we need to restore the parent.
22904 // Since we don't keep a stack of them, we will search for it.
22905 currentParentIsValid = false;
22906 }
22907 }
22908
22909 node.sibling.return = node.return;
22910 node = node.sibling;
22911 }
22912}
22913
22914function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) {
22915 if (supportsMutation) {
22916 // Recursively delete all host nodes from the parent.
22917 // Detach refs and call componentWillUnmount() on the whole subtree.
22918 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22919 } else {
22920 // Detach refs and call componentWillUnmount() on the whole subtree.
22921 commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel);
22922 }
22923
22924 detachFiber(current$$1);
22925}
22926
22927function commitWork(current$$1, finishedWork) {
22928 if (!supportsMutation) {
22929 switch (finishedWork.tag) {
22930 case FunctionComponent:
22931 case ForwardRef:
22932 case MemoComponent:
22933 case SimpleMemoComponent:
22934 {
22935 // Note: We currently never use MountMutation, but useLayout uses
22936 // UnmountMutation.
22937 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22938 return;
22939 }
22940
22941 case Profiler:
22942 {
22943 return;
22944 }
22945
22946 case SuspenseComponent:
22947 {
22948 commitSuspenseComponent(finishedWork);
22949 attachSuspenseRetryListeners(finishedWork);
22950 return;
22951 }
22952
22953 case SuspenseListComponent:
22954 {
22955 attachSuspenseRetryListeners(finishedWork);
22956 return;
22957 }
22958
22959 case HostRoot:
22960 {
22961 if (supportsHydration) {
22962 var root = finishedWork.stateNode;
22963
22964 if (root.hydrate) {
22965 // We've just hydrated. No need to hydrate again.
22966 root.hydrate = false;
22967 commitHydratedContainer(root.containerInfo);
22968 }
22969 }
22970
22971 break;
22972 }
22973 }
22974
22975 commitContainer(finishedWork);
22976 return;
22977 }
22978
22979 switch (finishedWork.tag) {
22980 case FunctionComponent:
22981 case ForwardRef:
22982 case MemoComponent:
22983 case SimpleMemoComponent:
22984 {
22985 // Note: We currently never use MountMutation, but useLayout uses
22986 // UnmountMutation.
22987 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22988 return;
22989 }
22990
22991 case ClassComponent:
22992 {
22993 return;
22994 }
22995
22996 case HostComponent:
22997 {
22998 var instance = finishedWork.stateNode;
22999
23000 if (instance != null) {
23001 // Commit the work prepared earlier.
23002 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23003 // as the newProps. The updatePayload will contain the real change in
23004 // this case.
23005
23006 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
23007 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
23008
23009 var updatePayload = finishedWork.updateQueue;
23010 finishedWork.updateQueue = null;
23011
23012 if (updatePayload !== null) {
23013 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
23014 }
23015
23016 if (enableFlareAPI) {
23017 var prevListeners = oldProps.listeners;
23018 var nextListeners = newProps.listeners;
23019
23020 if (prevListeners !== nextListeners) {
23021 updateEventListeners(nextListeners, finishedWork, null);
23022 }
23023 }
23024 }
23025
23026 return;
23027 }
23028
23029 case HostText:
23030 {
23031 (function () {
23032 if (!(finishedWork.stateNode !== null)) {
23033 {
23034 throw ReactError(Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."));
23035 }
23036 }
23037 })();
23038
23039 var textInstance = finishedWork.stateNode;
23040 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23041 // as the newProps. The updatePayload will contain the real change in
23042 // this case.
23043
23044 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
23045 commitTextUpdate(textInstance, oldText, newText);
23046 return;
23047 }
23048
23049 case HostRoot:
23050 {
23051 if (supportsHydration) {
23052 var _root = finishedWork.stateNode;
23053
23054 if (_root.hydrate) {
23055 // We've just hydrated. No need to hydrate again.
23056 _root.hydrate = false;
23057 commitHydratedContainer(_root.containerInfo);
23058 }
23059 }
23060
23061 return;
23062 }
23063
23064 case Profiler:
23065 {
23066 return;
23067 }
23068
23069 case SuspenseComponent:
23070 {
23071 commitSuspenseComponent(finishedWork);
23072 attachSuspenseRetryListeners(finishedWork);
23073 return;
23074 }
23075
23076 case SuspenseListComponent:
23077 {
23078 attachSuspenseRetryListeners(finishedWork);
23079 return;
23080 }
23081
23082 case IncompleteClassComponent:
23083 {
23084 return;
23085 }
23086
23087 case FundamentalComponent:
23088 {
23089 if (enableFundamentalAPI) {
23090 var fundamentalInstance = finishedWork.stateNode;
23091 updateFundamentalComponent(fundamentalInstance);
23092 }
23093
23094 return;
23095 }
23096
23097 case ScopeComponent:
23098 {
23099 if (enableScopeAPI) {
23100 var scopeInstance = finishedWork.stateNode;
23101 scopeInstance.fiber = finishedWork;
23102
23103 if (enableFlareAPI) {
23104 var _newProps = finishedWork.memoizedProps;
23105
23106 var _oldProps = current$$1 !== null ? current$$1.memoizedProps : _newProps;
23107
23108 var _prevListeners = _oldProps.listeners;
23109 var _nextListeners = _newProps.listeners;
23110
23111 if (_prevListeners !== _nextListeners) {
23112 updateEventListeners(_nextListeners, finishedWork, null);
23113 }
23114 }
23115 }
23116
23117 return;
23118 }
23119
23120 default:
23121 {
23122 (function () {
23123 {
23124 {
23125 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."));
23126 }
23127 }
23128 })();
23129 }
23130 }
23131}
23132
23133function commitSuspenseComponent(finishedWork) {
23134 var newState = finishedWork.memoizedState;
23135 var newDidTimeout;
23136 var primaryChildParent = finishedWork;
23137
23138 if (newState === null) {
23139 newDidTimeout = false;
23140 } else {
23141 newDidTimeout = true;
23142 primaryChildParent = finishedWork.child;
23143 markCommitTimeOfFallback();
23144 }
23145
23146 if (supportsMutation && primaryChildParent !== null) {
23147 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
23148 }
23149
23150 if (enableSuspenseCallback && newState !== null) {
23151 var suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
23152
23153 if (typeof suspenseCallback === 'function') {
23154 var thenables = finishedWork.updateQueue;
23155
23156 if (thenables !== null) {
23157 suspenseCallback(new Set(thenables));
23158 }
23159 } else {
23160 if (suspenseCallback !== undefined) {
23161 warning$1(false, 'Unexpected type for suspenseCallback.');
23162 }
23163 }
23164 }
23165}
23166
23167function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
23168 if (!supportsHydration) {
23169 return;
23170 }
23171
23172 var newState = finishedWork.memoizedState;
23173
23174 if (newState === null) {
23175 var current$$1 = finishedWork.alternate;
23176
23177 if (current$$1 !== null) {
23178 var prevState = current$$1.memoizedState;
23179
23180 if (prevState !== null) {
23181 var suspenseInstance = prevState.dehydrated;
23182
23183 if (suspenseInstance !== null) {
23184 commitHydratedSuspenseInstance(suspenseInstance);
23185
23186 if (enableSuspenseCallback) {
23187 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
23188
23189 if (hydrationCallbacks !== null) {
23190 var onHydrated = hydrationCallbacks.onHydrated;
23191
23192 if (onHydrated) {
23193 onHydrated(suspenseInstance);
23194 }
23195 }
23196 }
23197 }
23198 }
23199 }
23200 }
23201}
23202
23203function attachSuspenseRetryListeners(finishedWork) {
23204 // If this boundary just timed out, then it will have a set of thenables.
23205 // For each thenable, attach a listener so that when it resolves, React
23206 // attempts to re-render the boundary in the primary (pre-timeout) state.
23207 var thenables = finishedWork.updateQueue;
23208
23209 if (thenables !== null) {
23210 finishedWork.updateQueue = null;
23211 var retryCache = finishedWork.stateNode;
23212
23213 if (retryCache === null) {
23214 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
23215 }
23216
23217 thenables.forEach(function (thenable) {
23218 // Memoize using the boundary fiber to prevent redundant listeners.
23219 var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
23220
23221 if (!retryCache.has(thenable)) {
23222 if (enableSchedulerTracing) {
23223 if (thenable.__reactDoNotTraceInteractions !== true) {
23224 retry = unstable_wrap(retry);
23225 }
23226 }
23227
23228 retryCache.add(thenable);
23229 thenable.then(retry, retry);
23230 }
23231 });
23232 }
23233}
23234
23235function commitResetTextContent(current$$1) {
23236 if (!supportsMutation) {
23237 return;
23238 }
23239
23240 resetTextContent(current$$1.stateNode);
23241}
23242
23243var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
23244
23245function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
23246 var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
23247
23248 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
23249 // being called "element".
23250
23251 update.payload = {
23252 element: null
23253 };
23254 var error = errorInfo.value;
23255
23256 update.callback = function () {
23257 onUncaughtError(error);
23258 logError(fiber, errorInfo);
23259 };
23260
23261 return update;
23262}
23263
23264function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
23265 var update = createUpdate(expirationTime, null);
23266 update.tag = CaptureUpdate;
23267 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
23268
23269 if (typeof getDerivedStateFromError === 'function') {
23270 var error = errorInfo.value;
23271
23272 update.payload = function () {
23273 logError(fiber, errorInfo);
23274 return getDerivedStateFromError(error);
23275 };
23276 }
23277
23278 var inst = fiber.stateNode;
23279
23280 if (inst !== null && typeof inst.componentDidCatch === 'function') {
23281 update.callback = function callback() {
23282 {
23283 markFailedErrorBoundaryForHotReloading(fiber);
23284 }
23285
23286 if (typeof getDerivedStateFromError !== 'function') {
23287 // To preserve the preexisting retry behavior of error boundaries,
23288 // we keep track of which ones already failed during this batch.
23289 // This gets reset before we yield back to the browser.
23290 // TODO: Warn in strict mode if getDerivedStateFromError is
23291 // not defined.
23292 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
23293
23294 logError(fiber, errorInfo);
23295 }
23296
23297 var error = errorInfo.value;
23298 var stack = errorInfo.stack;
23299 this.componentDidCatch(error, {
23300 componentStack: stack !== null ? stack : ''
23301 });
23302
23303 {
23304 if (typeof getDerivedStateFromError !== 'function') {
23305 // If componentDidCatch is the only error boundary method defined,
23306 // then it needs to call setState to recover from errors.
23307 // If no state update is scheduled then the boundary will swallow the error.
23308 !(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;
23309 }
23310 }
23311 };
23312 } else {
23313 update.callback = function () {
23314 markFailedErrorBoundaryForHotReloading(fiber);
23315 };
23316 }
23317
23318 return update;
23319}
23320
23321function attachPingListener(root, renderExpirationTime, thenable) {
23322 // Attach a listener to the promise to "ping" the root and retry. But
23323 // only if one does not already exist for the current render expiration
23324 // time (which acts like a "thread ID" here).
23325 var pingCache = root.pingCache;
23326 var threadIDs;
23327
23328 if (pingCache === null) {
23329 pingCache = root.pingCache = new PossiblyWeakMap$1();
23330 threadIDs = new Set();
23331 pingCache.set(thenable, threadIDs);
23332 } else {
23333 threadIDs = pingCache.get(thenable);
23334
23335 if (threadIDs === undefined) {
23336 threadIDs = new Set();
23337 pingCache.set(thenable, threadIDs);
23338 }
23339 }
23340
23341 if (!threadIDs.has(renderExpirationTime)) {
23342 // Memoize using the thread ID to prevent redundant listeners.
23343 threadIDs.add(renderExpirationTime);
23344 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
23345 thenable.then(ping, ping);
23346 }
23347}
23348
23349function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
23350 // The source fiber did not complete.
23351 sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
23352
23353 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
23354
23355 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
23356 // This is a thenable.
23357 var thenable = value;
23358 checkForWrongSuspensePriorityInDEV(sourceFiber);
23359 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
23360
23361 var _workInProgress = returnFiber;
23362
23363 do {
23364 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
23365 // Found the nearest boundary.
23366 // Stash the promise on the boundary fiber. If the boundary times out, we'll
23367 // attach another listener to flip the boundary back to its normal state.
23368 var thenables = _workInProgress.updateQueue;
23369
23370 if (thenables === null) {
23371 var updateQueue = new Set();
23372 updateQueue.add(thenable);
23373 _workInProgress.updateQueue = updateQueue;
23374 } else {
23375 thenables.add(thenable);
23376 } // If the boundary is outside of batched mode, we should *not*
23377 // suspend the commit. Pretend as if the suspended component rendered
23378 // null and keep rendering. In the commit phase, we'll schedule a
23379 // subsequent synchronous update to re-render the Suspense.
23380 //
23381 // Note: It doesn't matter whether the component that suspended was
23382 // inside a batched mode tree. If the Suspense is outside of it, we
23383 // should *not* suspend the commit.
23384
23385
23386 if ((_workInProgress.mode & BatchedMode) === NoMode) {
23387 _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
23388 // But we shouldn't call any lifecycle methods or callbacks. Remove
23389 // all lifecycle effect tags.
23390
23391 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
23392
23393 if (sourceFiber.tag === ClassComponent) {
23394 var currentSourceFiber = sourceFiber.alternate;
23395
23396 if (currentSourceFiber === null) {
23397 // This is a new mount. Change the tag so it's not mistaken for a
23398 // completed class component. For example, we should not call
23399 // componentWillUnmount if it is deleted.
23400 sourceFiber.tag = IncompleteClassComponent;
23401 } else {
23402 // When we try rendering again, we should not reuse the current fiber,
23403 // since it's known to be in an inconsistent state. Use a force update to
23404 // prevent a bail out.
23405 var update = createUpdate(Sync, null);
23406 update.tag = ForceUpdate;
23407 enqueueUpdate(sourceFiber, update);
23408 }
23409 } // The source fiber did not complete. Mark it with Sync priority to
23410 // indicate that it still has pending work.
23411
23412
23413 sourceFiber.expirationTime = Sync; // Exit without suspending.
23414
23415 return;
23416 } // Confirmed that the boundary is in a concurrent mode tree. Continue
23417 // with the normal suspend path.
23418 //
23419 // After this we'll use a set of heuristics to determine whether this
23420 // render pass will run to completion or restart or "suspend" the commit.
23421 // The actual logic for this is spread out in different places.
23422 //
23423 // This first principle is that if we're going to suspend when we complete
23424 // a root, then we should also restart if we get an update or ping that
23425 // might unsuspend it, and vice versa. The only reason to suspend is
23426 // because you think you might want to restart before committing. However,
23427 // it doesn't make sense to restart only while in the period we're suspended.
23428 //
23429 // Restarting too aggressively is also not good because it starves out any
23430 // intermediate loading state. So we use heuristics to determine when.
23431 // Suspense Heuristics
23432 //
23433 // If nothing threw a Promise or all the same fallbacks are already showing,
23434 // then don't suspend/restart.
23435 //
23436 // If this is an initial render of a new tree of Suspense boundaries and
23437 // those trigger a fallback, then don't suspend/restart. We want to ensure
23438 // that we can show the initial loading state as quickly as possible.
23439 //
23440 // If we hit a "Delayed" case, such as when we'd switch from content back into
23441 // a fallback, then we should always suspend/restart. SuspenseConfig applies to
23442 // this case. If none is defined, JND is used instead.
23443 //
23444 // If we're already showing a fallback and it gets "retried", allowing us to show
23445 // another level, but there's still an inner boundary that would show a fallback,
23446 // then we suspend/restart for 500ms since the last time we showed a fallback
23447 // anywhere in the tree. This effectively throttles progressive loading into a
23448 // consistent train of commits. This also gives us an opportunity to restart to
23449 // get to the completed state slightly earlier.
23450 //
23451 // If there's ambiguity due to batching it's resolved in preference of:
23452 // 1) "delayed", 2) "initial render", 3) "retry".
23453 //
23454 // We want to ensure that a "busy" state doesn't get force committed. We want to
23455 // ensure that new initial loading states can commit as soon as possible.
23456
23457
23458 attachPingListener(root, renderExpirationTime, thenable);
23459 _workInProgress.effectTag |= ShouldCapture;
23460 _workInProgress.expirationTime = renderExpirationTime;
23461 return;
23462 } // This boundary already captured during this render. Continue to the next
23463 // boundary.
23464
23465
23466 _workInProgress = _workInProgress.return;
23467 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
23468 // TODO: Use invariant so the message is stripped in prod?
23469
23470
23471 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));
23472 } // We didn't find a boundary that could handle this type of exception. Start
23473 // over and traverse parent path again, this time treating the exception
23474 // as an error.
23475
23476
23477 renderDidError();
23478 value = createCapturedValue(value, sourceFiber);
23479 var workInProgress = returnFiber;
23480
23481 do {
23482 switch (workInProgress.tag) {
23483 case HostRoot:
23484 {
23485 var _errorInfo = value;
23486 workInProgress.effectTag |= ShouldCapture;
23487 workInProgress.expirationTime = renderExpirationTime;
23488
23489 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
23490
23491 enqueueCapturedUpdate(workInProgress, _update);
23492 return;
23493 }
23494
23495 case ClassComponent:
23496 // Capture and retry
23497 var errorInfo = value;
23498 var ctor = workInProgress.type;
23499 var instance = workInProgress.stateNode;
23500
23501 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
23502 workInProgress.effectTag |= ShouldCapture;
23503 workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
23504
23505 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
23506
23507 enqueueCapturedUpdate(workInProgress, _update2);
23508 return;
23509 }
23510
23511 break;
23512
23513 default:
23514 break;
23515 }
23516
23517 workInProgress = workInProgress.return;
23518 } while (workInProgress !== null);
23519}
23520
23521var ceil = Math.ceil;
23522var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
23523var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
23524var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
23525var NoContext =
23526/* */
235270;
23528var BatchedContext =
23529/* */
235301;
23531var EventContext =
23532/* */
235332;
23534var DiscreteEventContext =
23535/* */
235364;
23537var LegacyUnbatchedContext =
23538/* */
235398;
23540var RenderContext =
23541/* */
2354216;
23543var CommitContext =
23544/* */
2354532;
23546var RootIncomplete = 0;
23547var RootFatalErrored = 1;
23548var RootErrored = 2;
23549var RootSuspended = 3;
23550var RootSuspendedWithDelay = 4;
23551var RootCompleted = 5;
23552var RootLocked = 6;
23553// Describes where we are in the React execution stack
23554var executionContext = NoContext; // The root we're working on
23555
23556var workInProgressRoot = null; // The fiber we're working on
23557
23558var workInProgress = null; // The expiration time we're rendering
23559
23560var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc.
23561
23562var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
23563
23564var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
23565// This is conceptually a time stamp but expressed in terms of an ExpirationTime
23566// because we deal mostly with expiration times in the hot path, so this avoids
23567// the conversion happening in the hot path.
23568
23569var workInProgressRootLatestProcessedExpirationTime = Sync;
23570var workInProgressRootLatestSuspenseTimeout = Sync;
23571var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
23572// includes unprocessed updates, not work in bailed out children.
23573
23574var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
23575// This flag determines if it might be worthwhile to restart if an opportunity
23576// happens latere.
23577
23578var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
23579// model where we don't commit new loading states in too quick succession.
23580
23581var globalMostRecentFallbackTime = 0;
23582var FALLBACK_THROTTLE_MS = 500;
23583var nextEffect = null;
23584var hasUncaughtError = false;
23585var firstUncaughtError = null;
23586var legacyErrorBoundariesThatAlreadyFailed = null;
23587var rootDoesHavePassiveEffects = false;
23588var rootWithPendingPassiveEffects = null;
23589var pendingPassiveEffectsRenderPriority = NoPriority;
23590var pendingPassiveEffectsExpirationTime = NoWork;
23591var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
23592
23593var NESTED_UPDATE_LIMIT = 50;
23594var nestedUpdateCount = 0;
23595var rootWithNestedUpdates = null;
23596var NESTED_PASSIVE_UPDATE_LIMIT = 50;
23597var nestedPassiveUpdateCount = 0;
23598var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
23599// during the commit phase. This enables them to be traced across components
23600// that spawn new work during render. E.g. hidden boundaries, suspended SSR
23601// hydration or SuspenseList.
23602
23603var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
23604// time). However, if two updates are scheduled within the same event, we
23605// should treat their start times as simultaneous, even if the actual clock
23606// time has advanced between the first and second call.
23607// In other words, because expiration times determine how updates are batched,
23608// we want all updates of like priority that occur within the same event to
23609// receive the same expiration time. Otherwise we get tearing.
23610
23611var currentEventTime = NoWork;
23612function requestCurrentTime() {
23613 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
23614 // We're inside React, so it's fine to read the actual time.
23615 return msToExpirationTime(now());
23616 } // We're not inside React, so we may be in the middle of a browser event.
23617
23618
23619 if (currentEventTime !== NoWork) {
23620 // Use the same start time for all updates until we enter React again.
23621 return currentEventTime;
23622 } // This is the first update since React yielded. Compute a new start time.
23623
23624
23625 currentEventTime = msToExpirationTime(now());
23626 return currentEventTime;
23627}
23628function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
23629 var mode = fiber.mode;
23630
23631 if ((mode & BatchedMode) === NoMode) {
23632 return Sync;
23633 }
23634
23635 var priorityLevel = getCurrentPriorityLevel();
23636
23637 if ((mode & ConcurrentMode) === NoMode) {
23638 return priorityLevel === ImmediatePriority ? Sync : Batched;
23639 }
23640
23641 if ((executionContext & RenderContext) !== NoContext) {
23642 // Use whatever time we're already rendering
23643 // TODO: Should there be a way to opt out, like with `runWithPriority`?
23644 return renderExpirationTime;
23645 }
23646
23647 var expirationTime;
23648
23649 if (suspenseConfig !== null) {
23650 // Compute an expiration time based on the Suspense timeout.
23651 expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
23652 } else {
23653 // Compute an expiration time based on the Scheduler priority.
23654 switch (priorityLevel) {
23655 case ImmediatePriority:
23656 expirationTime = Sync;
23657 break;
23658
23659 case UserBlockingPriority$2:
23660 // TODO: Rename this to computeUserBlockingExpiration
23661 expirationTime = computeInteractiveExpiration(currentTime);
23662 break;
23663
23664 case NormalPriority:
23665 case LowPriority:
23666 // TODO: Handle LowPriority
23667 // TODO: Rename this to... something better.
23668 expirationTime = computeAsyncExpiration(currentTime);
23669 break;
23670
23671 case IdlePriority:
23672 expirationTime = Idle;
23673 break;
23674
23675 default:
23676 (function () {
23677 {
23678 {
23679 throw ReactError(Error("Expected a valid priority level"));
23680 }
23681 }
23682 })();
23683
23684 }
23685 } // If we're in the middle of rendering a tree, do not update at the same
23686 // expiration time that is already rendering.
23687 // TODO: We shouldn't have to do this if the update is on a different root.
23688 // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
23689 // the root when we check for this condition.
23690
23691
23692 if (workInProgressRoot !== null && expirationTime === renderExpirationTime) {
23693 // This is a trick to move this update into a separate batch
23694 expirationTime -= 1;
23695 }
23696
23697 return expirationTime;
23698}
23699var lastUniqueAsyncExpiration = NoWork;
23700function computeUniqueAsyncExpiration() {
23701 var currentTime = requestCurrentTime();
23702 var result = computeAsyncExpiration(currentTime);
23703
23704 if (result <= lastUniqueAsyncExpiration) {
23705 // Since we assume the current time monotonically increases, we only hit
23706 // this branch when computeUniqueAsyncExpiration is fired multiple times
23707 // within a 200ms window (or whatever the async bucket size is).
23708 result -= 1;
23709 }
23710
23711 lastUniqueAsyncExpiration = result;
23712 return result;
23713}
23714function scheduleUpdateOnFiber(fiber, expirationTime) {
23715 checkForNestedUpdates();
23716 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
23717 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
23718
23719 if (root === null) {
23720 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
23721 return;
23722 }
23723
23724 checkForInterruption(fiber, expirationTime);
23725 recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
23726 // priority as an argument to that function and this one.
23727
23728 var priorityLevel = getCurrentPriorityLevel();
23729
23730 if (expirationTime === Sync) {
23731 if ( // Check if we're inside unbatchedUpdates
23732 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
23733 (executionContext & (RenderContext | CommitContext)) === NoContext) {
23734 // Register pending interactions on the root to avoid losing traced interaction data.
23735 schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
23736 // root inside of batchedUpdates should be synchronous, but layout updates
23737 // should be deferred until the end of the batch.
23738
23739 performSyncWorkOnRoot(root);
23740 } else {
23741 ensureRootIsScheduled(root);
23742 schedulePendingInteractions(root, expirationTime);
23743
23744 if (executionContext === NoContext) {
23745 // Flush the synchronous work now, unless we're already working or inside
23746 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
23747 // scheduleCallbackForFiber to preserve the ability to schedule a callback
23748 // without immediately flushing it. We only do this for user-initiated
23749 // updates, to preserve historical behavior of sync mode.
23750 flushSyncCallbackQueue();
23751 }
23752 }
23753 } else {
23754 ensureRootIsScheduled(root);
23755 schedulePendingInteractions(root, expirationTime);
23756 }
23757
23758 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
23759 // discrete, even inside a discrete event.
23760 priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority)) {
23761 // This is the result of a discrete event. Track the lowest priority
23762 // discrete update per root so we can flush them early, if needed.
23763 if (rootsWithPendingDiscreteUpdates === null) {
23764 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
23765 } else {
23766 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
23767
23768 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
23769 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
23770 }
23771 }
23772 }
23773}
23774var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
23775// work without treating it as a typical update that originates from an event;
23776// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
23777// on a fiber.
23778
23779function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
23780 // Update the source fiber's expiration time
23781 if (fiber.expirationTime < expirationTime) {
23782 fiber.expirationTime = expirationTime;
23783 }
23784
23785 var alternate = fiber.alternate;
23786
23787 if (alternate !== null && alternate.expirationTime < expirationTime) {
23788 alternate.expirationTime = expirationTime;
23789 } // Walk the parent path to the root and update the child expiration time.
23790
23791
23792 var node = fiber.return;
23793 var root = null;
23794
23795 if (node === null && fiber.tag === HostRoot) {
23796 root = fiber.stateNode;
23797 } else {
23798 while (node !== null) {
23799 alternate = node.alternate;
23800
23801 if (node.childExpirationTime < expirationTime) {
23802 node.childExpirationTime = expirationTime;
23803
23804 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23805 alternate.childExpirationTime = expirationTime;
23806 }
23807 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23808 alternate.childExpirationTime = expirationTime;
23809 }
23810
23811 if (node.return === null && node.tag === HostRoot) {
23812 root = node.stateNode;
23813 break;
23814 }
23815
23816 node = node.return;
23817 }
23818 }
23819
23820 if (root !== null) {
23821 if (workInProgressRoot === root) {
23822 // Received an update to a tree that's in the middle of rendering. Mark
23823 // that's unprocessed work on this root.
23824 markUnprocessedUpdateTime(expirationTime);
23825
23826 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
23827 // The root already suspended with a delay, which means this render
23828 // definitely won't finish. Since we have a new update, let's mark it as
23829 // suspended now, right before marking the incoming update. This has the
23830 // effect of interrupting the current render and switching to the update.
23831 // TODO: This happens to work when receiving an update during the render
23832 // phase, because of the trick inside computeExpirationForFiber to
23833 // subtract 1 from `renderExpirationTime` to move it into a
23834 // separate bucket. But we should probably model it with an exception,
23835 // using the same mechanism we use to force hydration of a subtree.
23836 // TODO: This does not account for low pri updates that were already
23837 // scheduled before the root started rendering. Need to track the next
23838 // pending expiration time (perhaps by backtracking the return path) and
23839 // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
23840 markRootSuspendedAtTime(root, renderExpirationTime);
23841 }
23842 } // Mark that the root has a pending update.
23843
23844
23845 markRootUpdatedAtTime(root, expirationTime);
23846 }
23847
23848 return root;
23849}
23850
23851function getNextRootExpirationTimeToWorkOn(root) {
23852 // Determines the next expiration time that the root should render, taking
23853 // into account levels that may be suspended, or levels that may have
23854 // received a ping.
23855 var lastExpiredTime = root.lastExpiredTime;
23856
23857 if (lastExpiredTime !== NoWork) {
23858 return lastExpiredTime;
23859 } // "Pending" refers to any update that hasn't committed yet, including if it
23860 // suspended. The "suspended" range is therefore a subset.
23861
23862
23863 var firstPendingTime = root.firstPendingTime;
23864
23865 if (!isRootSuspendedAtTime(root, firstPendingTime)) {
23866 // The highest priority pending time is not suspended. Let's work on that.
23867 return firstPendingTime;
23868 } // If the first pending time is suspended, check if there's a lower priority
23869 // pending level that we know about. Or check if we received a ping. Work
23870 // on whichever is higher priority.
23871
23872
23873 var lastPingedTime = root.lastPingedTime;
23874 var nextKnownPendingLevel = root.nextKnownPendingLevel;
23875 return lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
23876} // Use this function to schedule a task for a root. There's only one task per
23877// root; if a task was already scheduled, we'll check to make sure the
23878// expiration time of the existing task is the same as the expiration time of
23879// the next level that the root has work on. This function is called on every
23880// update, and right before exiting a task.
23881
23882
23883function ensureRootIsScheduled(root) {
23884 var lastExpiredTime = root.lastExpiredTime;
23885
23886 if (lastExpiredTime !== NoWork) {
23887 // Special case: Expired work should flush synchronously.
23888 root.callbackExpirationTime = Sync;
23889 root.callbackPriority = ImmediatePriority;
23890 root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23891 return;
23892 }
23893
23894 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23895 var existingCallbackNode = root.callbackNode;
23896
23897 if (expirationTime === NoWork) {
23898 // There's nothing to work on.
23899 if (existingCallbackNode !== null) {
23900 root.callbackNode = null;
23901 root.callbackExpirationTime = NoWork;
23902 root.callbackPriority = NoPriority;
23903 }
23904
23905 return;
23906 } // TODO: If this is an update, we already read the current time. Pass the
23907 // time as an argument.
23908
23909
23910 var currentTime = requestCurrentTime();
23911 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
23912 // expiration time. Otherwise, we'll cancel it and schedule a new one.
23913
23914 if (existingCallbackNode !== null) {
23915 var existingCallbackPriority = root.callbackPriority;
23916 var existingCallbackExpirationTime = root.callbackExpirationTime;
23917
23918 if ( // Callback must have the exact same expiration time.
23919 existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
23920 existingCallbackPriority >= priorityLevel) {
23921 // Existing callback is sufficient.
23922 return;
23923 } // Need to schedule a new task.
23924 // TODO: Instead of scheduling a new task, we should be able to change the
23925 // priority of the existing one.
23926
23927
23928 cancelCallback(existingCallbackNode);
23929 }
23930
23931 root.callbackExpirationTime = expirationTime;
23932 root.callbackPriority = priorityLevel;
23933 var callbackNode;
23934
23935 if (expirationTime === Sync) {
23936 // Sync React callbacks are scheduled on a special internal queue
23937 callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23938 } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) {
23939 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root));
23940 } else {
23941 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
23942 // ordering because tasks are processed in timeout order.
23943 {
23944 timeout: expirationTimeToMs(expirationTime) - now()
23945 });
23946 }
23947
23948 root.callbackNode = callbackNode;
23949} // This is the entry point for every concurrent task, i.e. anything that
23950// goes through Scheduler.
23951
23952
23953function performConcurrentWorkOnRoot(root, didTimeout) {
23954 // Since we know we're in a React event, we can clear the current
23955 // event time. The next update will compute a new event time.
23956 currentEventTime = NoWork;
23957
23958 if (didTimeout) {
23959 // The render task took too long to complete. Mark the current time as
23960 // expired to synchronously render all expired work in a single batch.
23961 var currentTime = requestCurrentTime();
23962 markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
23963
23964 ensureRootIsScheduled(root);
23965 return null;
23966 } // Determine the next expiration time to work on, using the fields stored
23967 // on the root.
23968
23969
23970 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23971
23972 if (expirationTime !== NoWork) {
23973 var originalCallbackNode = root.callbackNode;
23974
23975 (function () {
23976 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
23977 {
23978 throw ReactError(Error("Should not already be working."));
23979 }
23980 }
23981 })();
23982
23983 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
23984 // and prepare a fresh one. Otherwise we'll continue where we left off.
23985
23986 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
23987 prepareFreshStack(root, expirationTime);
23988 startWorkOnPendingInteractions(root, expirationTime);
23989 } // If we have a work-in-progress fiber, it means there's still work to do
23990 // in this root.
23991
23992
23993 if (workInProgress !== null) {
23994 var prevExecutionContext = executionContext;
23995 executionContext |= RenderContext;
23996 var prevDispatcher = pushDispatcher(root);
23997 var prevInteractions = pushInteractions(root);
23998 startWorkLoopTimer(workInProgress);
23999
24000 do {
24001 try {
24002 workLoopConcurrent();
24003 break;
24004 } catch (thrownValue) {
24005 handleError(root, thrownValue);
24006 }
24007 } while (true);
24008
24009 resetContextDependencies();
24010 executionContext = prevExecutionContext;
24011 popDispatcher(prevDispatcher);
24012
24013 if (enableSchedulerTracing) {
24014 popInteractions(prevInteractions);
24015 }
24016
24017 if (workInProgressRootExitStatus === RootFatalErrored) {
24018 var fatalError = workInProgressRootFatalError;
24019 stopInterruptedWorkLoopTimer();
24020 prepareFreshStack(root, expirationTime);
24021 markRootSuspendedAtTime(root, expirationTime);
24022 ensureRootIsScheduled(root);
24023 throw fatalError;
24024 }
24025
24026 if (workInProgress !== null) {
24027 // There's still work left over. Exit without committing.
24028 stopInterruptedWorkLoopTimer();
24029 } else {
24030 // We now have a consistent tree. The next step is either to commit it,
24031 // or, if something suspended, wait to commit it after a timeout.
24032 stopFinishedWorkLoopTimer();
24033 var finishedWork = root.finishedWork = root.current.alternate;
24034 root.finishedExpirationTime = expirationTime;
24035 resolveLocksOnRoot(root, expirationTime);
24036 finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
24037 }
24038
24039 ensureRootIsScheduled(root);
24040
24041 if (root.callbackNode === originalCallbackNode) {
24042 // The task node scheduled for this root is the same one that's
24043 // currently executed. Need to return a continuation.
24044 return performConcurrentWorkOnRoot.bind(null, root);
24045 }
24046 }
24047 }
24048
24049 return null;
24050}
24051
24052function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
24053 // Set this to null to indicate there's no in-progress render.
24054 workInProgressRoot = null;
24055
24056 switch (exitStatus) {
24057 case RootIncomplete:
24058 case RootFatalErrored:
24059 {
24060 (function () {
24061 {
24062 {
24063 throw ReactError(Error("Root did not complete. This is a bug in React."));
24064 }
24065 }
24066 })();
24067 }
24068 // Flow knows about invariant, so it complains if I add a break
24069 // statement, but eslint doesn't know about invariant, so it complains
24070 // if I do. eslint-disable-next-line no-fallthrough
24071
24072 case RootErrored:
24073 {
24074 if (expirationTime !== Idle) {
24075 // If this was an async render, the error may have happened due to
24076 // a mutation in a concurrent event. Try rendering one more time,
24077 // synchronously, to see if the error goes away. If there are
24078 // lower priority updates, let's include those, too, in case they
24079 // fix the inconsistency. Render at Idle to include all updates.
24080 markRootExpiredAtTime(root, Idle);
24081 break;
24082 } // Commit the root in its errored state.
24083
24084
24085 commitRoot(root);
24086 break;
24087 }
24088
24089 case RootSuspended:
24090 {
24091 markRootSuspendedAtTime(root, expirationTime);
24092 var lastSuspendedTime = root.lastSuspendedTime;
24093
24094 if (expirationTime === lastSuspendedTime) {
24095 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24096 }
24097
24098 flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we
24099 // should immediately commit it or wait a bit.
24100 // If we have processed new updates during this render, we may now
24101 // have a new loading state ready. We want to ensure that we commit
24102 // that as soon as possible.
24103
24104 var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
24105
24106 if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
24107 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24108 // If we have not processed any new updates during this pass, then
24109 // this is either a retry of an existing fallback state or a
24110 // hidden tree. Hidden trees shouldn't be batched with other work
24111 // and after that's fixed it can only be a retry. We're going to
24112 // throttle committing retries so that we don't show too many
24113 // loading states too quickly.
24114 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
24115
24116 if (msUntilTimeout > 10) {
24117 if (workInProgressRootHasPendingPing) {
24118 var lastPingedTime = root.lastPingedTime;
24119
24120 if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
24121 // This render was pinged but we didn't get to restart
24122 // earlier so try restarting now instead.
24123 root.lastPingedTime = expirationTime;
24124 prepareFreshStack(root, expirationTime);
24125 break;
24126 }
24127 }
24128
24129 var nextTime = getNextRootExpirationTimeToWorkOn(root);
24130
24131 if (nextTime !== NoWork && nextTime !== expirationTime) {
24132 // There's additional work on this root.
24133 break;
24134 }
24135
24136 if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
24137 // We should prefer to render the fallback of at the last
24138 // suspended level. Ping the last suspended level to try
24139 // rendering it again.
24140 root.lastPingedTime = lastSuspendedTime;
24141 break;
24142 } // The render is suspended, it hasn't timed out, and there's no
24143 // lower priority work to do. Instead of committing the fallback
24144 // immediately, wait for more data to arrive.
24145
24146
24147 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
24148 break;
24149 }
24150 } // The work expired. Commit immediately.
24151
24152
24153 commitRoot(root);
24154 break;
24155 }
24156
24157 case RootSuspendedWithDelay:
24158 {
24159 markRootSuspendedAtTime(root, expirationTime);
24160 var _lastSuspendedTime = root.lastSuspendedTime;
24161
24162 if (expirationTime === _lastSuspendedTime) {
24163 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24164 }
24165
24166 flushSuspensePriorityWarningInDEV();
24167
24168 if ( // do not delay if we're inside an act() scope
24169 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24170 // We're suspended in a state that should be avoided. We'll try to
24171 // avoid committing it for as long as the timeouts let us.
24172 if (workInProgressRootHasPendingPing) {
24173 var _lastPingedTime = root.lastPingedTime;
24174
24175 if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
24176 // This render was pinged but we didn't get to restart earlier
24177 // so try restarting now instead.
24178 root.lastPingedTime = expirationTime;
24179 prepareFreshStack(root, expirationTime);
24180 break;
24181 }
24182 }
24183
24184 var _nextTime = getNextRootExpirationTimeToWorkOn(root);
24185
24186 if (_nextTime !== NoWork && _nextTime !== expirationTime) {
24187 // There's additional work on this root.
24188 break;
24189 }
24190
24191 if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
24192 // We should prefer to render the fallback of at the last
24193 // suspended level. Ping the last suspended level to try
24194 // rendering it again.
24195 root.lastPingedTime = _lastSuspendedTime;
24196 break;
24197 }
24198
24199 var _msUntilTimeout;
24200
24201 if (workInProgressRootLatestSuspenseTimeout !== Sync) {
24202 // We have processed a suspense config whose expiration time we
24203 // can use as the timeout.
24204 _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
24205 } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
24206 // This should never normally happen because only new updates
24207 // cause delayed states, so we should have processed something.
24208 // However, this could also happen in an offscreen tree.
24209 _msUntilTimeout = 0;
24210 } else {
24211 // If we don't have a suspense config, we're going to use a
24212 // heuristic to determine how long we can suspend.
24213 var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
24214 var currentTimeMs = now();
24215 var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
24216 var timeElapsed = currentTimeMs - eventTimeMs;
24217
24218 if (timeElapsed < 0) {
24219 // We get this wrong some time since we estimate the time.
24220 timeElapsed = 0;
24221 }
24222
24223 _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
24224 // event time is exact instead of inferred from expiration time
24225 // we don't need this.
24226
24227 if (timeUntilExpirationMs < _msUntilTimeout) {
24228 _msUntilTimeout = timeUntilExpirationMs;
24229 }
24230 } // Don't bother with a very short suspense time.
24231
24232
24233 if (_msUntilTimeout > 10) {
24234 // The render is suspended, it hasn't timed out, and there's no
24235 // lower priority work to do. Instead of committing the fallback
24236 // immediately, wait for more data to arrive.
24237 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
24238 break;
24239 }
24240 } // The work expired. Commit immediately.
24241
24242
24243 commitRoot(root);
24244 break;
24245 }
24246
24247 case RootCompleted:
24248 {
24249 // The work completed. Ready to commit.
24250 if ( // do not delay if we're inside an act() scope
24251 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
24252 // If we have exceeded the minimum loading delay, which probably
24253 // means we have shown a spinner already, we might have to suspend
24254 // a bit longer to ensure that the spinner is shown for
24255 // enough time.
24256 var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
24257
24258 if (_msUntilTimeout2 > 10) {
24259 markRootSuspendedAtTime(root, expirationTime);
24260 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
24261 break;
24262 }
24263 }
24264
24265 commitRoot(root);
24266 break;
24267 }
24268
24269 case RootLocked:
24270 {
24271 // This root has a lock that prevents it from committing. Exit. If
24272 // we begin work on the root again, without any intervening updates,
24273 // it will finish without doing additional work.
24274 markRootSuspendedAtTime(root, expirationTime);
24275 break;
24276 }
24277
24278 default:
24279 {
24280 (function () {
24281 {
24282 {
24283 throw ReactError(Error("Unknown root exit status."));
24284 }
24285 }
24286 })();
24287 }
24288 }
24289} // This is the entry point for synchronous tasks that don't go
24290// through Scheduler
24291
24292
24293function performSyncWorkOnRoot(root) {
24294 // Check if there's expired work on this root. Otherwise, render at Sync.
24295 var lastExpiredTime = root.lastExpiredTime;
24296 var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
24297
24298 if (root.finishedExpirationTime === expirationTime) {
24299 // There's already a pending commit at this expiration time.
24300 // TODO: This is poorly factored. This case only exists for the
24301 // batch.commit() API.
24302 commitRoot(root);
24303 } else {
24304 (function () {
24305 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24306 {
24307 throw ReactError(Error("Should not already be working."));
24308 }
24309 }
24310 })();
24311
24312 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24313 // and prepare a fresh one. Otherwise we'll continue where we left off.
24314
24315 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24316 prepareFreshStack(root, expirationTime);
24317 startWorkOnPendingInteractions(root, expirationTime);
24318 } // If we have a work-in-progress fiber, it means there's still work to do
24319 // in this root.
24320
24321
24322 if (workInProgress !== null) {
24323 var prevExecutionContext = executionContext;
24324 executionContext |= RenderContext;
24325 var prevDispatcher = pushDispatcher(root);
24326 var prevInteractions = pushInteractions(root);
24327 startWorkLoopTimer(workInProgress);
24328
24329 do {
24330 try {
24331 workLoopSync();
24332 break;
24333 } catch (thrownValue) {
24334 handleError(root, thrownValue);
24335 }
24336 } while (true);
24337
24338 resetContextDependencies();
24339 executionContext = prevExecutionContext;
24340 popDispatcher(prevDispatcher);
24341
24342 if (enableSchedulerTracing) {
24343 popInteractions(prevInteractions);
24344 }
24345
24346 if (workInProgressRootExitStatus === RootFatalErrored) {
24347 var fatalError = workInProgressRootFatalError;
24348 stopInterruptedWorkLoopTimer();
24349 prepareFreshStack(root, expirationTime);
24350 markRootSuspendedAtTime(root, expirationTime);
24351 ensureRootIsScheduled(root);
24352 throw fatalError;
24353 }
24354
24355 if (workInProgress !== null) {
24356 // This is a sync render, so we should have finished the whole tree.
24357 (function () {
24358 {
24359 {
24360 throw ReactError(Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."));
24361 }
24362 }
24363 })();
24364 } else {
24365 // We now have a consistent tree. Because this is a sync render, we
24366 // will commit it even if something suspended. The only exception is
24367 // if the root is locked (using the unstable_createBatch API).
24368 stopFinishedWorkLoopTimer();
24369 root.finishedWork = root.current.alternate;
24370 root.finishedExpirationTime = expirationTime;
24371 resolveLocksOnRoot(root, expirationTime);
24372 finishSyncRender(root, workInProgressRootExitStatus, expirationTime);
24373 } // Before exiting, make sure there's a callback scheduled for the next
24374 // pending level.
24375
24376
24377 ensureRootIsScheduled(root);
24378 }
24379 }
24380
24381 return null;
24382}
24383
24384function finishSyncRender(root, exitStatus, expirationTime) {
24385 if (exitStatus === RootLocked) {
24386 // This root has a lock that prevents it from committing. Exit. If we
24387 // begin work on the root again, without any intervening updates, it
24388 // will finish without doing additional work.
24389 markRootSuspendedAtTime(root, expirationTime);
24390 } else {
24391 // Set this to null to indicate there's no in-progress render.
24392 workInProgressRoot = null;
24393
24394 {
24395 if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) {
24396 flushSuspensePriorityWarningInDEV();
24397 }
24398 }
24399
24400 commitRoot(root);
24401 }
24402}
24403
24404function flushRoot(root, expirationTime) {
24405 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24406 (function () {
24407 {
24408 {
24409 throw ReactError(Error("work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method."));
24410 }
24411 }
24412 })();
24413 }
24414
24415 markRootExpiredAtTime(root, expirationTime);
24416 ensureRootIsScheduled(root);
24417 flushSyncCallbackQueue();
24418}
24419function flushDiscreteUpdates() {
24420 // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
24421 // However, `act` uses `batchedUpdates`, so there's no way to distinguish
24422 // those two cases. Need to fix this before exposing flushDiscreteUpdates
24423 // as a public API.
24424 if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
24425 if (true && (executionContext & RenderContext) !== NoContext) {
24426 warning$1(false, 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
24427 } // We're already rendering, so we can't synchronously flush pending work.
24428 // This is probably a nested event dispatch triggered by a lifecycle/effect,
24429 // like `el.focus()`. Exit.
24430
24431
24432 return;
24433 }
24434
24435 flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
24436 // they fire before the next serial event.
24437
24438 flushPassiveEffects();
24439}
24440
24441function resolveLocksOnRoot(root, expirationTime) {
24442 var firstBatch = root.firstBatch;
24443
24444 if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
24445 scheduleCallback(NormalPriority, function () {
24446 firstBatch._onComplete();
24447
24448 return null;
24449 });
24450 workInProgressRootExitStatus = RootLocked;
24451 }
24452}
24453
24454
24455
24456
24457function flushPendingDiscreteUpdates() {
24458 if (rootsWithPendingDiscreteUpdates !== null) {
24459 // For each root with pending discrete updates, schedule a callback to
24460 // immediately flush them.
24461 var roots = rootsWithPendingDiscreteUpdates;
24462 rootsWithPendingDiscreteUpdates = null;
24463 roots.forEach(function (expirationTime, root) {
24464 markRootExpiredAtTime(root, expirationTime);
24465 ensureRootIsScheduled(root);
24466 }); // Now flush the immediate queue.
24467
24468 flushSyncCallbackQueue();
24469 }
24470}
24471
24472function batchedUpdates$1(fn, a) {
24473 var prevExecutionContext = executionContext;
24474 executionContext |= BatchedContext;
24475
24476 try {
24477 return fn(a);
24478 } finally {
24479 executionContext = prevExecutionContext;
24480
24481 if (executionContext === NoContext) {
24482 // Flush the immediate callbacks that were scheduled during this batch
24483 flushSyncCallbackQueue();
24484 }
24485 }
24486}
24487function batchedEventUpdates$1(fn, a) {
24488 var prevExecutionContext = executionContext;
24489 executionContext |= EventContext;
24490
24491 try {
24492 return fn(a);
24493 } finally {
24494 executionContext = prevExecutionContext;
24495
24496 if (executionContext === NoContext) {
24497 // Flush the immediate callbacks that were scheduled during this batch
24498 flushSyncCallbackQueue();
24499 }
24500 }
24501}
24502function discreteUpdates$1(fn, a, b, c) {
24503 var prevExecutionContext = executionContext;
24504 executionContext |= DiscreteEventContext;
24505
24506 try {
24507 // Should this
24508 return runWithPriority$2(UserBlockingPriority$2, fn.bind(null, a, b, c));
24509 } finally {
24510 executionContext = prevExecutionContext;
24511
24512 if (executionContext === NoContext) {
24513 // Flush the immediate callbacks that were scheduled during this batch
24514 flushSyncCallbackQueue();
24515 }
24516 }
24517}
24518function unbatchedUpdates(fn, a) {
24519 var prevExecutionContext = executionContext;
24520 executionContext &= ~BatchedContext;
24521 executionContext |= LegacyUnbatchedContext;
24522
24523 try {
24524 return fn(a);
24525 } finally {
24526 executionContext = prevExecutionContext;
24527
24528 if (executionContext === NoContext) {
24529 // Flush the immediate callbacks that were scheduled during this batch
24530 flushSyncCallbackQueue();
24531 }
24532 }
24533}
24534function flushSync(fn, a) {
24535 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24536 (function () {
24537 {
24538 {
24539 throw ReactError(Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering."));
24540 }
24541 }
24542 })();
24543 }
24544
24545 var prevExecutionContext = executionContext;
24546 executionContext |= BatchedContext;
24547
24548 try {
24549 return runWithPriority$2(ImmediatePriority, fn.bind(null, a));
24550 } finally {
24551 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
24552 // Note that this will happen even if batchedUpdates is higher up
24553 // the stack.
24554
24555 flushSyncCallbackQueue();
24556 }
24557}
24558function flushControlled(fn) {
24559 var prevExecutionContext = executionContext;
24560 executionContext |= BatchedContext;
24561
24562 try {
24563 runWithPriority$2(ImmediatePriority, fn);
24564 } finally {
24565 executionContext = prevExecutionContext;
24566
24567 if (executionContext === NoContext) {
24568 // Flush the immediate callbacks that were scheduled during this batch
24569 flushSyncCallbackQueue();
24570 }
24571 }
24572}
24573
24574function prepareFreshStack(root, expirationTime) {
24575 root.finishedWork = null;
24576 root.finishedExpirationTime = NoWork;
24577 var timeoutHandle = root.timeoutHandle;
24578
24579 if (timeoutHandle !== noTimeout) {
24580 // The root previous suspended and scheduled a timeout to commit a fallback
24581 // state. Now that we have additional work, cancel the timeout.
24582 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
24583
24584 cancelTimeout(timeoutHandle);
24585 }
24586
24587 if (workInProgress !== null) {
24588 var interruptedWork = workInProgress.return;
24589
24590 while (interruptedWork !== null) {
24591 unwindInterruptedWork(interruptedWork);
24592 interruptedWork = interruptedWork.return;
24593 }
24594 }
24595
24596 workInProgressRoot = root;
24597 workInProgress = createWorkInProgress(root.current, null, expirationTime);
24598 renderExpirationTime = expirationTime;
24599 workInProgressRootExitStatus = RootIncomplete;
24600 workInProgressRootFatalError = null;
24601 workInProgressRootLatestProcessedExpirationTime = Sync;
24602 workInProgressRootLatestSuspenseTimeout = Sync;
24603 workInProgressRootCanSuspendUsingConfig = null;
24604 workInProgressRootNextUnprocessedUpdateTime = NoWork;
24605 workInProgressRootHasPendingPing = false;
24606
24607 if (enableSchedulerTracing) {
24608 spawnedWorkDuringRender = null;
24609 }
24610
24611 {
24612 ReactStrictModeWarnings.discardPendingWarnings();
24613 componentsThatTriggeredHighPriSuspend = null;
24614 }
24615}
24616
24617function handleError(root, thrownValue) {
24618 do {
24619 try {
24620 // Reset module-level state that was set during the render phase.
24621 resetContextDependencies();
24622 resetHooks();
24623
24624 if (workInProgress === null || workInProgress.return === null) {
24625 // Expected to be working on a non-root fiber. This is a fatal error
24626 // because there's no ancestor that can handle it; the root is
24627 // supposed to capture all errors that weren't caught by an error
24628 // boundary.
24629 workInProgressRootExitStatus = RootFatalErrored;
24630 workInProgressRootFatalError = thrownValue;
24631 return null;
24632 }
24633
24634 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
24635 // Record the time spent rendering before an error was thrown. This
24636 // avoids inaccurate Profiler durations in the case of a
24637 // suspended render.
24638 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
24639 }
24640
24641 throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime);
24642 workInProgress = completeUnitOfWork(workInProgress);
24643 } catch (yetAnotherThrownValue) {
24644 // Something in the return path also threw.
24645 thrownValue = yetAnotherThrownValue;
24646 continue;
24647 } // Return to the normal work loop.
24648
24649
24650 return;
24651 } while (true);
24652}
24653
24654function pushDispatcher(root) {
24655 var prevDispatcher = ReactCurrentDispatcher.current;
24656 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
24657
24658 if (prevDispatcher === null) {
24659 // The React isomorphic package does not include a default dispatcher.
24660 // Instead the first renderer will lazily attach one, in order to give
24661 // nicer error messages.
24662 return ContextOnlyDispatcher;
24663 } else {
24664 return prevDispatcher;
24665 }
24666}
24667
24668function popDispatcher(prevDispatcher) {
24669 ReactCurrentDispatcher.current = prevDispatcher;
24670}
24671
24672function pushInteractions(root) {
24673 if (enableSchedulerTracing) {
24674 var prevInteractions = __interactionsRef.current;
24675 __interactionsRef.current = root.memoizedInteractions;
24676 return prevInteractions;
24677 }
24678
24679 return null;
24680}
24681
24682function popInteractions(prevInteractions) {
24683 if (enableSchedulerTracing) {
24684 __interactionsRef.current = prevInteractions;
24685 }
24686}
24687
24688function markCommitTimeOfFallback() {
24689 globalMostRecentFallbackTime = now();
24690}
24691function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
24692 if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
24693 workInProgressRootLatestProcessedExpirationTime = expirationTime;
24694 }
24695
24696 if (suspenseConfig !== null) {
24697 if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
24698 workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
24699
24700 workInProgressRootCanSuspendUsingConfig = suspenseConfig;
24701 }
24702 }
24703}
24704function markUnprocessedUpdateTime(expirationTime) {
24705 if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
24706 workInProgressRootNextUnprocessedUpdateTime = expirationTime;
24707 }
24708}
24709function renderDidSuspend() {
24710 if (workInProgressRootExitStatus === RootIncomplete) {
24711 workInProgressRootExitStatus = RootSuspended;
24712 }
24713}
24714function renderDidSuspendDelayIfPossible() {
24715 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
24716 workInProgressRootExitStatus = RootSuspendedWithDelay;
24717 } // Check if there's a lower priority update somewhere else in the tree.
24718
24719
24720 if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
24721 // Mark the current render as suspended, and then mark that there's a
24722 // pending update.
24723 // TODO: This should immediately interrupt the current render, instead
24724 // of waiting until the next time we yield.
24725 markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
24726 markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
24727 }
24728}
24729function renderDidError() {
24730 if (workInProgressRootExitStatus !== RootCompleted) {
24731 workInProgressRootExitStatus = RootErrored;
24732 }
24733} // Called during render to determine if anything has suspended.
24734// Returns false if we're not sure.
24735
24736function renderHasNotSuspendedYet() {
24737 // If something errored or completed, we can't really be sure,
24738 // so those are false.
24739 return workInProgressRootExitStatus === RootIncomplete;
24740}
24741
24742function inferTimeFromExpirationTime(expirationTime) {
24743 // We don't know exactly when the update was scheduled, but we can infer an
24744 // approximate start time from the expiration time.
24745 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24746 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
24747}
24748
24749function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
24750 // We don't know exactly when the update was scheduled, but we can infer an
24751 // approximate start time from the expiration time by subtracting the timeout
24752 // that was added to the event time.
24753 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24754 return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
24755} // The work loop is an extremely hot path. Tell Closure not to inline it.
24756
24757/** @noinline */
24758
24759
24760function workLoopSync() {
24761 // Already timed out, so perform work without checking if we need to yield.
24762 while (workInProgress !== null) {
24763 workInProgress = performUnitOfWork(workInProgress);
24764 }
24765}
24766/** @noinline */
24767
24768
24769function workLoopConcurrent() {
24770 // Perform work until Scheduler asks us to yield
24771 while (workInProgress !== null && !shouldYield()) {
24772 workInProgress = performUnitOfWork(workInProgress);
24773 }
24774}
24775
24776function performUnitOfWork(unitOfWork) {
24777 // The current, flushed, state of this fiber is the alternate. Ideally
24778 // nothing should rely on this, but relying on it here means that we don't
24779 // need an additional field on the work in progress.
24780 var current$$1 = unitOfWork.alternate;
24781 startWorkTimer(unitOfWork);
24782 setCurrentFiber(unitOfWork);
24783 var next;
24784
24785 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
24786 startProfilerTimer(unitOfWork);
24787 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24788 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
24789 } else {
24790 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24791 }
24792
24793 resetCurrentFiber();
24794 unitOfWork.memoizedProps = unitOfWork.pendingProps;
24795
24796 if (next === null) {
24797 // If this doesn't spawn new work, complete the current work.
24798 next = completeUnitOfWork(unitOfWork);
24799 }
24800
24801 ReactCurrentOwner$2.current = null;
24802 return next;
24803}
24804
24805function completeUnitOfWork(unitOfWork) {
24806 // Attempt to complete the current unit of work, then move to the next
24807 // sibling. If there are no more siblings, return to the parent fiber.
24808 workInProgress = unitOfWork;
24809
24810 do {
24811 // The current, flushed, state of this fiber is the alternate. Ideally
24812 // nothing should rely on this, but relying on it here means that we don't
24813 // need an additional field on the work in progress.
24814 var current$$1 = workInProgress.alternate;
24815 var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
24816
24817 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
24818 setCurrentFiber(workInProgress);
24819 var next = void 0;
24820
24821 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode) {
24822 next = completeWork(current$$1, workInProgress, renderExpirationTime);
24823 } else {
24824 startProfilerTimer(workInProgress);
24825 next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error.
24826
24827 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
24828 }
24829
24830 stopWorkTimer(workInProgress);
24831 resetCurrentFiber();
24832 resetChildExpirationTime(workInProgress);
24833
24834 if (next !== null) {
24835 // Completing this fiber spawned new work. Work on that next.
24836 return next;
24837 }
24838
24839 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
24840 (returnFiber.effectTag & Incomplete) === NoEffect) {
24841 // Append all the effects of the subtree and this fiber onto the effect
24842 // list of the parent. The completion order of the children affects the
24843 // side-effect order.
24844 if (returnFiber.firstEffect === null) {
24845 returnFiber.firstEffect = workInProgress.firstEffect;
24846 }
24847
24848 if (workInProgress.lastEffect !== null) {
24849 if (returnFiber.lastEffect !== null) {
24850 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
24851 }
24852
24853 returnFiber.lastEffect = workInProgress.lastEffect;
24854 } // If this fiber had side-effects, we append it AFTER the children's
24855 // side-effects. We can perform certain side-effects earlier if needed,
24856 // by doing multiple passes over the effect list. We don't want to
24857 // schedule our own side-effect on our own list because if end up
24858 // reusing children we'll schedule this effect onto itself since we're
24859 // at the end.
24860
24861
24862 var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
24863 // list. PerformedWork effect is read by React DevTools but shouldn't be
24864 // committed.
24865
24866 if (effectTag > PerformedWork) {
24867 if (returnFiber.lastEffect !== null) {
24868 returnFiber.lastEffect.nextEffect = workInProgress;
24869 } else {
24870 returnFiber.firstEffect = workInProgress;
24871 }
24872
24873 returnFiber.lastEffect = workInProgress;
24874 }
24875 }
24876 } else {
24877 // This fiber did not complete because something threw. Pop values off
24878 // the stack without entering the complete phase. If this is a boundary,
24879 // capture values if possible.
24880 var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time.
24881
24882
24883 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode) {
24884 // Record the render duration for the fiber that errored.
24885 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
24886
24887 var actualDuration = workInProgress.actualDuration;
24888 var child = workInProgress.child;
24889
24890 while (child !== null) {
24891 actualDuration += child.actualDuration;
24892 child = child.sibling;
24893 }
24894
24895 workInProgress.actualDuration = actualDuration;
24896 }
24897
24898 if (_next !== null) {
24899 // If completing this work spawned new work, do that next. We'll come
24900 // back here again.
24901 // Since we're restarting, remove anything that is not a host effect
24902 // from the effect tag.
24903 // TODO: The name stopFailedWorkTimer is misleading because Suspense
24904 // also captures and restarts.
24905 stopFailedWorkTimer(workInProgress);
24906 _next.effectTag &= HostEffectMask;
24907 return _next;
24908 }
24909
24910 stopWorkTimer(workInProgress);
24911
24912 if (returnFiber !== null) {
24913 // Mark the parent fiber as incomplete and clear its effect list.
24914 returnFiber.firstEffect = returnFiber.lastEffect = null;
24915 returnFiber.effectTag |= Incomplete;
24916 }
24917 }
24918
24919 var siblingFiber = workInProgress.sibling;
24920
24921 if (siblingFiber !== null) {
24922 // If there is more work to do in this returnFiber, do that next.
24923 return siblingFiber;
24924 } // Otherwise, return to the parent
24925
24926
24927 workInProgress = returnFiber;
24928 } while (workInProgress !== null); // We've reached the root.
24929
24930
24931 if (workInProgressRootExitStatus === RootIncomplete) {
24932 workInProgressRootExitStatus = RootCompleted;
24933 }
24934
24935 return null;
24936}
24937
24938function getRemainingExpirationTime(fiber) {
24939 var updateExpirationTime = fiber.expirationTime;
24940 var childExpirationTime = fiber.childExpirationTime;
24941 return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
24942}
24943
24944function resetChildExpirationTime(completedWork) {
24945 if (renderExpirationTime !== Never && completedWork.childExpirationTime === Never) {
24946 // The children of this component are hidden. Don't bubble their
24947 // expiration times.
24948 return;
24949 }
24950
24951 var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
24952
24953 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
24954 // In profiling mode, resetChildExpirationTime is also used to reset
24955 // profiler durations.
24956 var actualDuration = completedWork.actualDuration;
24957 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
24958 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
24959 // When work is done, it should bubble to the parent's actualDuration. If
24960 // the fiber has not been cloned though, (meaning no work was done), then
24961 // this value will reflect the amount of time spent working on a previous
24962 // render. In that case it should not bubble. We determine whether it was
24963 // cloned by comparing the child pointer.
24964
24965 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
24966 var child = completedWork.child;
24967
24968 while (child !== null) {
24969 var childUpdateExpirationTime = child.expirationTime;
24970 var childChildExpirationTime = child.childExpirationTime;
24971
24972 if (childUpdateExpirationTime > newChildExpirationTime) {
24973 newChildExpirationTime = childUpdateExpirationTime;
24974 }
24975
24976 if (childChildExpirationTime > newChildExpirationTime) {
24977 newChildExpirationTime = childChildExpirationTime;
24978 }
24979
24980 if (shouldBubbleActualDurations) {
24981 actualDuration += child.actualDuration;
24982 }
24983
24984 treeBaseDuration += child.treeBaseDuration;
24985 child = child.sibling;
24986 }
24987
24988 completedWork.actualDuration = actualDuration;
24989 completedWork.treeBaseDuration = treeBaseDuration;
24990 } else {
24991 var _child = completedWork.child;
24992
24993 while (_child !== null) {
24994 var _childUpdateExpirationTime = _child.expirationTime;
24995 var _childChildExpirationTime = _child.childExpirationTime;
24996
24997 if (_childUpdateExpirationTime > newChildExpirationTime) {
24998 newChildExpirationTime = _childUpdateExpirationTime;
24999 }
25000
25001 if (_childChildExpirationTime > newChildExpirationTime) {
25002 newChildExpirationTime = _childChildExpirationTime;
25003 }
25004
25005 _child = _child.sibling;
25006 }
25007 }
25008
25009 completedWork.childExpirationTime = newChildExpirationTime;
25010}
25011
25012function commitRoot(root) {
25013 var renderPriorityLevel = getCurrentPriorityLevel();
25014 runWithPriority$2(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
25015 return null;
25016}
25017
25018function commitRootImpl(root, renderPriorityLevel) {
25019 flushPassiveEffects();
25020 flushRenderPhaseStrictModeWarningsInDEV();
25021
25022 (function () {
25023 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25024 {
25025 throw ReactError(Error("Should not already be working."));
25026 }
25027 }
25028 })();
25029
25030 var finishedWork = root.finishedWork;
25031 var expirationTime = root.finishedExpirationTime;
25032
25033 if (finishedWork === null) {
25034 return null;
25035 }
25036
25037 root.finishedWork = null;
25038 root.finishedExpirationTime = NoWork;
25039
25040 (function () {
25041 if (!(finishedWork !== root.current)) {
25042 {
25043 throw ReactError(Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."));
25044 }
25045 }
25046 })(); // commitRoot never returns a continuation; it always finishes synchronously.
25047 // So we can clear these now to allow a new callback to be scheduled.
25048
25049
25050 root.callbackNode = null;
25051 root.callbackExpirationTime = NoWork;
25052 root.callbackPriority = NoPriority;
25053 root.nextKnownPendingLevel = NoWork;
25054 startCommitTimer(); // Update the first and last pending times on this root. The new first
25055 // pending time is whatever is left on the root fiber.
25056
25057 var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
25058 markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
25059
25060 if (root === workInProgressRoot) {
25061 // We can reset these now that they are finished.
25062 workInProgressRoot = null;
25063 workInProgress = null;
25064 renderExpirationTime = NoWork;
25065 } else {} // This indicates that the last root we worked on is not the same one that
25066 // we're committing now. This most commonly happens when a suspended root
25067 // times out.
25068 // Get the list of effects.
25069
25070
25071 var firstEffect;
25072
25073 if (finishedWork.effectTag > PerformedWork) {
25074 // A fiber's effect list consists only of its children, not itself. So if
25075 // the root has an effect, we need to add it to the end of the list. The
25076 // resulting list is the set that would belong to the root's parent, if it
25077 // had one; that is, all the effects in the tree including the root.
25078 if (finishedWork.lastEffect !== null) {
25079 finishedWork.lastEffect.nextEffect = finishedWork;
25080 firstEffect = finishedWork.firstEffect;
25081 } else {
25082 firstEffect = finishedWork;
25083 }
25084 } else {
25085 // There is no effect on the root.
25086 firstEffect = finishedWork.firstEffect;
25087 }
25088
25089 if (firstEffect !== null) {
25090 var prevExecutionContext = executionContext;
25091 executionContext |= CommitContext;
25092 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
25093
25094 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
25095 // of the effect list for each phase: all mutation effects come before all
25096 // layout effects, and so on.
25097 // The first phase a "before mutation" phase. We use this phase to read the
25098 // state of the host tree right before we mutate it. This is where
25099 // getSnapshotBeforeUpdate is called.
25100
25101 startCommitSnapshotEffectsTimer();
25102 prepareForCommit(root.containerInfo);
25103 nextEffect = firstEffect;
25104
25105 do {
25106 {
25107 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
25108
25109 if (hasCaughtError()) {
25110 (function () {
25111 if (!(nextEffect !== null)) {
25112 {
25113 throw ReactError(Error("Should be working on an effect."));
25114 }
25115 }
25116 })();
25117
25118 var error = clearCaughtError();
25119 captureCommitPhaseError(nextEffect, error);
25120 nextEffect = nextEffect.nextEffect;
25121 }
25122 }
25123 } while (nextEffect !== null);
25124
25125 stopCommitSnapshotEffectsTimer();
25126
25127 if (enableProfilerTimer) {
25128 // Mark the current commit time to be shared by all Profilers in this
25129 // batch. This enables them to be grouped later.
25130 recordCommitTime();
25131 } // The next phase is the mutation phase, where we mutate the host tree.
25132
25133
25134 startCommitHostEffectsTimer();
25135 nextEffect = firstEffect;
25136
25137 do {
25138 {
25139 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
25140
25141 if (hasCaughtError()) {
25142 (function () {
25143 if (!(nextEffect !== null)) {
25144 {
25145 throw ReactError(Error("Should be working on an effect."));
25146 }
25147 }
25148 })();
25149
25150 var _error = clearCaughtError();
25151
25152 captureCommitPhaseError(nextEffect, _error);
25153 nextEffect = nextEffect.nextEffect;
25154 }
25155 }
25156 } while (nextEffect !== null);
25157
25158 stopCommitHostEffectsTimer();
25159 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
25160 // the mutation phase, so that the previous tree is still current during
25161 // componentWillUnmount, but before the layout phase, so that the finished
25162 // work is current during componentDidMount/Update.
25163
25164 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
25165 // the host tree after it's been mutated. The idiomatic use case for this is
25166 // layout, but class component lifecycles also fire here for legacy reasons.
25167
25168 startCommitLifeCyclesTimer();
25169 nextEffect = firstEffect;
25170
25171 do {
25172 {
25173 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
25174
25175 if (hasCaughtError()) {
25176 (function () {
25177 if (!(nextEffect !== null)) {
25178 {
25179 throw ReactError(Error("Should be working on an effect."));
25180 }
25181 }
25182 })();
25183
25184 var _error2 = clearCaughtError();
25185
25186 captureCommitPhaseError(nextEffect, _error2);
25187 nextEffect = nextEffect.nextEffect;
25188 }
25189 }
25190 } while (nextEffect !== null);
25191
25192 stopCommitLifeCyclesTimer();
25193 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
25194 // opportunity to paint.
25195
25196 requestPaint();
25197
25198 if (enableSchedulerTracing) {
25199 popInteractions(prevInteractions);
25200 }
25201
25202 executionContext = prevExecutionContext;
25203 } else {
25204 // No effects.
25205 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
25206 // no effects.
25207 // TODO: Maybe there's a better way to report this.
25208
25209 startCommitSnapshotEffectsTimer();
25210 stopCommitSnapshotEffectsTimer();
25211
25212 if (enableProfilerTimer) {
25213 recordCommitTime();
25214 }
25215
25216 startCommitHostEffectsTimer();
25217 stopCommitHostEffectsTimer();
25218 startCommitLifeCyclesTimer();
25219 stopCommitLifeCyclesTimer();
25220 }
25221
25222 stopCommitTimer();
25223 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
25224
25225 if (rootDoesHavePassiveEffects) {
25226 // This commit has passive effects. Stash a reference to them. But don't
25227 // schedule a callback until after flushing layout work.
25228 rootDoesHavePassiveEffects = false;
25229 rootWithPendingPassiveEffects = root;
25230 pendingPassiveEffectsExpirationTime = expirationTime;
25231 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
25232 } else {
25233 // We are done with the effect chain at this point so let's clear the
25234 // nextEffect pointers to assist with GC. If we have passive effects, we'll
25235 // clear this in flushPassiveEffects.
25236 nextEffect = firstEffect;
25237
25238 while (nextEffect !== null) {
25239 var nextNextEffect = nextEffect.nextEffect;
25240 nextEffect.nextEffect = null;
25241 nextEffect = nextNextEffect;
25242 }
25243 } // Check if there's remaining work on this root
25244
25245
25246 var remainingExpirationTime = root.firstPendingTime;
25247
25248 if (remainingExpirationTime !== NoWork) {
25249 if (enableSchedulerTracing) {
25250 if (spawnedWorkDuringRender !== null) {
25251 var expirationTimes = spawnedWorkDuringRender;
25252 spawnedWorkDuringRender = null;
25253
25254 for (var i = 0; i < expirationTimes.length; i++) {
25255 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
25256 }
25257 }
25258
25259 schedulePendingInteractions(root, remainingExpirationTime);
25260 }
25261 } else {
25262 // If there's no remaining work, we can clear the set of already failed
25263 // error boundaries.
25264 legacyErrorBoundariesThatAlreadyFailed = null;
25265 }
25266
25267 if (enableSchedulerTracing) {
25268 if (!rootDidHavePassiveEffects) {
25269 // If there are no passive effects, then we can complete the pending interactions.
25270 // Otherwise, we'll wait until after the passive effects are flushed.
25271 // Wait to do this until after remaining work has been scheduled,
25272 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
25273 finishPendingInteractions(root, expirationTime);
25274 }
25275 }
25276
25277 if (remainingExpirationTime === Sync) {
25278 // Count the number of times the root synchronously re-renders without
25279 // finishing. If there are too many, it indicates an infinite update loop.
25280 if (root === rootWithNestedUpdates) {
25281 nestedUpdateCount++;
25282 } else {
25283 nestedUpdateCount = 0;
25284 rootWithNestedUpdates = root;
25285 }
25286 } else {
25287 nestedUpdateCount = 0;
25288 }
25289
25290 onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
25291 // additional work on this root is scheduled.
25292
25293 ensureRootIsScheduled(root);
25294
25295 if (hasUncaughtError) {
25296 hasUncaughtError = false;
25297 var _error3 = firstUncaughtError;
25298 firstUncaughtError = null;
25299 throw _error3;
25300 }
25301
25302 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
25303 // This is a legacy edge case. We just committed the initial mount of
25304 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
25305 // synchronously, but layout updates should be deferred until the end
25306 // of the batch.
25307 return null;
25308 } // If layout work was scheduled, flush it now.
25309
25310
25311 flushSyncCallbackQueue();
25312 return null;
25313}
25314
25315function commitBeforeMutationEffects() {
25316 while (nextEffect !== null) {
25317 var effectTag = nextEffect.effectTag;
25318
25319 if ((effectTag & Snapshot) !== NoEffect) {
25320 setCurrentFiber(nextEffect);
25321 recordEffect();
25322 var current$$1 = nextEffect.alternate;
25323 commitBeforeMutationLifeCycles(current$$1, nextEffect);
25324 resetCurrentFiber();
25325 }
25326
25327 if ((effectTag & Passive) !== NoEffect) {
25328 // If there are passive effects, schedule a callback to flush at
25329 // the earliest opportunity.
25330 if (!rootDoesHavePassiveEffects) {
25331 rootDoesHavePassiveEffects = true;
25332 scheduleCallback(NormalPriority, function () {
25333 flushPassiveEffects();
25334 return null;
25335 });
25336 }
25337 }
25338
25339 nextEffect = nextEffect.nextEffect;
25340 }
25341}
25342
25343function commitMutationEffects(root, renderPriorityLevel) {
25344 // TODO: Should probably move the bulk of this function to commitWork.
25345 while (nextEffect !== null) {
25346 setCurrentFiber(nextEffect);
25347 var effectTag = nextEffect.effectTag;
25348
25349 if (effectTag & ContentReset) {
25350 commitResetTextContent(nextEffect);
25351 }
25352
25353 if (effectTag & Ref) {
25354 var current$$1 = nextEffect.alternate;
25355
25356 if (current$$1 !== null) {
25357 commitDetachRef(current$$1);
25358 }
25359 } // The following switch statement is only concerned about placement,
25360 // updates, and deletions. To avoid needing to add a case for every possible
25361 // bitmap value, we remove the secondary effects from the effect tag and
25362 // switch on that value.
25363
25364
25365 var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
25366
25367 switch (primaryEffectTag) {
25368 case Placement:
25369 {
25370 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25371 // inserted, before any life-cycles like componentDidMount gets called.
25372 // TODO: findDOMNode doesn't rely on this any more but isMounted does
25373 // and isMounted is deprecated anyway so we should be able to kill this.
25374
25375 nextEffect.effectTag &= ~Placement;
25376 break;
25377 }
25378
25379 case PlacementAndUpdate:
25380 {
25381 // Placement
25382 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25383 // inserted, before any life-cycles like componentDidMount gets called.
25384
25385 nextEffect.effectTag &= ~Placement; // Update
25386
25387 var _current = nextEffect.alternate;
25388 commitWork(_current, nextEffect);
25389 break;
25390 }
25391
25392 case Hydrating:
25393 {
25394 nextEffect.effectTag &= ~Hydrating;
25395 break;
25396 }
25397
25398 case HydratingAndUpdate:
25399 {
25400 nextEffect.effectTag &= ~Hydrating; // Update
25401
25402 var _current2 = nextEffect.alternate;
25403 commitWork(_current2, nextEffect);
25404 break;
25405 }
25406
25407 case Update:
25408 {
25409 var _current3 = nextEffect.alternate;
25410 commitWork(_current3, nextEffect);
25411 break;
25412 }
25413
25414 case Deletion:
25415 {
25416 commitDeletion(root, nextEffect, renderPriorityLevel);
25417 break;
25418 }
25419 } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
25420
25421
25422 recordEffect();
25423 resetCurrentFiber();
25424 nextEffect = nextEffect.nextEffect;
25425 }
25426}
25427
25428function commitLayoutEffects(root, committedExpirationTime) {
25429 // TODO: Should probably move the bulk of this function to commitWork.
25430 while (nextEffect !== null) {
25431 setCurrentFiber(nextEffect);
25432 var effectTag = nextEffect.effectTag;
25433
25434 if (effectTag & (Update | Callback)) {
25435 recordEffect();
25436 var current$$1 = nextEffect.alternate;
25437 commitLifeCycles(root, current$$1, nextEffect, committedExpirationTime);
25438 }
25439
25440 if (effectTag & Ref) {
25441 recordEffect();
25442 commitAttachRef(nextEffect);
25443 }
25444
25445 resetCurrentFiber();
25446 nextEffect = nextEffect.nextEffect;
25447 }
25448}
25449
25450function flushPassiveEffects() {
25451 if (pendingPassiveEffectsRenderPriority !== NoPriority) {
25452 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
25453 pendingPassiveEffectsRenderPriority = NoPriority;
25454 return runWithPriority$2(priorityLevel, flushPassiveEffectsImpl);
25455 }
25456}
25457
25458function flushPassiveEffectsImpl() {
25459 if (rootWithPendingPassiveEffects === null) {
25460 return false;
25461 }
25462
25463 var root = rootWithPendingPassiveEffects;
25464 var expirationTime = pendingPassiveEffectsExpirationTime;
25465 rootWithPendingPassiveEffects = null;
25466 pendingPassiveEffectsExpirationTime = NoWork;
25467
25468 (function () {
25469 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25470 {
25471 throw ReactError(Error("Cannot flush passive effects while already rendering."));
25472 }
25473 }
25474 })();
25475
25476 var prevExecutionContext = executionContext;
25477 executionContext |= CommitContext;
25478 var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root
25479 // fiber, because the root is not part of its own effect list. This could
25480 // change in the future.
25481
25482 var effect = root.current.firstEffect;
25483
25484 while (effect !== null) {
25485 {
25486 setCurrentFiber(effect);
25487 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
25488
25489 if (hasCaughtError()) {
25490 (function () {
25491 if (!(effect !== null)) {
25492 {
25493 throw ReactError(Error("Should be working on an effect."));
25494 }
25495 }
25496 })();
25497
25498 var error = clearCaughtError();
25499 captureCommitPhaseError(effect, error);
25500 }
25501
25502 resetCurrentFiber();
25503 }
25504
25505 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
25506
25507 effect.nextEffect = null;
25508 effect = nextNextEffect;
25509 }
25510
25511 if (enableSchedulerTracing) {
25512 popInteractions(prevInteractions);
25513 finishPendingInteractions(root, expirationTime);
25514 }
25515
25516 executionContext = prevExecutionContext;
25517 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
25518 // exceeds the limit, we'll fire a warning.
25519
25520 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
25521 return true;
25522}
25523
25524function isAlreadyFailedLegacyErrorBoundary(instance) {
25525 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
25526}
25527function markLegacyErrorBoundaryAsFailed(instance) {
25528 if (legacyErrorBoundariesThatAlreadyFailed === null) {
25529 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
25530 } else {
25531 legacyErrorBoundariesThatAlreadyFailed.add(instance);
25532 }
25533}
25534
25535function prepareToThrowUncaughtError(error) {
25536 if (!hasUncaughtError) {
25537 hasUncaughtError = true;
25538 firstUncaughtError = error;
25539 }
25540}
25541
25542var onUncaughtError = prepareToThrowUncaughtError;
25543
25544function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
25545 var errorInfo = createCapturedValue(error, sourceFiber);
25546 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
25547 enqueueUpdate(rootFiber, update);
25548 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
25549
25550 if (root !== null) {
25551 ensureRootIsScheduled(root);
25552 schedulePendingInteractions(root, Sync);
25553 }
25554}
25555
25556function captureCommitPhaseError(sourceFiber, error) {
25557 if (sourceFiber.tag === HostRoot) {
25558 // Error was thrown at the root. There is no parent, so the root
25559 // itself should capture it.
25560 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
25561 return;
25562 }
25563
25564 var fiber = sourceFiber.return;
25565
25566 while (fiber !== null) {
25567 if (fiber.tag === HostRoot) {
25568 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
25569 return;
25570 } else if (fiber.tag === ClassComponent) {
25571 var ctor = fiber.type;
25572 var instance = fiber.stateNode;
25573
25574 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
25575 var errorInfo = createCapturedValue(error, sourceFiber);
25576 var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
25577 Sync);
25578 enqueueUpdate(fiber, update);
25579 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
25580
25581 if (root !== null) {
25582 ensureRootIsScheduled(root);
25583 schedulePendingInteractions(root, Sync);
25584 }
25585
25586 return;
25587 }
25588 }
25589
25590 fiber = fiber.return;
25591 }
25592}
25593function pingSuspendedRoot(root, thenable, suspendedTime) {
25594 var pingCache = root.pingCache;
25595
25596 if (pingCache !== null) {
25597 // The thenable resolved, so we no longer need to memoize, because it will
25598 // never be thrown again.
25599 pingCache.delete(thenable);
25600 }
25601
25602 if (workInProgressRoot === root && renderExpirationTime === suspendedTime) {
25603 // Received a ping at the same priority level at which we're currently
25604 // rendering. We might want to restart this render. This should mirror
25605 // the logic of whether or not a root suspends once it completes.
25606 // TODO: If we're rendering sync either due to Sync, Batched or expired,
25607 // we should probably never restart.
25608 // If we're suspended with delay, we'll always suspend so we can always
25609 // restart. If we're suspended without any updates, it might be a retry.
25610 // If it's early in the retry we can restart. We can't know for sure
25611 // whether we'll eventually process an update during this render pass,
25612 // but it's somewhat unlikely that we get to a ping before that, since
25613 // getting to the root most update is usually very fast.
25614 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
25615 // Restart from the root. Don't need to schedule a ping because
25616 // we're already working on this tree.
25617 prepareFreshStack(root, renderExpirationTime);
25618 } else {
25619 // Even though we can't restart right now, we might get an
25620 // opportunity later. So we mark this render as having a ping.
25621 workInProgressRootHasPendingPing = true;
25622 }
25623
25624 return;
25625 }
25626
25627 if (!isRootSuspendedAtTime(root, suspendedTime)) {
25628 // The root is no longer suspended at this time.
25629 return;
25630 }
25631
25632 var lastPingedTime = root.lastPingedTime;
25633
25634 if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
25635 // There's already a lower priority ping scheduled.
25636 return;
25637 } // Mark the time at which this ping was scheduled.
25638
25639
25640 root.lastPingedTime = suspendedTime;
25641
25642 if (root.finishedExpirationTime === suspendedTime) {
25643 // If there's a pending fallback waiting to commit, throw it away.
25644 root.finishedExpirationTime = NoWork;
25645 root.finishedWork = null;
25646 }
25647
25648 ensureRootIsScheduled(root);
25649 schedulePendingInteractions(root, suspendedTime);
25650}
25651
25652function retryTimedOutBoundary(boundaryFiber, retryTime) {
25653 // The boundary fiber (a Suspense component or SuspenseList component)
25654 // previously was rendered in its fallback state. One of the promises that
25655 // suspended it has resolved, which means at least part of the tree was
25656 // likely unblocked. Try rendering again, at a new expiration time.
25657 if (retryTime === Never) {
25658 var suspenseConfig = null; // Retries don't carry over the already committed update.
25659
25660 var currentTime = requestCurrentTime();
25661 retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
25662 } // TODO: Special case idle priority?
25663
25664
25665 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
25666
25667 if (root !== null) {
25668 ensureRootIsScheduled(root);
25669 schedulePendingInteractions(root, retryTime);
25670 }
25671}
25672
25673function retryDehydratedSuspenseBoundary(boundaryFiber) {
25674 var suspenseState = boundaryFiber.memoizedState;
25675 var retryTime = Never;
25676
25677 if (suspenseState !== null) {
25678 retryTime = suspenseState.retryTime;
25679 }
25680
25681 retryTimedOutBoundary(boundaryFiber, retryTime);
25682}
25683function resolveRetryThenable(boundaryFiber, thenable) {
25684 var retryTime = Never; // Default
25685
25686 var retryCache;
25687
25688 if (enableSuspenseServerRenderer) {
25689 switch (boundaryFiber.tag) {
25690 case SuspenseComponent:
25691 retryCache = boundaryFiber.stateNode;
25692 var suspenseState = boundaryFiber.memoizedState;
25693
25694 if (suspenseState !== null) {
25695 retryTime = suspenseState.retryTime;
25696 }
25697
25698 break;
25699
25700 case SuspenseListComponent:
25701 retryCache = boundaryFiber.stateNode;
25702 break;
25703
25704 default:
25705 (function () {
25706 {
25707 {
25708 throw ReactError(Error("Pinged unknown suspense boundary type. This is probably a bug in React."));
25709 }
25710 }
25711 })();
25712
25713 }
25714 } else {
25715 retryCache = boundaryFiber.stateNode;
25716 }
25717
25718 if (retryCache !== null) {
25719 // The thenable resolved, so we no longer need to memoize, because it will
25720 // never be thrown again.
25721 retryCache.delete(thenable);
25722 }
25723
25724 retryTimedOutBoundary(boundaryFiber, retryTime);
25725} // Computes the next Just Noticeable Difference (JND) boundary.
25726// The theory is that a person can't tell the difference between small differences in time.
25727// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
25728// difference in the experience. However, waiting for longer might mean that we can avoid
25729// showing an intermediate loading state. The longer we have already waited, the harder it
25730// is to tell small differences in time. Therefore, the longer we've already waited,
25731// the longer we can wait additionally. At some point we have to give up though.
25732// We pick a train model where the next boundary commits at a consistent schedule.
25733// These particular numbers are vague estimates. We expect to adjust them based on research.
25734
25735function jnd(timeElapsed) {
25736 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
25737}
25738
25739function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
25740 var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
25741
25742 if (busyMinDurationMs <= 0) {
25743 return 0;
25744 }
25745
25746 var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
25747
25748 var currentTimeMs = now();
25749 var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
25750 var timeElapsed = currentTimeMs - eventTimeMs;
25751
25752 if (timeElapsed <= busyDelayMs) {
25753 // If we haven't yet waited longer than the initial delay, we don't
25754 // have to wait any additional time.
25755 return 0;
25756 }
25757
25758 var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
25759
25760 return msUntilTimeout;
25761}
25762
25763function checkForNestedUpdates() {
25764 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
25765 nestedUpdateCount = 0;
25766 rootWithNestedUpdates = null;
25767
25768 (function () {
25769 {
25770 {
25771 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."));
25772 }
25773 }
25774 })();
25775 }
25776
25777 {
25778 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
25779 nestedPassiveUpdateCount = 0;
25780 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.');
25781 }
25782 }
25783}
25784
25785function flushRenderPhaseStrictModeWarningsInDEV() {
25786 {
25787 ReactStrictModeWarnings.flushLegacyContextWarning();
25788
25789 if (warnAboutDeprecatedLifecycles) {
25790 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
25791 }
25792 }
25793}
25794
25795function stopFinishedWorkLoopTimer() {
25796 var didCompleteRoot = true;
25797 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25798 interruptedBy = null;
25799}
25800
25801function stopInterruptedWorkLoopTimer() {
25802 // TODO: Track which fiber caused the interruption.
25803 var didCompleteRoot = false;
25804 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25805 interruptedBy = null;
25806}
25807
25808function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
25809 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime) {
25810 interruptedBy = fiberThatReceivedUpdate;
25811 }
25812}
25813
25814var didWarnStateUpdateForUnmountedComponent = null;
25815
25816function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
25817 {
25818 var tag = fiber.tag;
25819
25820 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
25821 // Only warn for user-defined components, not internal ones like Suspense.
25822 return;
25823 } // We show the whole stack but dedupe on the top component's name because
25824 // the problematic code almost always lies inside that component.
25825
25826
25827 var componentName = getComponentName(fiber.type) || 'ReactComponent';
25828
25829 if (didWarnStateUpdateForUnmountedComponent !== null) {
25830 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
25831 return;
25832 }
25833
25834 didWarnStateUpdateForUnmountedComponent.add(componentName);
25835 } else {
25836 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
25837 }
25838
25839 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));
25840 }
25841}
25842
25843var beginWork$$1;
25844
25845if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
25846 var dummyFiber = null;
25847
25848 beginWork$$1 = function (current$$1, unitOfWork, expirationTime) {
25849 // If a component throws an error, we replay it again in a synchronously
25850 // dispatched event, so that the debugger will treat it as an uncaught
25851 // error See ReactErrorUtils for more information.
25852 // Before entering the begin phase, copy the work-in-progress onto a dummy
25853 // fiber. If beginWork throws, we'll use this to reset the state.
25854 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
25855
25856 try {
25857 return beginWork$1(current$$1, unitOfWork, expirationTime);
25858 } catch (originalError) {
25859 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
25860 // Don't replay promises. Treat everything else like an error.
25861 throw originalError;
25862 } // Keep this code in sync with renderRoot; any changes here must have
25863 // corresponding changes there.
25864
25865
25866 resetContextDependencies();
25867 resetHooks(); // Unwind the failed stack frame
25868
25869 unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
25870
25871 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
25872
25873 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
25874 // Reset the profiler timer.
25875 startProfilerTimer(unitOfWork);
25876 } // Run beginWork again.
25877
25878
25879 invokeGuardedCallback(null, beginWork$1, null, current$$1, unitOfWork, expirationTime);
25880
25881 if (hasCaughtError()) {
25882 var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
25883 // Rethrow this error instead of the original one.
25884
25885 throw replayError;
25886 } else {
25887 // This branch is reachable if the render phase is impure.
25888 throw originalError;
25889 }
25890 }
25891 };
25892} else {
25893 beginWork$$1 = beginWork$1;
25894}
25895
25896var didWarnAboutUpdateInRender = false;
25897var didWarnAboutUpdateInGetChildContext = false;
25898
25899function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
25900 {
25901 if (fiber.tag === ClassComponent) {
25902 switch (phase) {
25903 case 'getChildContext':
25904 if (didWarnAboutUpdateInGetChildContext) {
25905 return;
25906 }
25907
25908 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
25909 didWarnAboutUpdateInGetChildContext = true;
25910 break;
25911
25912 case 'render':
25913 if (didWarnAboutUpdateInRender) {
25914 return;
25915 }
25916
25917 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.');
25918 didWarnAboutUpdateInRender = true;
25919 break;
25920 }
25921 }
25922 }
25923} // a 'shared' variable that changes when act() opens/closes in tests.
25924
25925
25926var IsThisRendererActing = {
25927 current: false
25928};
25929function warnIfNotScopedWithMatchingAct(fiber) {
25930 {
25931 if (warnsIfNotActing === true && IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
25932 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));
25933 }
25934 }
25935}
25936function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
25937 {
25938 if (warnsIfNotActing === true && (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25939 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));
25940 }
25941 }
25942}
25943
25944function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
25945 {
25946 if (warnsIfNotActing === true && executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25947 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));
25948 }
25949 }
25950}
25951
25952var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
25953
25954var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
25955// scheduler is the actual recommendation. The alternative could be a testing build,
25956// a new lib, or whatever; we dunno just yet. This message is for early adopters
25957// to get their tests right.
25958
25959function warnIfUnmockedScheduler(fiber) {
25960 {
25961 if (didWarnAboutUnmockedScheduler === false && unstable_flushAllWithoutAsserting === undefined) {
25962 if (fiber.mode & BatchedMode || fiber.mode & ConcurrentMode) {
25963 didWarnAboutUnmockedScheduler = true;
25964 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');
25965 } else if (warnAboutUnmockedScheduler === true) {
25966 didWarnAboutUnmockedScheduler = true;
25967 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');
25968 }
25969 }
25970 }
25971}
25972var componentsThatTriggeredHighPriSuspend = null;
25973function checkForWrongSuspensePriorityInDEV(sourceFiber) {
25974 {
25975 var currentPriorityLevel = getCurrentPriorityLevel();
25976
25977 if ((sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$2 || currentPriorityLevel === ImmediatePriority)) {
25978 var workInProgressNode = sourceFiber;
25979
25980 while (workInProgressNode !== null) {
25981 // Add the component that triggered the suspense
25982 var current$$1 = workInProgressNode.alternate;
25983
25984 if (current$$1 !== null) {
25985 // TODO: warn component that triggers the high priority
25986 // suspend is the HostRoot
25987 switch (workInProgressNode.tag) {
25988 case ClassComponent:
25989 // Loop through the component's update queue and see whether the component
25990 // has triggered any high priority updates
25991 var updateQueue = current$$1.updateQueue;
25992
25993 if (updateQueue !== null) {
25994 var update = updateQueue.firstUpdate;
25995
25996 while (update !== null) {
25997 var priorityLevel = update.priority;
25998
25999 if (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority) {
26000 if (componentsThatTriggeredHighPriSuspend === null) {
26001 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
26002 } else {
26003 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26004 }
26005
26006 break;
26007 }
26008
26009 update = update.next;
26010 }
26011 }
26012
26013 break;
26014
26015 case FunctionComponent:
26016 case ForwardRef:
26017 case SimpleMemoComponent:
26018 if (workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null) {
26019 var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether
26020 // the component has triggered any high pri updates
26021
26022 while (_update !== null) {
26023 var priority = _update.priority;
26024
26025 if (priority === UserBlockingPriority$2 || priority === ImmediatePriority) {
26026 if (componentsThatTriggeredHighPriSuspend === null) {
26027 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
26028 } else {
26029 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26030 }
26031
26032 break;
26033 }
26034
26035 if (_update.next === workInProgressNode.memoizedState.baseUpdate) {
26036 break;
26037 }
26038
26039 _update = _update.next;
26040 }
26041 }
26042
26043 break;
26044
26045 default:
26046 break;
26047 }
26048 }
26049
26050 workInProgressNode = workInProgressNode.return;
26051 }
26052 }
26053 }
26054}
26055
26056function flushSuspensePriorityWarningInDEV() {
26057 {
26058 if (componentsThatTriggeredHighPriSuspend !== null) {
26059 var componentNames = [];
26060 componentsThatTriggeredHighPriSuspend.forEach(function (name) {
26061 return componentNames.push(name);
26062 });
26063 componentsThatTriggeredHighPriSuspend = null;
26064
26065 if (componentNames.length > 0) {
26066 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
26067 componentNames.sort().join(', '));
26068 }
26069 }
26070 }
26071}
26072
26073function computeThreadID(root, expirationTime) {
26074 // Interaction threads are unique per root and expiration time.
26075 return expirationTime * 1000 + root.interactionThreadID;
26076}
26077
26078function markSpawnedWork(expirationTime) {
26079 if (!enableSchedulerTracing) {
26080 return;
26081 }
26082
26083 if (spawnedWorkDuringRender === null) {
26084 spawnedWorkDuringRender = [expirationTime];
26085 } else {
26086 spawnedWorkDuringRender.push(expirationTime);
26087 }
26088}
26089
26090function scheduleInteractions(root, expirationTime, interactions) {
26091 if (!enableSchedulerTracing) {
26092 return;
26093 }
26094
26095 if (interactions.size > 0) {
26096 var pendingInteractionMap = root.pendingInteractionMap;
26097 var pendingInteractions = pendingInteractionMap.get(expirationTime);
26098
26099 if (pendingInteractions != null) {
26100 interactions.forEach(function (interaction) {
26101 if (!pendingInteractions.has(interaction)) {
26102 // Update the pending async work count for previously unscheduled interaction.
26103 interaction.__count++;
26104 }
26105
26106 pendingInteractions.add(interaction);
26107 });
26108 } else {
26109 pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
26110
26111 interactions.forEach(function (interaction) {
26112 interaction.__count++;
26113 });
26114 }
26115
26116 var subscriber = __subscriberRef.current;
26117
26118 if (subscriber !== null) {
26119 var threadID = computeThreadID(root, expirationTime);
26120 subscriber.onWorkScheduled(interactions, threadID);
26121 }
26122 }
26123}
26124
26125function schedulePendingInteractions(root, expirationTime) {
26126 // This is called when work is scheduled on a root.
26127 // It associates the current interactions with the newly-scheduled expiration.
26128 // They will be restored when that expiration is later committed.
26129 if (!enableSchedulerTracing) {
26130 return;
26131 }
26132
26133 scheduleInteractions(root, expirationTime, __interactionsRef.current);
26134}
26135
26136function startWorkOnPendingInteractions(root, expirationTime) {
26137 // This is called when new work is started on a root.
26138 if (!enableSchedulerTracing) {
26139 return;
26140 } // Determine which interactions this batch of work currently includes, So that
26141 // we can accurately attribute time spent working on it, And so that cascading
26142 // work triggered during the render phase will be associated with it.
26143
26144
26145 var interactions = new Set();
26146 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26147 if (scheduledExpirationTime >= expirationTime) {
26148 scheduledInteractions.forEach(function (interaction) {
26149 return interactions.add(interaction);
26150 });
26151 }
26152 }); // Store the current set of interactions on the FiberRoot for a few reasons:
26153 // We can re-use it in hot functions like renderRoot() without having to
26154 // recalculate it. We will also use it in commitWork() to pass to any Profiler
26155 // onRender() hooks. This also provides DevTools with a way to access it when
26156 // the onCommitRoot() hook is called.
26157
26158 root.memoizedInteractions = interactions;
26159
26160 if (interactions.size > 0) {
26161 var subscriber = __subscriberRef.current;
26162
26163 if (subscriber !== null) {
26164 var threadID = computeThreadID(root, expirationTime);
26165
26166 try {
26167 subscriber.onWorkStarted(interactions, threadID);
26168 } catch (error) {
26169 // If the subscriber throws, rethrow it in a separate task
26170 scheduleCallback(ImmediatePriority, function () {
26171 throw error;
26172 });
26173 }
26174 }
26175 }
26176}
26177
26178function finishPendingInteractions(root, committedExpirationTime) {
26179 if (!enableSchedulerTracing) {
26180 return;
26181 }
26182
26183 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
26184 var subscriber;
26185
26186 try {
26187 subscriber = __subscriberRef.current;
26188
26189 if (subscriber !== null && root.memoizedInteractions.size > 0) {
26190 var threadID = computeThreadID(root, committedExpirationTime);
26191 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
26192 }
26193 } catch (error) {
26194 // If the subscriber throws, rethrow it in a separate task
26195 scheduleCallback(ImmediatePriority, function () {
26196 throw error;
26197 });
26198 } finally {
26199 // Clear completed interactions from the pending Map.
26200 // Unless the render was suspended or cascading work was scheduled,
26201 // In which case– leave pending interactions until the subsequent render.
26202 var pendingInteractionMap = root.pendingInteractionMap;
26203 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26204 // Only decrement the pending interaction count if we're done.
26205 // If there's still work at the current priority,
26206 // That indicates that we are waiting for suspense data.
26207 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
26208 pendingInteractionMap.delete(scheduledExpirationTime);
26209 scheduledInteractions.forEach(function (interaction) {
26210 interaction.__count--;
26211
26212 if (subscriber !== null && interaction.__count === 0) {
26213 try {
26214 subscriber.onInteractionScheduledWorkCompleted(interaction);
26215 } catch (error) {
26216 // If the subscriber throws, rethrow it in a separate task
26217 scheduleCallback(ImmediatePriority, function () {
26218 throw error;
26219 });
26220 }
26221 }
26222 });
26223 }
26224 });
26225 }
26226}
26227
26228var onCommitFiberRoot = null;
26229var onCommitFiberUnmount = null;
26230var hasLoggedError = false;
26231var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
26232function injectInternals(internals) {
26233 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
26234 // No DevTools
26235 return false;
26236 }
26237
26238 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
26239
26240 if (hook.isDisabled) {
26241 // This isn't a real property on the hook, but it can be set to opt out
26242 // of DevTools integration and associated warnings and logs.
26243 // https://github.com/facebook/react/issues/3877
26244 return true;
26245 }
26246
26247 if (!hook.supportsFiber) {
26248 {
26249 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');
26250 } // DevTools exists, even though it doesn't support Fiber.
26251
26252
26253 return true;
26254 }
26255
26256 try {
26257 var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
26258
26259 onCommitFiberRoot = function (root, expirationTime) {
26260 try {
26261 var didError = (root.current.effectTag & DidCapture) === DidCapture;
26262
26263 if (enableProfilerTimer) {
26264 var currentTime = requestCurrentTime();
26265 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
26266 hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
26267 } else {
26268 hook.onCommitFiberRoot(rendererID, root, undefined, didError);
26269 }
26270 } catch (err) {
26271 if (true && !hasLoggedError) {
26272 hasLoggedError = true;
26273 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26274 }
26275 }
26276 };
26277
26278 onCommitFiberUnmount = function (fiber) {
26279 try {
26280 hook.onCommitFiberUnmount(rendererID, fiber);
26281 } catch (err) {
26282 if (true && !hasLoggedError) {
26283 hasLoggedError = true;
26284 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26285 }
26286 }
26287 };
26288 } catch (err) {
26289 // Catch all errors because it is unsafe to throw during initialization.
26290 {
26291 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
26292 }
26293 } // DevTools exists
26294
26295
26296 return true;
26297}
26298function onCommitRoot(root, expirationTime) {
26299 if (typeof onCommitFiberRoot === 'function') {
26300 onCommitFiberRoot(root, expirationTime);
26301 }
26302}
26303function onCommitUnmount(fiber) {
26304 if (typeof onCommitFiberUnmount === 'function') {
26305 onCommitFiberUnmount(fiber);
26306 }
26307}
26308
26309var hasBadMapPolyfill;
26310
26311{
26312 hasBadMapPolyfill = false;
26313
26314 try {
26315 var nonExtensibleObject = Object.preventExtensions({});
26316 var testMap = new Map([[nonExtensibleObject, null]]);
26317 var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
26318 // https://github.com/rollup/rollup/issues/1771
26319 // TODO: we can remove these if Rollup fixes the bug.
26320
26321 testMap.set(0, 0);
26322 testSet.add(0);
26323 } catch (e) {
26324 // TODO: Consider warning about bad polyfills
26325 hasBadMapPolyfill = true;
26326 }
26327}
26328
26329var debugCounter = 1;
26330
26331function FiberNode(tag, pendingProps, key, mode) {
26332 // Instance
26333 this.tag = tag;
26334 this.key = key;
26335 this.elementType = null;
26336 this.type = null;
26337 this.stateNode = null; // Fiber
26338
26339 this.return = null;
26340 this.child = null;
26341 this.sibling = null;
26342 this.index = 0;
26343 this.ref = null;
26344 this.pendingProps = pendingProps;
26345 this.memoizedProps = null;
26346 this.updateQueue = null;
26347 this.memoizedState = null;
26348 this.dependencies = null;
26349 this.mode = mode; // Effects
26350
26351 this.effectTag = NoEffect;
26352 this.nextEffect = null;
26353 this.firstEffect = null;
26354 this.lastEffect = null;
26355 this.expirationTime = NoWork;
26356 this.childExpirationTime = NoWork;
26357 this.alternate = null;
26358
26359 if (enableProfilerTimer) {
26360 // Note: The following is done to avoid a v8 performance cliff.
26361 //
26362 // Initializing the fields below to smis and later updating them with
26363 // double values will cause Fibers to end up having separate shapes.
26364 // This behavior/bug has something to do with Object.preventExtension().
26365 // Fortunately this only impacts DEV builds.
26366 // Unfortunately it makes React unusably slow for some applications.
26367 // To work around this, initialize the fields below with doubles.
26368 //
26369 // Learn more about this here:
26370 // https://github.com/facebook/react/issues/14365
26371 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
26372 this.actualDuration = Number.NaN;
26373 this.actualStartTime = Number.NaN;
26374 this.selfBaseDuration = Number.NaN;
26375 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
26376 // This won't trigger the performance cliff mentioned above,
26377 // and it simplifies other profiler code (including DevTools).
26378
26379 this.actualDuration = 0;
26380 this.actualStartTime = -1;
26381 this.selfBaseDuration = 0;
26382 this.treeBaseDuration = 0;
26383 } // This is normally DEV-only except www when it adds listeners.
26384 // TODO: remove the User Timing integration in favor of Root Events.
26385
26386
26387 if (enableUserTimingAPI) {
26388 this._debugID = debugCounter++;
26389 this._debugIsCurrentlyTiming = false;
26390 }
26391
26392 {
26393 this._debugSource = null;
26394 this._debugOwner = null;
26395 this._debugNeedsRemount = false;
26396 this._debugHookTypes = null;
26397
26398 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
26399 Object.preventExtensions(this);
26400 }
26401 }
26402} // This is a constructor function, rather than a POJO constructor, still
26403// please ensure we do the following:
26404// 1) Nobody should add any instance methods on this. Instance methods can be
26405// more difficult to predict when they get optimized and they are almost
26406// never inlined properly in static compilers.
26407// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
26408// always know when it is a fiber.
26409// 3) We might want to experiment with using numeric keys since they are easier
26410// to optimize in a non-JIT environment.
26411// 4) We can easily go from a constructor to a createFiber object literal if that
26412// is faster.
26413// 5) It should be easy to port this to a C struct and keep a C implementation
26414// compatible.
26415
26416
26417var createFiber = function (tag, pendingProps, key, mode) {
26418 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
26419 return new FiberNode(tag, pendingProps, key, mode);
26420};
26421
26422function shouldConstruct(Component) {
26423 var prototype = Component.prototype;
26424 return !!(prototype && prototype.isReactComponent);
26425}
26426
26427function isSimpleFunctionComponent(type) {
26428 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
26429}
26430function resolveLazyComponentTag(Component) {
26431 if (typeof Component === 'function') {
26432 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
26433 } else if (Component !== undefined && Component !== null) {
26434 var $$typeof = Component.$$typeof;
26435
26436 if ($$typeof === REACT_FORWARD_REF_TYPE) {
26437 return ForwardRef;
26438 }
26439
26440 if ($$typeof === REACT_MEMO_TYPE) {
26441 return MemoComponent;
26442 }
26443 }
26444
26445 return IndeterminateComponent;
26446} // This is used to create an alternate fiber to do work on.
26447
26448function createWorkInProgress(current, pendingProps, expirationTime) {
26449 var workInProgress = current.alternate;
26450
26451 if (workInProgress === null) {
26452 // We use a double buffering pooling technique because we know that we'll
26453 // only ever need at most two versions of a tree. We pool the "other" unused
26454 // node that we're free to reuse. This is lazily created to avoid allocating
26455 // extra objects for things that are never updated. It also allow us to
26456 // reclaim the extra memory if needed.
26457 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
26458 workInProgress.elementType = current.elementType;
26459 workInProgress.type = current.type;
26460 workInProgress.stateNode = current.stateNode;
26461
26462 {
26463 // DEV-only fields
26464 workInProgress._debugID = current._debugID;
26465 workInProgress._debugSource = current._debugSource;
26466 workInProgress._debugOwner = current._debugOwner;
26467 workInProgress._debugHookTypes = current._debugHookTypes;
26468 }
26469
26470 workInProgress.alternate = current;
26471 current.alternate = workInProgress;
26472 } else {
26473 workInProgress.pendingProps = pendingProps; // We already have an alternate.
26474 // Reset the effect tag.
26475
26476 workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
26477
26478 workInProgress.nextEffect = null;
26479 workInProgress.firstEffect = null;
26480 workInProgress.lastEffect = null;
26481
26482 if (enableProfilerTimer) {
26483 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
26484 // This prevents time from endlessly accumulating in new commits.
26485 // This has the downside of resetting values for different priority renders,
26486 // But works for yielding (the common case) and should support resuming.
26487 workInProgress.actualDuration = 0;
26488 workInProgress.actualStartTime = -1;
26489 }
26490 }
26491
26492 workInProgress.childExpirationTime = current.childExpirationTime;
26493 workInProgress.expirationTime = current.expirationTime;
26494 workInProgress.child = current.child;
26495 workInProgress.memoizedProps = current.memoizedProps;
26496 workInProgress.memoizedState = current.memoizedState;
26497 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26498 // it cannot be shared with the current fiber.
26499
26500 var currentDependencies = current.dependencies;
26501 workInProgress.dependencies = currentDependencies === null ? null : {
26502 expirationTime: currentDependencies.expirationTime,
26503 firstContext: currentDependencies.firstContext,
26504 responders: currentDependencies.responders
26505 }; // These will be overridden during the parent's reconciliation
26506
26507 workInProgress.sibling = current.sibling;
26508 workInProgress.index = current.index;
26509 workInProgress.ref = current.ref;
26510
26511 if (enableProfilerTimer) {
26512 workInProgress.selfBaseDuration = current.selfBaseDuration;
26513 workInProgress.treeBaseDuration = current.treeBaseDuration;
26514 }
26515
26516 {
26517 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
26518
26519 switch (workInProgress.tag) {
26520 case IndeterminateComponent:
26521 case FunctionComponent:
26522 case SimpleMemoComponent:
26523 workInProgress.type = resolveFunctionForHotReloading(current.type);
26524 break;
26525
26526 case ClassComponent:
26527 workInProgress.type = resolveClassForHotReloading(current.type);
26528 break;
26529
26530 case ForwardRef:
26531 workInProgress.type = resolveForwardRefForHotReloading(current.type);
26532 break;
26533
26534 default:
26535 break;
26536 }
26537 }
26538
26539 return workInProgress;
26540} // Used to reuse a Fiber for a second pass.
26541
26542function resetWorkInProgress(workInProgress, renderExpirationTime) {
26543 // This resets the Fiber to what createFiber or createWorkInProgress would
26544 // have set the values to before during the first pass. Ideally this wouldn't
26545 // be necessary but unfortunately many code paths reads from the workInProgress
26546 // when they should be reading from current and writing to workInProgress.
26547 // We assume pendingProps, index, key, ref, return are still untouched to
26548 // avoid doing another reconciliation.
26549 // Reset the effect tag but keep any Placement tags, since that's something
26550 // that child fiber is setting, not the reconciliation.
26551 workInProgress.effectTag &= Placement; // The effect list is no longer valid.
26552
26553 workInProgress.nextEffect = null;
26554 workInProgress.firstEffect = null;
26555 workInProgress.lastEffect = null;
26556 var current = workInProgress.alternate;
26557
26558 if (current === null) {
26559 // Reset to createFiber's initial values.
26560 workInProgress.childExpirationTime = NoWork;
26561 workInProgress.expirationTime = renderExpirationTime;
26562 workInProgress.child = null;
26563 workInProgress.memoizedProps = null;
26564 workInProgress.memoizedState = null;
26565 workInProgress.updateQueue = null;
26566 workInProgress.dependencies = null;
26567
26568 if (enableProfilerTimer) {
26569 // Note: We don't reset the actualTime counts. It's useful to accumulate
26570 // actual time across multiple render passes.
26571 workInProgress.selfBaseDuration = 0;
26572 workInProgress.treeBaseDuration = 0;
26573 }
26574 } else {
26575 // Reset to the cloned values that createWorkInProgress would've.
26576 workInProgress.childExpirationTime = current.childExpirationTime;
26577 workInProgress.expirationTime = current.expirationTime;
26578 workInProgress.child = current.child;
26579 workInProgress.memoizedProps = current.memoizedProps;
26580 workInProgress.memoizedState = current.memoizedState;
26581 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26582 // it cannot be shared with the current fiber.
26583
26584 var currentDependencies = current.dependencies;
26585 workInProgress.dependencies = currentDependencies === null ? null : {
26586 expirationTime: currentDependencies.expirationTime,
26587 firstContext: currentDependencies.firstContext,
26588 responders: currentDependencies.responders
26589 };
26590
26591 if (enableProfilerTimer) {
26592 // Note: We don't reset the actualTime counts. It's useful to accumulate
26593 // actual time across multiple render passes.
26594 workInProgress.selfBaseDuration = current.selfBaseDuration;
26595 workInProgress.treeBaseDuration = current.treeBaseDuration;
26596 }
26597 }
26598
26599 return workInProgress;
26600}
26601function createHostRootFiber(tag) {
26602 var mode;
26603
26604 if (tag === ConcurrentRoot) {
26605 mode = ConcurrentMode | BatchedMode | StrictMode;
26606 } else if (tag === BatchedRoot) {
26607 mode = BatchedMode | StrictMode;
26608 } else {
26609 mode = NoMode;
26610 }
26611
26612 if (enableProfilerTimer && isDevToolsPresent) {
26613 // Always collect profile timings when DevTools are present.
26614 // This enables DevTools to start capturing timing at any point–
26615 // Without some nodes in the tree having empty base times.
26616 mode |= ProfileMode;
26617 }
26618
26619 return createFiber(HostRoot, null, null, mode);
26620}
26621function createFiberFromTypeAndProps(type, // React$ElementType
26622key, pendingProps, owner, mode, expirationTime) {
26623 var fiber;
26624 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
26625
26626 var resolvedType = type;
26627
26628 if (typeof type === 'function') {
26629 if (shouldConstruct(type)) {
26630 fiberTag = ClassComponent;
26631
26632 {
26633 resolvedType = resolveClassForHotReloading(resolvedType);
26634 }
26635 } else {
26636 {
26637 resolvedType = resolveFunctionForHotReloading(resolvedType);
26638 }
26639 }
26640 } else if (typeof type === 'string') {
26641 fiberTag = HostComponent;
26642 } else {
26643 getTag: switch (type) {
26644 case REACT_FRAGMENT_TYPE:
26645 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
26646
26647 case REACT_CONCURRENT_MODE_TYPE:
26648 fiberTag = Mode;
26649 mode |= ConcurrentMode | BatchedMode | StrictMode;
26650 break;
26651
26652 case REACT_STRICT_MODE_TYPE:
26653 fiberTag = Mode;
26654 mode |= StrictMode;
26655 break;
26656
26657 case REACT_PROFILER_TYPE:
26658 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
26659
26660 case REACT_SUSPENSE_TYPE:
26661 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
26662
26663 case REACT_SUSPENSE_LIST_TYPE:
26664 return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
26665
26666 default:
26667 {
26668 if (typeof type === 'object' && type !== null) {
26669 switch (type.$$typeof) {
26670 case REACT_PROVIDER_TYPE:
26671 fiberTag = ContextProvider;
26672 break getTag;
26673
26674 case REACT_CONTEXT_TYPE:
26675 // This is a consumer
26676 fiberTag = ContextConsumer;
26677 break getTag;
26678
26679 case REACT_FORWARD_REF_TYPE:
26680 fiberTag = ForwardRef;
26681
26682 {
26683 resolvedType = resolveForwardRefForHotReloading(resolvedType);
26684 }
26685
26686 break getTag;
26687
26688 case REACT_MEMO_TYPE:
26689 fiberTag = MemoComponent;
26690 break getTag;
26691
26692 case REACT_LAZY_TYPE:
26693 fiberTag = LazyComponent;
26694 resolvedType = null;
26695 break getTag;
26696
26697 case REACT_FUNDAMENTAL_TYPE:
26698 if (enableFundamentalAPI) {
26699 return createFiberFromFundamental(type, pendingProps, mode, expirationTime, key);
26700 }
26701
26702 break;
26703
26704 case REACT_SCOPE_TYPE:
26705 if (enableScopeAPI) {
26706 return createFiberFromScope(type, pendingProps, mode, expirationTime, key);
26707 }
26708
26709 }
26710 }
26711
26712 var info = '';
26713
26714 {
26715 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
26716 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.';
26717 }
26718
26719 var ownerName = owner ? getComponentName(owner.type) : null;
26720
26721 if (ownerName) {
26722 info += '\n\nCheck the render method of `' + ownerName + '`.';
26723 }
26724 }
26725
26726 (function () {
26727 {
26728 {
26729 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));
26730 }
26731 }
26732 })();
26733 }
26734 }
26735 }
26736
26737 fiber = createFiber(fiberTag, pendingProps, key, mode);
26738 fiber.elementType = type;
26739 fiber.type = resolvedType;
26740 fiber.expirationTime = expirationTime;
26741 return fiber;
26742}
26743function createFiberFromElement(element, mode, expirationTime) {
26744 var owner = null;
26745
26746 {
26747 owner = element._owner;
26748 }
26749
26750 var type = element.type;
26751 var key = element.key;
26752 var pendingProps = element.props;
26753 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
26754
26755 {
26756 fiber._debugSource = element._source;
26757 fiber._debugOwner = element._owner;
26758 }
26759
26760 return fiber;
26761}
26762function createFiberFromFragment(elements, mode, expirationTime, key) {
26763 var fiber = createFiber(Fragment, elements, key, mode);
26764 fiber.expirationTime = expirationTime;
26765 return fiber;
26766}
26767function createFiberFromFundamental(fundamentalComponent, pendingProps, mode, expirationTime, key) {
26768 var fiber = createFiber(FundamentalComponent, pendingProps, key, mode);
26769 fiber.elementType = fundamentalComponent;
26770 fiber.type = fundamentalComponent;
26771 fiber.expirationTime = expirationTime;
26772 return fiber;
26773}
26774
26775function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) {
26776 var fiber = createFiber(ScopeComponent, pendingProps, key, mode);
26777 fiber.type = scope;
26778 fiber.elementType = scope;
26779 fiber.expirationTime = expirationTime;
26780 return fiber;
26781}
26782
26783function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
26784 {
26785 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
26786 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
26787 }
26788 }
26789
26790 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
26791
26792 fiber.elementType = REACT_PROFILER_TYPE;
26793 fiber.type = REACT_PROFILER_TYPE;
26794 fiber.expirationTime = expirationTime;
26795 return fiber;
26796}
26797
26798function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
26799 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
26800 // This needs to be fixed in getComponentName so that it relies on the tag
26801 // instead.
26802
26803 fiber.type = REACT_SUSPENSE_TYPE;
26804 fiber.elementType = REACT_SUSPENSE_TYPE;
26805 fiber.expirationTime = expirationTime;
26806 return fiber;
26807}
26808function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
26809 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
26810
26811 {
26812 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
26813 // This needs to be fixed in getComponentName so that it relies on the tag
26814 // instead.
26815 fiber.type = REACT_SUSPENSE_LIST_TYPE;
26816 }
26817
26818 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
26819 fiber.expirationTime = expirationTime;
26820 return fiber;
26821}
26822function createFiberFromText(content, mode, expirationTime) {
26823 var fiber = createFiber(HostText, content, null, mode);
26824 fiber.expirationTime = expirationTime;
26825 return fiber;
26826}
26827function createFiberFromHostInstanceForDeletion() {
26828 var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
26829
26830 fiber.elementType = 'DELETED';
26831 fiber.type = 'DELETED';
26832 return fiber;
26833}
26834function createFiberFromDehydratedFragment(dehydratedNode) {
26835 var fiber = createFiber(DehydratedFragment, null, null, NoMode);
26836 fiber.stateNode = dehydratedNode;
26837 return fiber;
26838}
26839function createFiberFromPortal(portal, mode, expirationTime) {
26840 var pendingProps = portal.children !== null ? portal.children : [];
26841 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
26842 fiber.expirationTime = expirationTime;
26843 fiber.stateNode = {
26844 containerInfo: portal.containerInfo,
26845 pendingChildren: null,
26846 // Used by persistent updates
26847 implementation: portal.implementation
26848 };
26849 return fiber;
26850} // Used for stashing WIP properties to replay failed work in DEV.
26851
26852function assignFiberPropertiesInDEV(target, source) {
26853 if (target === null) {
26854 // This Fiber's initial properties will always be overwritten.
26855 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
26856 target = createFiber(IndeterminateComponent, null, null, NoMode);
26857 } // This is intentionally written as a list of all properties.
26858 // We tried to use Object.assign() instead but this is called in
26859 // the hottest path, and Object.assign() was too slow:
26860 // https://github.com/facebook/react/issues/12502
26861 // This code is DEV-only so size is not a concern.
26862
26863
26864 target.tag = source.tag;
26865 target.key = source.key;
26866 target.elementType = source.elementType;
26867 target.type = source.type;
26868 target.stateNode = source.stateNode;
26869 target.return = source.return;
26870 target.child = source.child;
26871 target.sibling = source.sibling;
26872 target.index = source.index;
26873 target.ref = source.ref;
26874 target.pendingProps = source.pendingProps;
26875 target.memoizedProps = source.memoizedProps;
26876 target.updateQueue = source.updateQueue;
26877 target.memoizedState = source.memoizedState;
26878 target.dependencies = source.dependencies;
26879 target.mode = source.mode;
26880 target.effectTag = source.effectTag;
26881 target.nextEffect = source.nextEffect;
26882 target.firstEffect = source.firstEffect;
26883 target.lastEffect = source.lastEffect;
26884 target.expirationTime = source.expirationTime;
26885 target.childExpirationTime = source.childExpirationTime;
26886 target.alternate = source.alternate;
26887
26888 if (enableProfilerTimer) {
26889 target.actualDuration = source.actualDuration;
26890 target.actualStartTime = source.actualStartTime;
26891 target.selfBaseDuration = source.selfBaseDuration;
26892 target.treeBaseDuration = source.treeBaseDuration;
26893 }
26894
26895 target._debugID = source._debugID;
26896 target._debugSource = source._debugSource;
26897 target._debugOwner = source._debugOwner;
26898 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
26899 target._debugNeedsRemount = source._debugNeedsRemount;
26900 target._debugHookTypes = source._debugHookTypes;
26901 return target;
26902}
26903
26904function FiberRootNode(containerInfo, tag, hydrate) {
26905 this.tag = tag;
26906 this.current = null;
26907 this.containerInfo = containerInfo;
26908 this.pendingChildren = null;
26909 this.pingCache = null;
26910 this.finishedExpirationTime = NoWork;
26911 this.finishedWork = null;
26912 this.timeoutHandle = noTimeout;
26913 this.context = null;
26914 this.pendingContext = null;
26915 this.hydrate = hydrate;
26916 this.firstBatch = null;
26917 this.callbackNode = null;
26918 this.callbackPriority = NoPriority;
26919 this.firstPendingTime = NoWork;
26920 this.firstSuspendedTime = NoWork;
26921 this.lastSuspendedTime = NoWork;
26922 this.nextKnownPendingLevel = NoWork;
26923 this.lastPingedTime = NoWork;
26924 this.lastExpiredTime = NoWork;
26925
26926 if (enableSchedulerTracing) {
26927 this.interactionThreadID = unstable_getThreadID();
26928 this.memoizedInteractions = new Set();
26929 this.pendingInteractionMap = new Map();
26930 }
26931
26932 if (enableSuspenseCallback) {
26933 this.hydrationCallbacks = null;
26934 }
26935}
26936
26937function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
26938 var root = new FiberRootNode(containerInfo, tag, hydrate);
26939
26940 if (enableSuspenseCallback) {
26941 root.hydrationCallbacks = hydrationCallbacks;
26942 } // Cyclic construction. This cheats the type system right now because
26943 // stateNode is any.
26944
26945
26946 var uninitializedFiber = createHostRootFiber(tag);
26947 root.current = uninitializedFiber;
26948 uninitializedFiber.stateNode = root;
26949 return root;
26950}
26951function isRootSuspendedAtTime(root, expirationTime) {
26952 var firstSuspendedTime = root.firstSuspendedTime;
26953 var lastSuspendedTime = root.lastSuspendedTime;
26954 return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
26955}
26956function markRootSuspendedAtTime(root, expirationTime) {
26957 var firstSuspendedTime = root.firstSuspendedTime;
26958 var lastSuspendedTime = root.lastSuspendedTime;
26959
26960 if (firstSuspendedTime < expirationTime) {
26961 root.firstSuspendedTime = expirationTime;
26962 }
26963
26964 if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
26965 root.lastSuspendedTime = expirationTime;
26966 }
26967
26968 if (expirationTime <= root.lastPingedTime) {
26969 root.lastPingedTime = NoWork;
26970 }
26971
26972 if (expirationTime <= root.lastExpiredTime) {
26973 root.lastExpiredTime = NoWork;
26974 }
26975}
26976function markRootUpdatedAtTime(root, expirationTime) {
26977 // Update the range of pending times
26978 var firstPendingTime = root.firstPendingTime;
26979
26980 if (expirationTime > firstPendingTime) {
26981 root.firstPendingTime = expirationTime;
26982 } // Update the range of suspended times. Treat everything lower priority or
26983 // equal to this update as unsuspended.
26984
26985
26986 var firstSuspendedTime = root.firstSuspendedTime;
26987
26988 if (firstSuspendedTime !== NoWork) {
26989 if (expirationTime >= firstSuspendedTime) {
26990 // The entire suspended range is now unsuspended.
26991 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26992 } else if (expirationTime >= root.lastSuspendedTime) {
26993 root.lastSuspendedTime = expirationTime + 1;
26994 } // This is a pending level. Check if it's higher priority than the next
26995 // known pending level.
26996
26997
26998 if (expirationTime > root.nextKnownPendingLevel) {
26999 root.nextKnownPendingLevel = expirationTime;
27000 }
27001 }
27002}
27003function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
27004 // Update the range of pending times
27005 root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
27006 // equal to this update as unsuspended.
27007
27008 if (finishedExpirationTime <= root.lastSuspendedTime) {
27009 // The entire suspended range is now unsuspended.
27010 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
27011 } else if (finishedExpirationTime <= root.firstSuspendedTime) {
27012 // Part of the suspended range is now unsuspended. Narrow the range to
27013 // include everything between the unsuspended time (non-inclusive) and the
27014 // last suspended time.
27015 root.firstSuspendedTime = finishedExpirationTime - 1;
27016 }
27017
27018 if (finishedExpirationTime <= root.lastPingedTime) {
27019 // Clear the pinged time
27020 root.lastPingedTime = NoWork;
27021 }
27022
27023 if (finishedExpirationTime <= root.lastExpiredTime) {
27024 // Clear the expired time
27025 root.lastExpiredTime = NoWork;
27026 }
27027}
27028function markRootExpiredAtTime(root, expirationTime) {
27029 var lastExpiredTime = root.lastExpiredTime;
27030
27031 if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
27032 root.lastExpiredTime = expirationTime;
27033 }
27034}
27035
27036// This lets us hook into Fiber to debug what it's doing.
27037// See https://github.com/facebook/react/pull/8033.
27038// This is not part of the public API, not even for React DevTools.
27039// You may only inject a debugTool if you work on React Fiber itself.
27040var ReactFiberInstrumentation = {
27041 debugTool: null
27042};
27043var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
27044
27045var didWarnAboutNestedUpdates;
27046var didWarnAboutFindNodeInStrictMode;
27047
27048{
27049 didWarnAboutNestedUpdates = false;
27050 didWarnAboutFindNodeInStrictMode = {};
27051}
27052
27053function getContextForSubtree(parentComponent) {
27054 if (!parentComponent) {
27055 return emptyContextObject;
27056 }
27057
27058 var fiber = get(parentComponent);
27059 var parentContext = findCurrentUnmaskedContext(fiber);
27060
27061 if (fiber.tag === ClassComponent) {
27062 var Component = fiber.type;
27063
27064 if (isContextProvider(Component)) {
27065 return processChildContext(fiber, Component, parentContext);
27066 }
27067 }
27068
27069 return parentContext;
27070}
27071
27072function scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback) {
27073 {
27074 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
27075 didWarnAboutNestedUpdates = true;
27076 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');
27077 }
27078 }
27079
27080 var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
27081 // being called "element".
27082
27083 update.payload = {
27084 element: element
27085 };
27086 callback = callback === undefined ? null : callback;
27087
27088 if (callback !== null) {
27089 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
27090 update.callback = callback;
27091 }
27092
27093 enqueueUpdate(current$$1, update);
27094 scheduleWork(current$$1, expirationTime);
27095 return expirationTime;
27096}
27097
27098function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback) {
27099 // TODO: If this is a nested container, this won't be the root.
27100 var current$$1 = container.current;
27101
27102 {
27103 if (ReactFiberInstrumentation_1.debugTool) {
27104 if (current$$1.alternate === null) {
27105 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
27106 } else if (element === null) {
27107 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
27108 } else {
27109 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
27110 }
27111 }
27112 }
27113
27114 var context = getContextForSubtree(parentComponent);
27115
27116 if (container.context === null) {
27117 container.context = context;
27118 } else {
27119 container.pendingContext = context;
27120 }
27121
27122 return scheduleRootUpdate(current$$1, element, expirationTime, suspenseConfig, callback);
27123}
27124
27125function findHostInstance(component) {
27126 var fiber = get(component);
27127
27128 if (fiber === undefined) {
27129 if (typeof component.render === 'function') {
27130 (function () {
27131 {
27132 {
27133 throw ReactError(Error("Unable to find node on an unmounted component."));
27134 }
27135 }
27136 })();
27137 } else {
27138 (function () {
27139 {
27140 {
27141 throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
27142 }
27143 }
27144 })();
27145 }
27146 }
27147
27148 var hostFiber = findCurrentHostFiber(fiber);
27149
27150 if (hostFiber === null) {
27151 return null;
27152 }
27153
27154 return hostFiber.stateNode;
27155}
27156
27157function findHostInstanceWithWarning(component, methodName) {
27158 {
27159 var fiber = get(component);
27160
27161 if (fiber === undefined) {
27162 if (typeof component.render === 'function') {
27163 (function () {
27164 {
27165 {
27166 throw ReactError(Error("Unable to find node on an unmounted component."));
27167 }
27168 }
27169 })();
27170 } else {
27171 (function () {
27172 {
27173 {
27174 throw ReactError(Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component)));
27175 }
27176 }
27177 })();
27178 }
27179 }
27180
27181 var hostFiber = findCurrentHostFiber(fiber);
27182
27183 if (hostFiber === null) {
27184 return null;
27185 }
27186
27187 if (hostFiber.mode & StrictMode) {
27188 var componentName = getComponentName(fiber.type) || 'Component';
27189
27190 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
27191 didWarnAboutFindNodeInStrictMode[componentName] = true;
27192
27193 if (fiber.mode & StrictMode) {
27194 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));
27195 } else {
27196 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));
27197 }
27198 }
27199 }
27200
27201 return hostFiber.stateNode;
27202 }
27203
27204 return findHostInstance(component);
27205}
27206
27207function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
27208 return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
27209}
27210function updateContainer(element, container, parentComponent, callback) {
27211 var current$$1 = container.current;
27212 var currentTime = requestCurrentTime();
27213
27214 {
27215 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
27216 if ('undefined' !== typeof jest) {
27217 warnIfUnmockedScheduler(current$$1);
27218 warnIfNotScopedWithMatchingAct(current$$1);
27219 }
27220 }
27221
27222 var suspenseConfig = requestCurrentSuspenseConfig();
27223 var expirationTime = computeExpirationForFiber(currentTime, current$$1, suspenseConfig);
27224 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, suspenseConfig, callback);
27225}
27226function getPublicRootInstance(container) {
27227 var containerFiber = container.current;
27228
27229 if (!containerFiber.child) {
27230 return null;
27231 }
27232
27233 switch (containerFiber.child.tag) {
27234 case HostComponent:
27235 return getPublicInstance(containerFiber.child.stateNode);
27236
27237 default:
27238 return containerFiber.child.stateNode;
27239 }
27240}
27241function attemptSynchronousHydration$1(fiber) {
27242 switch (fiber.tag) {
27243 case HostRoot:
27244 var root = fiber.stateNode;
27245
27246 if (root.hydrate) {
27247 // Flush the first scheduled "update".
27248 flushRoot(root, root.firstPendingTime);
27249 }
27250
27251 break;
27252
27253 case SuspenseComponent:
27254 flushSync(function () {
27255 return scheduleWork(fiber, Sync);
27256 });
27257 break;
27258 }
27259}
27260function findHostInstanceWithNoPortals(fiber) {
27261 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
27262
27263 if (hostFiber === null) {
27264 return null;
27265 }
27266
27267 if (hostFiber.tag === FundamentalComponent) {
27268 return hostFiber.stateNode.instance;
27269 }
27270
27271 return hostFiber.stateNode;
27272}
27273
27274var shouldSuspendImpl = function (fiber) {
27275 return false;
27276};
27277
27278function shouldSuspend(fiber) {
27279 return shouldSuspendImpl(fiber);
27280}
27281var overrideHookState = null;
27282var overrideProps = null;
27283var scheduleUpdate = null;
27284var setSuspenseHandler = null;
27285
27286{
27287 var copyWithSetImpl = function (obj, path, idx, value) {
27288 if (idx >= path.length) {
27289 return value;
27290 }
27291
27292 var key = path[idx];
27293 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
27294
27295 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
27296 return updated;
27297 };
27298
27299 var copyWithSet = function (obj, path, value) {
27300 return copyWithSetImpl(obj, path, 0, value);
27301 }; // Support DevTools editable values for useState and useReducer.
27302
27303
27304 overrideHookState = function (fiber, id, path, value) {
27305 // For now, the "id" of stateful hooks is just the stateful hook index.
27306 // This may change in the future with e.g. nested hooks.
27307 var currentHook = fiber.memoizedState;
27308
27309 while (currentHook !== null && id > 0) {
27310 currentHook = currentHook.next;
27311 id--;
27312 }
27313
27314 if (currentHook !== null) {
27315 var newState = copyWithSet(currentHook.memoizedState, path, value);
27316 currentHook.memoizedState = newState;
27317 currentHook.baseState = newState; // We aren't actually adding an update to the queue,
27318 // because there is no update we can add for useReducer hooks that won't trigger an error.
27319 // (There's no appropriate action type for DevTools overrides.)
27320 // As a result though, React will see the scheduled update as a noop and bailout.
27321 // Shallow cloning props works as a workaround for now to bypass the bailout check.
27322
27323 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
27324 scheduleWork(fiber, Sync);
27325 }
27326 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
27327
27328
27329 overrideProps = function (fiber, path, value) {
27330 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
27331
27332 if (fiber.alternate) {
27333 fiber.alternate.pendingProps = fiber.pendingProps;
27334 }
27335
27336 scheduleWork(fiber, Sync);
27337 };
27338
27339 scheduleUpdate = function (fiber) {
27340 scheduleWork(fiber, Sync);
27341 };
27342
27343 setSuspenseHandler = function (newShouldSuspendImpl) {
27344 shouldSuspendImpl = newShouldSuspendImpl;
27345 };
27346}
27347
27348function injectIntoDevTools(devToolsConfig) {
27349 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
27350 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
27351 return injectInternals(_assign({}, devToolsConfig, {
27352 overrideHookState: overrideHookState,
27353 overrideProps: overrideProps,
27354 setSuspenseHandler: setSuspenseHandler,
27355 scheduleUpdate: scheduleUpdate,
27356 currentDispatcherRef: ReactCurrentDispatcher,
27357 findHostInstanceByFiber: function (fiber) {
27358 var hostFiber = findCurrentHostFiber(fiber);
27359
27360 if (hostFiber === null) {
27361 return null;
27362 }
27363
27364 return hostFiber.stateNode;
27365 },
27366 findFiberByHostInstance: function (instance) {
27367 if (!findFiberByHostInstance) {
27368 // Might not be implemented by the renderer.
27369 return null;
27370 }
27371
27372 return findFiberByHostInstance(instance);
27373 },
27374 // React Refresh
27375 findHostInstancesForRefresh: findHostInstancesForRefresh,
27376 scheduleRefresh: scheduleRefresh,
27377 scheduleRoot: scheduleRoot,
27378 setRefreshHandler: setRefreshHandler,
27379 // Enables DevTools to append owner stacks to error messages in DEV mode.
27380 getCurrentFiber: function () {
27381 return current;
27382 }
27383 }));
27384}
27385
27386// This file intentionally does *not* have the Flow annotation.
27387// Don't add it. See `./inline-typed.js` for an explanation.
27388
27389function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
27390implementation) {
27391 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
27392 return {
27393 // This tag allow us to uniquely identify this as a React Portal
27394 $$typeof: REACT_PORTAL_TYPE,
27395 key: key == null ? null : '' + key,
27396 children: children,
27397 containerInfo: containerInfo,
27398 implementation: implementation
27399 };
27400}
27401
27402// TODO: this is special because it gets imported during build.
27403
27404var ReactVersion = '16.10.0';
27405
27406// TODO: This type is shared between the reconciler and ReactDOM, but will
27407// eventually be lifted out to the renderer.
27408setAttemptSynchronousHydration(attemptSynchronousHydration$1);
27409var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
27410var topLevelUpdateWarnings;
27411var warnOnInvalidCallback;
27412var didWarnAboutUnstableCreatePortal = false;
27413
27414{
27415 if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
27416 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
27417 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
27418 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');
27419 }
27420
27421 topLevelUpdateWarnings = function (container) {
27422 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
27423 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
27424
27425 if (hostInstance) {
27426 !(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;
27427 }
27428 }
27429
27430 var isRootRenderedBySomeReact = !!container._reactRootContainer;
27431 var rootEl = getReactRootElementInContainer(container);
27432 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
27433 !(!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;
27434 !(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;
27435 };
27436
27437 warnOnInvalidCallback = function (callback, callerName) {
27438 !(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;
27439 };
27440}
27441
27442setRestoreImplementation(restoreControlledState$$1);
27443
27444function ReactBatch(root) {
27445 var expirationTime = computeUniqueAsyncExpiration();
27446 this._expirationTime = expirationTime;
27447 this._root = root;
27448 this._next = null;
27449 this._callbacks = null;
27450 this._didComplete = false;
27451 this._hasChildren = false;
27452 this._children = null;
27453 this._defer = true;
27454}
27455
27456ReactBatch.prototype.render = function (children) {
27457 var _this = this;
27458
27459 (function () {
27460 if (!_this._defer) {
27461 {
27462 throw ReactError(Error("batch.render: Cannot render a batch that already committed."));
27463 }
27464 }
27465 })();
27466
27467 this._hasChildren = true;
27468 this._children = children;
27469 var internalRoot = this._root._internalRoot;
27470 var expirationTime = this._expirationTime;
27471 var work = new ReactWork();
27472 updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, null, work._onCommit);
27473 return work;
27474};
27475
27476ReactBatch.prototype.then = function (onComplete) {
27477 if (this._didComplete) {
27478 onComplete();
27479 return;
27480 }
27481
27482 var callbacks = this._callbacks;
27483
27484 if (callbacks === null) {
27485 callbacks = this._callbacks = [];
27486 }
27487
27488 callbacks.push(onComplete);
27489};
27490
27491ReactBatch.prototype.commit = function () {
27492 var _this2 = this;
27493
27494 var internalRoot = this._root._internalRoot;
27495 var firstBatch = internalRoot.firstBatch;
27496
27497 (function () {
27498 if (!(_this2._defer && firstBatch !== null)) {
27499 {
27500 throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27501 }
27502 }
27503 })();
27504
27505 if (!this._hasChildren) {
27506 // This batch is empty. Return.
27507 this._next = null;
27508 this._defer = false;
27509 return;
27510 }
27511
27512 var expirationTime = this._expirationTime; // Ensure this is the first batch in the list.
27513
27514 if (firstBatch !== this) {
27515 // This batch is not the earliest batch. We need to move it to the front.
27516 // Update its expiration time to be the expiration time of the earliest
27517 // batch, so that we can flush it without flushing the other batches.
27518 if (this._hasChildren) {
27519 expirationTime = this._expirationTime = firstBatch._expirationTime; // Rendering this batch again ensures its children will be the final state
27520 // when we flush (updates are processed in insertion order: last
27521 // update wins).
27522 // TODO: This forces a restart. Should we print a warning?
27523
27524 this.render(this._children);
27525 } // Remove the batch from the list.
27526
27527
27528 var previous = null;
27529 var batch = firstBatch;
27530
27531 while (batch !== this) {
27532 previous = batch;
27533 batch = batch._next;
27534 }
27535
27536 (function () {
27537 if (!(previous !== null)) {
27538 {
27539 throw ReactError(Error("batch.commit: Cannot commit a batch multiple times."));
27540 }
27541 }
27542 })();
27543
27544 previous._next = batch._next; // Add it to the front.
27545
27546 this._next = firstBatch;
27547 firstBatch = internalRoot.firstBatch = this;
27548 } // Synchronously flush all the work up to this batch's expiration time.
27549
27550
27551 this._defer = false;
27552 flushRoot(internalRoot, expirationTime); // Pop the batch from the list.
27553
27554 var next = this._next;
27555 this._next = null;
27556 firstBatch = internalRoot.firstBatch = next; // Append the next earliest batch's children to the update queue.
27557
27558 if (firstBatch !== null && firstBatch._hasChildren) {
27559 firstBatch.render(firstBatch._children);
27560 }
27561};
27562
27563ReactBatch.prototype._onComplete = function () {
27564 if (this._didComplete) {
27565 return;
27566 }
27567
27568 this._didComplete = true;
27569 var callbacks = this._callbacks;
27570
27571 if (callbacks === null) {
27572 return;
27573 } // TODO: Error handling.
27574
27575
27576 for (var i = 0; i < callbacks.length; i++) {
27577 var _callback = callbacks[i];
27578
27579 _callback();
27580 }
27581};
27582
27583function ReactWork() {
27584 this._callbacks = null;
27585 this._didCommit = false; // TODO: Avoid need to bind by replacing callbacks in the update queue with
27586 // list of Work objects.
27587
27588 this._onCommit = this._onCommit.bind(this);
27589}
27590
27591ReactWork.prototype.then = function (onCommit) {
27592 if (this._didCommit) {
27593 onCommit();
27594 return;
27595 }
27596
27597 var callbacks = this._callbacks;
27598
27599 if (callbacks === null) {
27600 callbacks = this._callbacks = [];
27601 }
27602
27603 callbacks.push(onCommit);
27604};
27605
27606ReactWork.prototype._onCommit = function () {
27607 if (this._didCommit) {
27608 return;
27609 }
27610
27611 this._didCommit = true;
27612 var callbacks = this._callbacks;
27613
27614 if (callbacks === null) {
27615 return;
27616 } // TODO: Error handling.
27617
27618
27619 for (var i = 0; i < callbacks.length; i++) {
27620 var _callback2 = callbacks[i];
27621
27622 (function () {
27623 if (!(typeof _callback2 === 'function')) {
27624 {
27625 throw ReactError(Error("Invalid argument passed as callback. Expected a function. Instead received: " + _callback2));
27626 }
27627 }
27628 })();
27629
27630 _callback2();
27631 }
27632};
27633
27634function createRootImpl(container, tag, options) {
27635 // Tag is either LegacyRoot or Concurrent Root
27636 var hydrate = options != null && options.hydrate === true;
27637 var hydrationCallbacks = options != null && options.hydrationOptions || null;
27638 var root = createContainer(container, tag, hydrate, hydrationCallbacks);
27639 markContainerAsRoot(root.current, container);
27640
27641 if (hydrate && tag !== LegacyRoot) {
27642 var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
27643 eagerlyTrapReplayableEvents(doc);
27644 }
27645
27646 return root;
27647}
27648
27649function ReactSyncRoot(container, tag, options) {
27650 this._internalRoot = createRootImpl(container, tag, options);
27651}
27652
27653function ReactRoot(container, options) {
27654 this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
27655}
27656
27657ReactRoot.prototype.render = ReactSyncRoot.prototype.render = function (children, callback) {
27658 var root = this._internalRoot;
27659 var work = new ReactWork();
27660 callback = callback === undefined ? null : callback;
27661
27662 {
27663 warnOnInvalidCallback(callback, 'render');
27664 }
27665
27666 if (callback !== null) {
27667 work.then(callback);
27668 }
27669
27670 updateContainer(children, root, null, work._onCommit);
27671 return work;
27672};
27673
27674ReactRoot.prototype.unmount = ReactSyncRoot.prototype.unmount = function (callback) {
27675 var root = this._internalRoot;
27676 var work = new ReactWork();
27677 callback = callback === undefined ? null : callback;
27678
27679 {
27680 warnOnInvalidCallback(callback, 'render');
27681 }
27682
27683 if (callback !== null) {
27684 work.then(callback);
27685 }
27686
27687 updateContainer(null, root, null, work._onCommit);
27688 return work;
27689}; // Sync roots cannot create batches. Only concurrent ones.
27690
27691
27692ReactRoot.prototype.createBatch = function () {
27693 var batch = new ReactBatch(this);
27694 var expirationTime = batch._expirationTime;
27695 var internalRoot = this._internalRoot;
27696 var firstBatch = internalRoot.firstBatch;
27697
27698 if (firstBatch === null) {
27699 internalRoot.firstBatch = batch;
27700 batch._next = null;
27701 } else {
27702 // Insert sorted by expiration time then insertion order
27703 var insertAfter = null;
27704 var insertBefore = firstBatch;
27705
27706 while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) {
27707 insertAfter = insertBefore;
27708 insertBefore = insertBefore._next;
27709 }
27710
27711 batch._next = insertBefore;
27712
27713 if (insertAfter !== null) {
27714 insertAfter._next = batch;
27715 }
27716 }
27717
27718 return batch;
27719};
27720/**
27721 * True if the supplied DOM node is a valid node element.
27722 *
27723 * @param {?DOMElement} node The candidate DOM node.
27724 * @return {boolean} True if the DOM is a valid DOM node.
27725 * @internal
27726 */
27727
27728
27729function isValidContainer(node) {
27730 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 '));
27731}
27732
27733function getReactRootElementInContainer(container) {
27734 if (!container) {
27735 return null;
27736 }
27737
27738 if (container.nodeType === DOCUMENT_NODE) {
27739 return container.documentElement;
27740 } else {
27741 return container.firstChild;
27742 }
27743}
27744
27745function shouldHydrateDueToLegacyHeuristic(container) {
27746 var rootElement = getReactRootElementInContainer(container);
27747 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
27748}
27749
27750setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
27751var warnedAboutHydrateAPI = false;
27752
27753function legacyCreateRootFromDOMContainer(container, forceHydrate) {
27754 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
27755
27756 if (!shouldHydrate) {
27757 var warned = false;
27758 var rootSibling;
27759
27760 while (rootSibling = container.lastChild) {
27761 {
27762 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
27763 warned = true;
27764 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.');
27765 }
27766 }
27767
27768 container.removeChild(rootSibling);
27769 }
27770 }
27771
27772 {
27773 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
27774 warnedAboutHydrateAPI = true;
27775 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.');
27776 }
27777 } // Legacy roots are not batched.
27778
27779
27780 return new ReactSyncRoot(container, LegacyRoot, shouldHydrate ? {
27781 hydrate: true
27782 } : undefined);
27783}
27784
27785function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
27786 {
27787 topLevelUpdateWarnings(container);
27788 warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
27789 } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
27790 // member of intersection type." Whyyyyyy.
27791
27792
27793 var root = container._reactRootContainer;
27794 var fiberRoot;
27795
27796 if (!root) {
27797 // Initial mount
27798 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
27799 fiberRoot = root._internalRoot;
27800
27801 if (typeof callback === 'function') {
27802 var originalCallback = callback;
27803
27804 callback = function () {
27805 var instance = getPublicRootInstance(fiberRoot);
27806 originalCallback.call(instance);
27807 };
27808 } // Initial mount should not be batched.
27809
27810
27811 unbatchedUpdates(function () {
27812 updateContainer(children, fiberRoot, parentComponent, callback);
27813 });
27814 } else {
27815 fiberRoot = root._internalRoot;
27816
27817 if (typeof callback === 'function') {
27818 var _originalCallback = callback;
27819
27820 callback = function () {
27821 var instance = getPublicRootInstance(fiberRoot);
27822
27823 _originalCallback.call(instance);
27824 };
27825 } // Update
27826
27827
27828 updateContainer(children, fiberRoot, parentComponent, callback);
27829 }
27830
27831 return getPublicRootInstance(fiberRoot);
27832}
27833
27834function createPortal$$1(children, container) {
27835 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
27836
27837 (function () {
27838 if (!isValidContainer(container)) {
27839 {
27840 throw ReactError(Error("Target container is not a DOM element."));
27841 }
27842 }
27843 })(); // TODO: pass ReactDOM portal implementation as third argument
27844
27845
27846 return createPortal$1(children, container, null, key);
27847}
27848
27849var ReactDOM = {
27850 createPortal: createPortal$$1,
27851 findDOMNode: function (componentOrElement) {
27852 {
27853 var owner = ReactCurrentOwner.current;
27854
27855 if (owner !== null && owner.stateNode !== null) {
27856 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
27857 !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;
27858 owner.stateNode._warnedAboutRefsInRender = true;
27859 }
27860 }
27861
27862 if (componentOrElement == null) {
27863 return null;
27864 }
27865
27866 if (componentOrElement.nodeType === ELEMENT_NODE) {
27867 return componentOrElement;
27868 }
27869
27870 {
27871 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
27872 }
27873
27874 return findHostInstance(componentOrElement);
27875 },
27876 hydrate: function (element, container, callback) {
27877 (function () {
27878 if (!isValidContainer(container)) {
27879 {
27880 throw ReactError(Error("Target container is not a DOM element."));
27881 }
27882 }
27883 })();
27884
27885 {
27886 !!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;
27887 } // TODO: throw or warn if we couldn't hydrate?
27888
27889
27890 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
27891 },
27892 render: function (element, container, callback) {
27893 (function () {
27894 if (!isValidContainer(container)) {
27895 {
27896 throw ReactError(Error("Target container is not a DOM element."));
27897 }
27898 }
27899 })();
27900
27901 {
27902 !!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;
27903 }
27904
27905 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
27906 },
27907 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
27908 (function () {
27909 if (!isValidContainer(containerNode)) {
27910 {
27911 throw ReactError(Error("Target container is not a DOM element."));
27912 }
27913 }
27914 })();
27915
27916 (function () {
27917 if (!(parentComponent != null && has$1(parentComponent))) {
27918 {
27919 throw ReactError(Error("parentComponent must be a valid React Component"));
27920 }
27921 }
27922 })();
27923
27924 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
27925 },
27926 unmountComponentAtNode: function (container) {
27927 (function () {
27928 if (!isValidContainer(container)) {
27929 {
27930 throw ReactError(Error("unmountComponentAtNode(...): Target container is not a DOM element."));
27931 }
27932 }
27933 })();
27934
27935 {
27936 !!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;
27937 }
27938
27939 if (container._reactRootContainer) {
27940 {
27941 var rootEl = getReactRootElementInContainer(container);
27942 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
27943 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
27944 } // Unmount should not be batched.
27945
27946
27947 unbatchedUpdates(function () {
27948 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
27949 container._reactRootContainer = null;
27950 });
27951 }); // If you call unmountComponentAtNode twice in quick succession, you'll
27952 // get `true` twice. That's probably fine?
27953
27954 return true;
27955 } else {
27956 {
27957 var _rootEl = getReactRootElementInContainer(container);
27958
27959 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
27960
27961 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
27962 !!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;
27963 }
27964
27965 return false;
27966 }
27967 },
27968 // Temporary alias since we already shipped React 16 RC with it.
27969 // TODO: remove in React 17.
27970 unstable_createPortal: function () {
27971 if (!didWarnAboutUnstableCreatePortal) {
27972 didWarnAboutUnstableCreatePortal = true;
27973 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.');
27974 }
27975
27976 return createPortal$$1.apply(void 0, arguments);
27977 },
27978 unstable_batchedUpdates: batchedUpdates$1,
27979 // TODO remove this legacy method, unstable_discreteUpdates replaces it
27980 unstable_interactiveUpdates: function (fn, a, b, c) {
27981 flushDiscreteUpdates();
27982 return discreteUpdates$1(fn, a, b, c);
27983 },
27984 unstable_discreteUpdates: discreteUpdates$1,
27985 unstable_flushDiscreteUpdates: flushDiscreteUpdates,
27986 flushSync: flushSync,
27987 unstable_createRoot: createRoot,
27988 unstable_createSyncRoot: createSyncRoot,
27989 unstable_flushControlled: flushControlled,
27990 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
27991 // Keep in sync with ReactDOMUnstableNativeDependencies.js
27992 // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
27993 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
27994 }
27995};
27996
27997function createRoot(container, options) {
27998 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
27999
28000 (function () {
28001 if (!isValidContainer(container)) {
28002 {
28003 throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
28004 }
28005 }
28006 })();
28007
28008 warnIfReactDOMContainerInDEV(container);
28009 return new ReactRoot(container, options);
28010}
28011
28012function createSyncRoot(container, options) {
28013 var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot';
28014
28015 (function () {
28016 if (!isValidContainer(container)) {
28017 {
28018 throw ReactError(Error(functionName + "(...): Target container is not a DOM element."));
28019 }
28020 }
28021 })();
28022
28023 warnIfReactDOMContainerInDEV(container);
28024 return new ReactSyncRoot(container, BatchedRoot, options);
28025}
28026
28027function warnIfReactDOMContainerInDEV(container) {
28028 {
28029 !!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;
28030 container._reactHasBeenPassedToCreateRootDEV = true;
28031 }
28032}
28033
28034if (enableStableConcurrentModeAPIs) {
28035 ReactDOM.createRoot = createRoot;
28036 ReactDOM.createSyncRoot = createSyncRoot;
28037}
28038
28039var foundDevTools = injectIntoDevTools({
28040 findFiberByHostInstance: getClosestInstanceFromNode,
28041 bundleType: 1,
28042 version: ReactVersion,
28043 rendererPackageName: 'react-dom'
28044});
28045
28046{
28047 if (!foundDevTools && canUseDOM && window.top === window.self) {
28048 // If we're in Chrome or Firefox, provide a download link if not installed.
28049 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
28050 var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
28051
28052 if (/^(https?|file):$/.test(protocol)) {
28053 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');
28054 }
28055 }
28056 }
28057}
28058
28059
28060
28061var ReactDOM$2 = Object.freeze({
28062 default: ReactDOM
28063});
28064
28065var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
28066
28067// TODO: decide on the top-level export form.
28068// This is hacky but makes it work with both Rollup and Jest.
28069
28070
28071var reactDom = ReactDOM$3.default || ReactDOM$3;
28072
28073return reactDom;
28074
28075})));