UNPKG

970 kBJavaScriptView Raw
1/** @license React v16.12.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
13
14if (process.env.NODE_ENV !== "production") {
15 (function() {
16'use strict';
17
18var React = require('react');
19var _assign = require('object-assign');
20var Scheduler = require('scheduler');
21var checkPropTypes = require('prop-types/checkPropTypes');
22var tracing = require('scheduler/tracing');
23
24// Do not require this module directly! Use normal `invariant` calls with
25// template literal strings. The messages will be replaced with error codes
26// during build.
27
28/**
29 * Use invariant() to assert state which your program assumes to be true.
30 *
31 * Provide sprintf-style format (only %s is supported) and arguments
32 * to provide information about what broke and what you were
33 * expecting.
34 *
35 * The invariant message will be stripped in production, but the invariant
36 * will remain to ensure logic does not differ in production.
37 */
38
39if (!React) {
40 {
41 throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");
42 }
43}
44
45/**
46 * Injectable ordering of event plugins.
47 */
48var eventPluginOrder = null;
49/**
50 * Injectable mapping from names to event plugin modules.
51 */
52
53var namesToPlugins = {};
54/**
55 * Recomputes the plugin list using the injected plugins and plugin ordering.
56 *
57 * @private
58 */
59
60function recomputePluginOrdering() {
61 if (!eventPluginOrder) {
62 // Wait until an `eventPluginOrder` is injected.
63 return;
64 }
65
66 for (var pluginName in namesToPlugins) {
67 var pluginModule = namesToPlugins[pluginName];
68 var pluginIndex = eventPluginOrder.indexOf(pluginName);
69
70 if (!(pluginIndex > -1)) {
71 {
72 throw Error("EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`.");
73 }
74 }
75
76 if (plugins[pluginIndex]) {
77 continue;
78 }
79
80 if (!pluginModule.extractEvents) {
81 {
82 throw Error("EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not.");
83 }
84 }
85
86 plugins[pluginIndex] = pluginModule;
87 var publishedEvents = pluginModule.eventTypes;
88
89 for (var eventName in publishedEvents) {
90 if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
91 {
92 throw Error("EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`.");
93 }
94 }
95 }
96 }
97}
98/**
99 * Publishes an event so that it can be dispatched by the supplied plugin.
100 *
101 * @param {object} dispatchConfig Dispatch configuration for the event.
102 * @param {object} PluginModule Plugin publishing the event.
103 * @return {boolean} True if the event was successfully published.
104 * @private
105 */
106
107
108function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
109 if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
110 {
111 throw Error("EventPluginHub: More than one plugin attempted to publish the same event name, `" + eventName + "`.");
112 }
113 }
114
115 eventNameDispatchConfigs[eventName] = dispatchConfig;
116 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
117
118 if (phasedRegistrationNames) {
119 for (var phaseName in phasedRegistrationNames) {
120 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
121 var phasedRegistrationName = phasedRegistrationNames[phaseName];
122 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
123 }
124 }
125
126 return true;
127 } else if (dispatchConfig.registrationName) {
128 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
129 return true;
130 }
131
132 return false;
133}
134/**
135 * Publishes a registration name that is used to identify dispatched events.
136 *
137 * @param {string} registrationName Registration name to add.
138 * @param {object} PluginModule Plugin publishing the event.
139 * @private
140 */
141
142
143function publishRegistrationName(registrationName, pluginModule, eventName) {
144 if (!!registrationNameModules[registrationName]) {
145 {
146 throw Error("EventPluginHub: More than one plugin attempted to publish the same registration name, `" + registrationName + "`.");
147 }
148 }
149
150 registrationNameModules[registrationName] = pluginModule;
151 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
152
153 {
154 var lowerCasedName = registrationName.toLowerCase();
155 possibleRegistrationNames[lowerCasedName] = registrationName;
156
157 if (registrationName === 'onDoubleClick') {
158 possibleRegistrationNames.ondblclick = registrationName;
159 }
160 }
161}
162/**
163 * Registers plugins so that they can extract and dispatch events.
164 *
165 * @see {EventPluginHub}
166 */
167
168/**
169 * Ordered list of injected plugins.
170 */
171
172
173var plugins = [];
174/**
175 * Mapping from event name to dispatch config
176 */
177
178var eventNameDispatchConfigs = {};
179/**
180 * Mapping from registration name to plugin module
181 */
182
183var registrationNameModules = {};
184/**
185 * Mapping from registration name to event name
186 */
187
188var registrationNameDependencies = {};
189/**
190 * Mapping from lowercase registration names to the properly cased version,
191 * used to warn in the case of missing event handlers. Available
192 * only in true.
193 * @type {Object}
194 */
195
196var possibleRegistrationNames = {}; // Trust the developer to only use possibleRegistrationNames in true
197
198/**
199 * Injects an ordering of plugins (by plugin name). This allows the ordering
200 * to be decoupled from injection of the actual plugins so that ordering is
201 * always deterministic regardless of packaging, on-the-fly injection, etc.
202 *
203 * @param {array} InjectedEventPluginOrder
204 * @internal
205 * @see {EventPluginHub.injection.injectEventPluginOrder}
206 */
207
208function injectEventPluginOrder(injectedEventPluginOrder) {
209 if (!!eventPluginOrder) {
210 {
211 throw Error("EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.");
212 }
213 } // Clone the ordering so it cannot be dynamically mutated.
214
215
216 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
217 recomputePluginOrdering();
218}
219/**
220 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
221 * in the ordering injected by `injectEventPluginOrder`.
222 *
223 * Plugins can be injected as part of page initialization or on-the-fly.
224 *
225 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
226 * @internal
227 * @see {EventPluginHub.injection.injectEventPluginsByName}
228 */
229
230function injectEventPluginsByName(injectedNamesToPlugins) {
231 var isOrderingDirty = false;
232
233 for (var pluginName in injectedNamesToPlugins) {
234 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
235 continue;
236 }
237
238 var pluginModule = injectedNamesToPlugins[pluginName];
239
240 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
241 if (!!namesToPlugins[pluginName]) {
242 {
243 throw Error("EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`.");
244 }
245 }
246
247 namesToPlugins[pluginName] = pluginModule;
248 isOrderingDirty = true;
249 }
250 }
251
252 if (isOrderingDirty) {
253 recomputePluginOrdering();
254 }
255}
256
257var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
258 var funcArgs = Array.prototype.slice.call(arguments, 3);
259
260 try {
261 func.apply(context, funcArgs);
262 } catch (error) {
263 this.onError(error);
264 }
265};
266
267{
268 // In DEV mode, we swap out invokeGuardedCallback for a special version
269 // that plays more nicely with the browser's DevTools. The idea is to preserve
270 // "Pause on exceptions" behavior. Because React wraps all user-provided
271 // functions in invokeGuardedCallback, and the production version of
272 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
273 // like caught exceptions, and the DevTools won't pause unless the developer
274 // takes the extra step of enabling pause on caught exceptions. This is
275 // unintuitive, though, because even though React has caught the error, from
276 // the developer's perspective, the error is uncaught.
277 //
278 // To preserve the expected "Pause on exceptions" behavior, we don't use a
279 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
280 // DOM node, and call the user-provided callback from inside an event handler
281 // for that fake event. If the callback throws, the error is "captured" using
282 // a global event handler. But because the error happens in a different
283 // event loop context, it does not interrupt the normal program flow.
284 // Effectively, this gives us try-catch behavior without actually using
285 // try-catch. Neat!
286 // Check that the browser supports the APIs we need to implement our special
287 // DEV version of invokeGuardedCallback
288 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
289 var fakeNode = document.createElement('react');
290
291 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
292 // If document doesn't exist we know for sure we will crash in this method
293 // when we call document.createEvent(). However this can cause confusing
294 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
295 // So we preemptively throw with a better message instead.
296 if (!(typeof document !== 'undefined')) {
297 {
298 throw 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.");
299 }
300 }
301
302 var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
303 // set this to true at the beginning, then set it to false right after
304 // calling the function. If the function errors, `didError` will never be
305 // set to false. This strategy works even if the browser is flaky and
306 // fails to call our global error handler, because it doesn't rely on
307 // the error event at all.
308
309 var didError = true; // Keeps track of the value of window.event so that we can reset it
310 // during the callback to let user code access window.event in the
311 // browsers that support it.
312
313 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
314 // dispatching: https://github.com/facebook/react/issues/13688
315
316 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
317 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
318 // call the user-provided callback.
319
320 var funcArgs = Array.prototype.slice.call(arguments, 3);
321
322 function callCallback() {
323 // We immediately remove the callback from event listeners so that
324 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
325 // nested call would trigger the fake event handlers of any call higher
326 // in the stack.
327 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
328 // window.event assignment in both IE <= 10 as they throw an error
329 // "Member not found" in strict mode, and in Firefox which does not
330 // support window.event.
331
332 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
333 window.event = windowEvent;
334 }
335
336 func.apply(context, funcArgs);
337 didError = false;
338 } // Create a global error event handler. We use this to capture the value
339 // that was thrown. It's possible that this error handler will fire more
340 // than once; for example, if non-React code also calls `dispatchEvent`
341 // and a handler for that event throws. We should be resilient to most of
342 // those cases. Even if our error event handler fires more than once, the
343 // last error event is always used. If the callback actually does error,
344 // we know that the last error event is the correct one, because it's not
345 // possible for anything else to have happened in between our callback
346 // erroring and the code that follows the `dispatchEvent` call below. If
347 // the callback doesn't error, but the error event was fired, we know to
348 // ignore it because `didError` will be false, as described above.
349
350
351 var error; // Use this to track whether the error event is ever called.
352
353 var didSetError = false;
354 var isCrossOriginError = false;
355
356 function handleWindowError(event) {
357 error = event.error;
358 didSetError = true;
359
360 if (error === null && event.colno === 0 && event.lineno === 0) {
361 isCrossOriginError = true;
362 }
363
364 if (event.defaultPrevented) {
365 // Some other error handler has prevented default.
366 // Browsers silence the error report if this happens.
367 // We'll remember this to later decide whether to log it or not.
368 if (error != null && typeof error === 'object') {
369 try {
370 error._suppressLogging = true;
371 } catch (inner) {// Ignore.
372 }
373 }
374 }
375 } // Create a fake event type.
376
377
378 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
379
380 window.addEventListener('error', handleWindowError);
381 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
382 // errors, it will trigger our global error handler.
383
384 evt.initEvent(evtType, false, false);
385 fakeNode.dispatchEvent(evt);
386
387 if (windowEventDescriptor) {
388 Object.defineProperty(window, 'event', windowEventDescriptor);
389 }
390
391 if (didError) {
392 if (!didSetError) {
393 // The callback errored, but the error event never fired.
394 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.');
395 } else if (isCrossOriginError) {
396 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.');
397 }
398
399 this.onError(error);
400 } // Remove our event listeners
401
402
403 window.removeEventListener('error', handleWindowError);
404 };
405
406 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
407 }
408}
409
410var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
411
412var hasError = false;
413var caughtError = null; // Used by event system to capture/rethrow the first error.
414
415var hasRethrowError = false;
416var rethrowError = null;
417var reporter = {
418 onError: function (error) {
419 hasError = true;
420 caughtError = error;
421 }
422};
423/**
424 * Call a function while guarding against errors that happens within it.
425 * Returns an error if it throws, otherwise null.
426 *
427 * In production, this is implemented using a try-catch. The reason we don't
428 * use a try-catch directly is so that we can swap out a different
429 * implementation in DEV mode.
430 *
431 * @param {String} name of the guard to use for logging or debugging
432 * @param {Function} func The function to invoke
433 * @param {*} context The context to use when calling the function
434 * @param {...*} args Arguments for function
435 */
436
437function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
438 hasError = false;
439 caughtError = null;
440 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
441}
442/**
443 * Same as invokeGuardedCallback, but instead of returning an error, it stores
444 * it in a global so it can be rethrown by `rethrowCaughtError` later.
445 * TODO: See if caughtError and rethrowError can be unified.
446 *
447 * @param {String} name of the guard to use for logging or debugging
448 * @param {Function} func The function to invoke
449 * @param {*} context The context to use when calling the function
450 * @param {...*} args Arguments for function
451 */
452
453function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
454 invokeGuardedCallback.apply(this, arguments);
455
456 if (hasError) {
457 var error = clearCaughtError();
458
459 if (!hasRethrowError) {
460 hasRethrowError = true;
461 rethrowError = error;
462 }
463 }
464}
465/**
466 * During execution of guarded functions we will capture the first error which
467 * we will rethrow to be handled by the top level error handler.
468 */
469
470function rethrowCaughtError() {
471 if (hasRethrowError) {
472 var error = rethrowError;
473 hasRethrowError = false;
474 rethrowError = null;
475 throw error;
476 }
477}
478function hasCaughtError() {
479 return hasError;
480}
481function clearCaughtError() {
482 if (hasError) {
483 var error = caughtError;
484 hasError = false;
485 caughtError = null;
486 return error;
487 } else {
488 {
489 {
490 throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
491 }
492 }
493 }
494}
495
496/**
497 * Similar to invariant but only logs a warning if the condition is not met.
498 * This can be used to log issues in development environments in critical
499 * paths. Removing the logging code for production environments will keep the
500 * same logic and follow the same code paths.
501 */
502var warningWithoutStack = function () {};
503
504{
505 warningWithoutStack = function (condition, format) {
506 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
507 args[_key - 2] = arguments[_key];
508 }
509
510 if (format === undefined) {
511 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
512 }
513
514 if (args.length > 8) {
515 // Check before the condition to catch violations early.
516 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
517 }
518
519 if (condition) {
520 return;
521 }
522
523 if (typeof console !== 'undefined') {
524 var argsWithFormat = args.map(function (item) {
525 return '' + item;
526 });
527 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
528 // breaks IE9: https://github.com/facebook/react/issues/13610
529
530 Function.prototype.apply.call(console.error, console, argsWithFormat);
531 }
532
533 try {
534 // --- Welcome to debugging React ---
535 // This error was thrown as a convenience so that you can use this stack
536 // to find the callsite that caused this warning to fire.
537 var argIndex = 0;
538 var message = 'Warning: ' + format.replace(/%s/g, function () {
539 return args[argIndex++];
540 });
541 throw new Error(message);
542 } catch (x) {}
543 };
544}
545
546var warningWithoutStack$1 = warningWithoutStack;
547
548var getFiberCurrentPropsFromNode = null;
549var getInstanceFromNode = null;
550var getNodeFromInstance = null;
551function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
552 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
553 getInstanceFromNode = getInstanceFromNodeImpl;
554 getNodeFromInstance = getNodeFromInstanceImpl;
555
556 {
557 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
558 }
559}
560var validateEventDispatches;
561
562{
563 validateEventDispatches = function (event) {
564 var dispatchListeners = event._dispatchListeners;
565 var dispatchInstances = event._dispatchInstances;
566 var listenersIsArr = Array.isArray(dispatchListeners);
567 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
568 var instancesIsArr = Array.isArray(dispatchInstances);
569 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
570 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
571 };
572}
573/**
574 * Dispatch the event to the listener.
575 * @param {SyntheticEvent} event SyntheticEvent to handle
576 * @param {function} listener Application-level callback
577 * @param {*} inst Internal component instance
578 */
579
580
581function executeDispatch(event, listener, inst) {
582 var type = event.type || 'unknown-event';
583 event.currentTarget = getNodeFromInstance(inst);
584 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
585 event.currentTarget = null;
586}
587/**
588 * Standard/simple iteration through an event's collected dispatches.
589 */
590
591function executeDispatchesInOrder(event) {
592 var dispatchListeners = event._dispatchListeners;
593 var dispatchInstances = event._dispatchInstances;
594
595 {
596 validateEventDispatches(event);
597 }
598
599 if (Array.isArray(dispatchListeners)) {
600 for (var i = 0; i < dispatchListeners.length; i++) {
601 if (event.isPropagationStopped()) {
602 break;
603 } // Listeners and Instances are two parallel arrays that are always in sync.
604
605
606 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
607 }
608 } else if (dispatchListeners) {
609 executeDispatch(event, dispatchListeners, dispatchInstances);
610 }
611
612 event._dispatchListeners = null;
613 event._dispatchInstances = null;
614}
615/**
616 * @see executeDispatchesInOrderStopAtTrueImpl
617 */
618
619
620
621/**
622 * Execution of a "direct" dispatch - there must be at most one dispatch
623 * accumulated on the event or it is considered an error. It doesn't really make
624 * sense for an event with multiple dispatches (bubbled) to keep track of the
625 * return values at each dispatch execution, but it does tend to make sense when
626 * dealing with "direct" dispatches.
627 *
628 * @return {*} The return value of executing the single dispatch.
629 */
630
631
632/**
633 * @param {SyntheticEvent} event
634 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
635 */
636
637/**
638 * Accumulates items that must not be null or undefined into the first one. This
639 * is used to conserve memory by avoiding array allocations, and thus sacrifices
640 * API cleanness. Since `current` can be null before being passed in and not
641 * null after this function, make sure to assign it back to `current`:
642 *
643 * `a = accumulateInto(a, b);`
644 *
645 * This API should be sparingly used. Try `accumulate` for something cleaner.
646 *
647 * @return {*|array<*>} An accumulation of items.
648 */
649
650function accumulateInto(current, next) {
651 if (!(next != null)) {
652 {
653 throw Error("accumulateInto(...): Accumulated items must not be null or undefined.");
654 }
655 }
656
657 if (current == null) {
658 return next;
659 } // Both are not empty. Warning: Never call x.concat(y) when you are not
660 // certain that x is an Array (x could be a string with concat method).
661
662
663 if (Array.isArray(current)) {
664 if (Array.isArray(next)) {
665 current.push.apply(current, next);
666 return current;
667 }
668
669 current.push(next);
670 return current;
671 }
672
673 if (Array.isArray(next)) {
674 // A bit too dangerous to mutate `next`.
675 return [current].concat(next);
676 }
677
678 return [current, next];
679}
680
681/**
682 * @param {array} arr an "accumulation" of items which is either an Array or
683 * a single item. Useful when paired with the `accumulate` module. This is a
684 * simple utility that allows us to reason about a collection of items, but
685 * handling the case when there is exactly one item (and we do not need to
686 * allocate an array).
687 * @param {function} cb Callback invoked with each element or a collection.
688 * @param {?} [scope] Scope used as `this` in a callback.
689 */
690function forEachAccumulated(arr, cb, scope) {
691 if (Array.isArray(arr)) {
692 arr.forEach(cb, scope);
693 } else if (arr) {
694 cb.call(scope, arr);
695 }
696}
697
698/**
699 * Internal queue of events that have accumulated their dispatches and are
700 * waiting to have their dispatches executed.
701 */
702
703var eventQueue = null;
704/**
705 * Dispatches an event and releases it back into the pool, unless persistent.
706 *
707 * @param {?object} event Synthetic event to be dispatched.
708 * @private
709 */
710
711var executeDispatchesAndRelease = function (event) {
712 if (event) {
713 executeDispatchesInOrder(event);
714
715 if (!event.isPersistent()) {
716 event.constructor.release(event);
717 }
718 }
719};
720
721var executeDispatchesAndReleaseTopLevel = function (e) {
722 return executeDispatchesAndRelease(e);
723};
724
725function runEventsInBatch(events) {
726 if (events !== null) {
727 eventQueue = accumulateInto(eventQueue, events);
728 } // Set `eventQueue` to null before processing it so that we can tell if more
729 // events get enqueued while processing.
730
731
732 var processingEventQueue = eventQueue;
733 eventQueue = null;
734
735 if (!processingEventQueue) {
736 return;
737 }
738
739 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
740
741 if (!!eventQueue) {
742 {
743 throw Error("processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.");
744 }
745 } // This would be a good time to rethrow if any of the event handlers threw.
746
747
748 rethrowCaughtError();
749}
750
751function isInteractive(tag) {
752 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
753}
754
755function shouldPreventMouseEvent(name, type, props) {
756 switch (name) {
757 case 'onClick':
758 case 'onClickCapture':
759 case 'onDoubleClick':
760 case 'onDoubleClickCapture':
761 case 'onMouseDown':
762 case 'onMouseDownCapture':
763 case 'onMouseMove':
764 case 'onMouseMoveCapture':
765 case 'onMouseUp':
766 case 'onMouseUpCapture':
767 return !!(props.disabled && isInteractive(type));
768
769 default:
770 return false;
771 }
772}
773/**
774 * This is a unified interface for event plugins to be installed and configured.
775 *
776 * Event plugins can implement the following properties:
777 *
778 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
779 * Required. When a top-level event is fired, this method is expected to
780 * extract synthetic events that will in turn be queued and dispatched.
781 *
782 * `eventTypes` {object}
783 * Optional, plugins that fire events must publish a mapping of registration
784 * names that are used to register listeners. Values of this mapping must
785 * be objects that contain `registrationName` or `phasedRegistrationNames`.
786 *
787 * `executeDispatch` {function(object, function, string)}
788 * Optional, allows plugins to override how an event gets dispatched. By
789 * default, the listener is simply invoked.
790 *
791 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
792 *
793 * @public
794 */
795
796/**
797 * Methods for injecting dependencies.
798 */
799
800
801var injection = {
802 /**
803 * @param {array} InjectedEventPluginOrder
804 * @public
805 */
806 injectEventPluginOrder: injectEventPluginOrder,
807
808 /**
809 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
810 */
811 injectEventPluginsByName: injectEventPluginsByName
812};
813/**
814 * @param {object} inst The instance, which is the source of events.
815 * @param {string} registrationName Name of listener (e.g. `onClick`).
816 * @return {?function} The stored callback.
817 */
818
819function getListener(inst, registrationName) {
820 var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
821 // live here; needs to be moved to a better place soon
822
823 var stateNode = inst.stateNode;
824
825 if (!stateNode) {
826 // Work in progress (ex: onload events in incremental mode).
827 return null;
828 }
829
830 var props = getFiberCurrentPropsFromNode(stateNode);
831
832 if (!props) {
833 // Work in progress.
834 return null;
835 }
836
837 listener = props[registrationName];
838
839 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
840 return null;
841 }
842
843 if (!(!listener || typeof listener === 'function')) {
844 {
845 throw Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
846 }
847 }
848
849 return listener;
850}
851/**
852 * Allows registered plugins an opportunity to extract events from top-level
853 * native browser events.
854 *
855 * @return {*} An accumulation of synthetic events.
856 * @internal
857 */
858
859function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
860 var events = null;
861
862 for (var i = 0; i < plugins.length; i++) {
863 // Not every plugin in the ordering may be loaded at runtime.
864 var possiblePlugin = plugins[i];
865
866 if (possiblePlugin) {
867 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
868
869 if (extractedEvents) {
870 events = accumulateInto(events, extractedEvents);
871 }
872 }
873 }
874
875 return events;
876}
877
878function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
879 var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
880 runEventsInBatch(events);
881}
882
883var FunctionComponent = 0;
884var ClassComponent = 1;
885var IndeterminateComponent = 2; // Before we know whether it is function or class
886
887var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
888
889var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
890
891var HostComponent = 5;
892var HostText = 6;
893var Fragment = 7;
894var Mode = 8;
895var ContextConsumer = 9;
896var ContextProvider = 10;
897var ForwardRef = 11;
898var Profiler = 12;
899var SuspenseComponent = 13;
900var MemoComponent = 14;
901var SimpleMemoComponent = 15;
902var LazyComponent = 16;
903var IncompleteClassComponent = 17;
904var DehydratedFragment = 18;
905var SuspenseListComponent = 19;
906var FundamentalComponent = 20;
907var ScopeComponent = 21;
908
909var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
910// Current owner and dispatcher used to share the same ref,
911// but PR #14548 split them out to better support the react-debug-tools package.
912
913if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
914 ReactSharedInternals.ReactCurrentDispatcher = {
915 current: null
916 };
917}
918
919if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
920 ReactSharedInternals.ReactCurrentBatchConfig = {
921 suspense: null
922 };
923}
924
925var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
926var describeComponentFrame = function (name, source, ownerName) {
927 var sourceInfo = '';
928
929 if (source) {
930 var path = source.fileName;
931 var fileName = path.replace(BEFORE_SLASH_RE, '');
932
933 {
934 // In DEV, include code for a common special case:
935 // prefer "folder/index.js" instead of just "index.js".
936 if (/^index\./.test(fileName)) {
937 var match = path.match(BEFORE_SLASH_RE);
938
939 if (match) {
940 var pathBeforeSlash = match[1];
941
942 if (pathBeforeSlash) {
943 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
944 fileName = folderName + '/' + fileName;
945 }
946 }
947 }
948 }
949
950 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
951 } else if (ownerName) {
952 sourceInfo = ' (created by ' + ownerName + ')';
953 }
954
955 return '\n in ' + (name || 'Unknown') + sourceInfo;
956};
957
958// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
959// nor polyfill, then a plain number is used for performance.
960var hasSymbol = typeof Symbol === 'function' && Symbol.for;
961var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
962var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
963var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
964var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
965var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
966var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
967var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
968// (unstable) APIs that have been removed. Can we remove the symbols?
969
970
971var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
972var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
973var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
974var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
975var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
976var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
977var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
978var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
979var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
980var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
981var FAUX_ITERATOR_SYMBOL = '@@iterator';
982function getIteratorFn(maybeIterable) {
983 if (maybeIterable === null || typeof maybeIterable !== 'object') {
984 return null;
985 }
986
987 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
988
989 if (typeof maybeIterator === 'function') {
990 return maybeIterator;
991 }
992
993 return null;
994}
995
996/**
997 * Similar to invariant but only logs a warning if the condition is not met.
998 * This can be used to log issues in development environments in critical
999 * paths. Removing the logging code for production environments will keep the
1000 * same logic and follow the same code paths.
1001 */
1002
1003var warning = warningWithoutStack$1;
1004
1005{
1006 warning = function (condition, format) {
1007 if (condition) {
1008 return;
1009 }
1010
1011 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1012 var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args
1013
1014 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1015 args[_key - 2] = arguments[_key];
1016 }
1017
1018 warningWithoutStack$1.apply(void 0, [false, format + '%s'].concat(args, [stack]));
1019 };
1020}
1021
1022var warning$1 = warning;
1023
1024var Uninitialized = -1;
1025var Pending = 0;
1026var Resolved = 1;
1027var Rejected = 2;
1028function refineResolvedLazyComponent(lazyComponent) {
1029 return lazyComponent._status === Resolved ? lazyComponent._result : null;
1030}
1031function initializeLazyComponentType(lazyComponent) {
1032 if (lazyComponent._status === Uninitialized) {
1033 lazyComponent._status = Pending;
1034 var ctor = lazyComponent._ctor;
1035 var thenable = ctor();
1036 lazyComponent._result = thenable;
1037 thenable.then(function (moduleObject) {
1038 if (lazyComponent._status === Pending) {
1039 var defaultExport = moduleObject.default;
1040
1041 {
1042 if (defaultExport === undefined) {
1043 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);
1044 }
1045 }
1046
1047 lazyComponent._status = Resolved;
1048 lazyComponent._result = defaultExport;
1049 }
1050 }, function (error) {
1051 if (lazyComponent._status === Pending) {
1052 lazyComponent._status = Rejected;
1053 lazyComponent._result = error;
1054 }
1055 });
1056 }
1057}
1058
1059function getWrappedName(outerType, innerType, wrapperName) {
1060 var functionName = innerType.displayName || innerType.name || '';
1061 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
1062}
1063
1064function getComponentName(type) {
1065 if (type == null) {
1066 // Host root, text node or just invalid type.
1067 return null;
1068 }
1069
1070 {
1071 if (typeof type.tag === 'number') {
1072 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
1073 }
1074 }
1075
1076 if (typeof type === 'function') {
1077 return type.displayName || type.name || null;
1078 }
1079
1080 if (typeof type === 'string') {
1081 return type;
1082 }
1083
1084 switch (type) {
1085 case REACT_FRAGMENT_TYPE:
1086 return 'Fragment';
1087
1088 case REACT_PORTAL_TYPE:
1089 return 'Portal';
1090
1091 case REACT_PROFILER_TYPE:
1092 return "Profiler";
1093
1094 case REACT_STRICT_MODE_TYPE:
1095 return 'StrictMode';
1096
1097 case REACT_SUSPENSE_TYPE:
1098 return 'Suspense';
1099
1100 case REACT_SUSPENSE_LIST_TYPE:
1101 return 'SuspenseList';
1102 }
1103
1104 if (typeof type === 'object') {
1105 switch (type.$$typeof) {
1106 case REACT_CONTEXT_TYPE:
1107 return 'Context.Consumer';
1108
1109 case REACT_PROVIDER_TYPE:
1110 return 'Context.Provider';
1111
1112 case REACT_FORWARD_REF_TYPE:
1113 return getWrappedName(type, type.render, 'ForwardRef');
1114
1115 case REACT_MEMO_TYPE:
1116 return getComponentName(type.type);
1117
1118 case REACT_LAZY_TYPE:
1119 {
1120 var thenable = type;
1121 var resolvedThenable = refineResolvedLazyComponent(thenable);
1122
1123 if (resolvedThenable) {
1124 return getComponentName(resolvedThenable);
1125 }
1126
1127 break;
1128 }
1129 }
1130 }
1131
1132 return null;
1133}
1134
1135var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1136
1137function describeFiber(fiber) {
1138 switch (fiber.tag) {
1139 case HostRoot:
1140 case HostPortal:
1141 case HostText:
1142 case Fragment:
1143 case ContextProvider:
1144 case ContextConsumer:
1145 return '';
1146
1147 default:
1148 var owner = fiber._debugOwner;
1149 var source = fiber._debugSource;
1150 var name = getComponentName(fiber.type);
1151 var ownerName = null;
1152
1153 if (owner) {
1154 ownerName = getComponentName(owner.type);
1155 }
1156
1157 return describeComponentFrame(name, source, ownerName);
1158 }
1159}
1160
1161function getStackByFiberInDevAndProd(workInProgress) {
1162 var info = '';
1163 var node = workInProgress;
1164
1165 do {
1166 info += describeFiber(node);
1167 node = node.return;
1168 } while (node);
1169
1170 return info;
1171}
1172var current = null;
1173var phase = null;
1174function getCurrentFiberOwnerNameInDevOrNull() {
1175 {
1176 if (current === null) {
1177 return null;
1178 }
1179
1180 var owner = current._debugOwner;
1181
1182 if (owner !== null && typeof owner !== 'undefined') {
1183 return getComponentName(owner.type);
1184 }
1185 }
1186
1187 return null;
1188}
1189function getCurrentFiberStackInDev() {
1190 {
1191 if (current === null) {
1192 return '';
1193 } // Safe because if current fiber exists, we are reconciling,
1194 // and it is guaranteed to be the work-in-progress version.
1195
1196
1197 return getStackByFiberInDevAndProd(current);
1198 }
1199
1200 return '';
1201}
1202function resetCurrentFiber() {
1203 {
1204 ReactDebugCurrentFrame.getCurrentStack = null;
1205 current = null;
1206 phase = null;
1207 }
1208}
1209function setCurrentFiber(fiber) {
1210 {
1211 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1212 current = fiber;
1213 phase = null;
1214 }
1215}
1216function setCurrentPhase(lifeCyclePhase) {
1217 {
1218 phase = lifeCyclePhase;
1219 }
1220}
1221
1222var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1223
1224function endsWith(subject, search) {
1225 var length = subject.length;
1226 return subject.substring(length - search.length, length) === search;
1227}
1228
1229var PLUGIN_EVENT_SYSTEM = 1;
1230var RESPONDER_EVENT_SYSTEM = 1 << 1;
1231var IS_PASSIVE = 1 << 2;
1232var IS_ACTIVE = 1 << 3;
1233var PASSIVE_NOT_SUPPORTED = 1 << 4;
1234var IS_REPLAYED = 1 << 5;
1235
1236var restoreImpl = null;
1237var restoreTarget = null;
1238var restoreQueue = null;
1239
1240function restoreStateOfTarget(target) {
1241 // We perform this translation at the end of the event loop so that we
1242 // always receive the correct fiber here
1243 var internalInstance = getInstanceFromNode(target);
1244
1245 if (!internalInstance) {
1246 // Unmounted
1247 return;
1248 }
1249
1250 if (!(typeof restoreImpl === 'function')) {
1251 {
1252 throw 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.");
1253 }
1254 }
1255
1256 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
1257 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
1258}
1259
1260function setRestoreImplementation(impl) {
1261 restoreImpl = impl;
1262}
1263function enqueueStateRestore(target) {
1264 if (restoreTarget) {
1265 if (restoreQueue) {
1266 restoreQueue.push(target);
1267 } else {
1268 restoreQueue = [target];
1269 }
1270 } else {
1271 restoreTarget = target;
1272 }
1273}
1274function needsStateRestore() {
1275 return restoreTarget !== null || restoreQueue !== null;
1276}
1277function restoreStateIfNeeded() {
1278 if (!restoreTarget) {
1279 return;
1280 }
1281
1282 var target = restoreTarget;
1283 var queuedTargets = restoreQueue;
1284 restoreTarget = null;
1285 restoreQueue = null;
1286 restoreStateOfTarget(target);
1287
1288 if (queuedTargets) {
1289 for (var i = 0; i < queuedTargets.length; i++) {
1290 restoreStateOfTarget(queuedTargets[i]);
1291 }
1292 }
1293}
1294
1295var enableUserTimingAPI = true; // Helps identify side effects in render-phase lifecycle hooks and setState
1296// reducers by double invoking them in Strict Mode.
1297
1298var debugRenderPhaseSideEffectsForStrictMode = true; // To preserve the "Pause on caught exceptions" behavior of the debugger, we
1299// replay the begin phase of a failed component inside invokeGuardedCallback.
1300
1301var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
1302
1303var warnAboutDeprecatedLifecycles = true; // Gather advanced timing metrics for Profiler subtrees.
1304
1305var enableProfilerTimer = true; // Trace which interactions trigger each commit.
1306
1307var enableSchedulerTracing = true; // SSR experiments
1308
1309var enableSuspenseServerRenderer = false;
1310var enableSelectiveHydration = false; // Only used in www builds.
1311
1312 // Only used in www builds.
1313
1314 // Disable javascript: URL strings in href for XSS protection.
1315
1316var disableJavaScriptURLs = false; // React Fire: prevent the value and checked attributes from syncing
1317// with their related DOM properties
1318
1319var disableInputAttributeSyncing = false; // These APIs will no longer be "unstable" in the upcoming 16.7 release,
1320// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
1321
1322var exposeConcurrentModeAPIs = false;
1323var warnAboutShorthandPropertyCollision = false; // Experimental React Flare event system and event components support.
1324
1325var enableFlareAPI = false; // Experimental Host Component support.
1326
1327var enableFundamentalAPI = false; // Experimental Scope support.
1328
1329var enableScopeAPI = false; // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
1330
1331 // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
1332// Till then, we warn about the missing mock, but still fallback to a legacy mode compatible version
1333
1334var warnAboutUnmockedScheduler = false; // For tests, we flush suspense fallbacks in an act scope;
1335// *except* in some of our own tests, where we test incremental loading states.
1336
1337var flushSuspenseFallbacksInTests = true; // Add a callback property to suspense to notify which promises are currently
1338// in the update queue. This allows reporting and tracing of what is causing
1339// the user to see a loading state.
1340// Also allows hydration callbacks to fire when a dehydrated boundary gets
1341// hydrated or deleted.
1342
1343var enableSuspenseCallback = false; // Part of the simplification of React.createElement so we can eventually move
1344// from React.createElement to React.jsx
1345// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
1346
1347var warnAboutDefaultPropsOnFunctionComponents = false;
1348var warnAboutStringRefs = false;
1349var disableLegacyContext = false;
1350var disableSchedulerTimeoutBasedOnReactExpirationTime = false;
1351var enableTrustedTypesIntegration = false; // Flag to turn event.target and event.currentTarget in ReactNative from a reactTag to a component instance
1352
1353// the renderer. Such as when we're dispatching events or if third party
1354// libraries need to call batchedUpdates. Eventually, this API will go away when
1355// everything is batched by default. We'll then have a similar API to opt-out of
1356// scheduled work and instead do synchronous work.
1357// Defaults
1358
1359var batchedUpdatesImpl = function (fn, bookkeeping) {
1360 return fn(bookkeeping);
1361};
1362
1363var discreteUpdatesImpl = function (fn, a, b, c) {
1364 return fn(a, b, c);
1365};
1366
1367var flushDiscreteUpdatesImpl = function () {};
1368
1369var batchedEventUpdatesImpl = batchedUpdatesImpl;
1370var isInsideEventHandler = false;
1371var isBatchingEventUpdates = false;
1372
1373function finishEventHandler() {
1374 // Here we wait until all updates have propagated, which is important
1375 // when using controlled components within layers:
1376 // https://github.com/facebook/react/issues/1698
1377 // Then we restore state of any controlled component.
1378 var controlledComponentsHavePendingUpdates = needsStateRestore();
1379
1380 if (controlledComponentsHavePendingUpdates) {
1381 // If a controlled event was fired, we may need to restore the state of
1382 // the DOM node back to the controlled value. This is necessary when React
1383 // bails out of the update without touching the DOM.
1384 flushDiscreteUpdatesImpl();
1385 restoreStateIfNeeded();
1386 }
1387}
1388
1389function batchedUpdates(fn, bookkeeping) {
1390 if (isInsideEventHandler) {
1391 // If we are currently inside another batch, we need to wait until it
1392 // fully completes before restoring state.
1393 return fn(bookkeeping);
1394 }
1395
1396 isInsideEventHandler = true;
1397
1398 try {
1399 return batchedUpdatesImpl(fn, bookkeeping);
1400 } finally {
1401 isInsideEventHandler = false;
1402 finishEventHandler();
1403 }
1404}
1405function batchedEventUpdates(fn, a, b) {
1406 if (isBatchingEventUpdates) {
1407 // If we are currently inside another batch, we need to wait until it
1408 // fully completes before restoring state.
1409 return fn(a, b);
1410 }
1411
1412 isBatchingEventUpdates = true;
1413
1414 try {
1415 return batchedEventUpdatesImpl(fn, a, b);
1416 } finally {
1417 isBatchingEventUpdates = false;
1418 finishEventHandler();
1419 }
1420} // This is for the React Flare event system
1421
1422function executeUserEventHandler(fn, value) {
1423 var previouslyInEventHandler = isInsideEventHandler;
1424
1425 try {
1426 isInsideEventHandler = true;
1427 var type = typeof value === 'object' && value !== null ? value.type : '';
1428 invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value);
1429 } finally {
1430 isInsideEventHandler = previouslyInEventHandler;
1431 }
1432}
1433function discreteUpdates(fn, a, b, c) {
1434 var prevIsInsideEventHandler = isInsideEventHandler;
1435 isInsideEventHandler = true;
1436
1437 try {
1438 return discreteUpdatesImpl(fn, a, b, c);
1439 } finally {
1440 isInsideEventHandler = prevIsInsideEventHandler;
1441
1442 if (!isInsideEventHandler) {
1443 finishEventHandler();
1444 }
1445 }
1446}
1447var lastFlushedEventTimeStamp = 0;
1448function flushDiscreteUpdatesIfNeeded(timeStamp) {
1449 // event.timeStamp isn't overly reliable due to inconsistencies in
1450 // how different browsers have historically provided the time stamp.
1451 // Some browsers provide high-resolution time stamps for all events,
1452 // some provide low-resolution time stamps for all events. FF < 52
1453 // even mixes both time stamps together. Some browsers even report
1454 // negative time stamps or time stamps that are 0 (iOS9) in some cases.
1455 // Given we are only comparing two time stamps with equality (!==),
1456 // we are safe from the resolution differences. If the time stamp is 0
1457 // we bail-out of preventing the flush, which can affect semantics,
1458 // such as if an earlier flush removes or adds event listeners that
1459 // are fired in the subsequent flush. However, this is the same
1460 // behaviour as we had before this change, so the risks are low.
1461 if (!isInsideEventHandler && (!enableFlareAPI || timeStamp === 0 || lastFlushedEventTimeStamp !== timeStamp)) {
1462 lastFlushedEventTimeStamp = timeStamp;
1463 flushDiscreteUpdatesImpl();
1464 }
1465}
1466function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
1467 batchedUpdatesImpl = _batchedUpdatesImpl;
1468 discreteUpdatesImpl = _discreteUpdatesImpl;
1469 flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
1470 batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
1471}
1472
1473var DiscreteEvent = 0;
1474var UserBlockingEvent = 1;
1475var ContinuousEvent = 2;
1476
1477// CommonJS interop named imports.
1478
1479var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
1480var runWithPriority = Scheduler.unstable_runWithPriority;
1481var listenToResponderEventTypesImpl;
1482function setListenToResponderEventTypes(_listenToResponderEventTypesImpl) {
1483 listenToResponderEventTypesImpl = _listenToResponderEventTypesImpl;
1484}
1485var rootEventTypesToEventResponderInstances = new Map();
1486var DoNotPropagateToNextResponder = 0;
1487var PropagateToNextResponder = 1;
1488var currentTimeStamp = 0;
1489var currentInstance = null;
1490var currentDocument = null;
1491var currentPropagationBehavior = DoNotPropagateToNextResponder;
1492var eventResponderContext = {
1493 dispatchEvent: function (eventValue, eventListener, eventPriority) {
1494 validateResponderContext();
1495 validateEventValue(eventValue);
1496
1497 switch (eventPriority) {
1498 case DiscreteEvent:
1499 {
1500 flushDiscreteUpdatesIfNeeded(currentTimeStamp);
1501 discreteUpdates(function () {
1502 return executeUserEventHandler(eventListener, eventValue);
1503 });
1504 break;
1505 }
1506
1507 case UserBlockingEvent:
1508 {
1509 runWithPriority(UserBlockingPriority, function () {
1510 return executeUserEventHandler(eventListener, eventValue);
1511 });
1512 break;
1513 }
1514
1515 case ContinuousEvent:
1516 {
1517 executeUserEventHandler(eventListener, eventValue);
1518 break;
1519 }
1520 }
1521 },
1522 isTargetWithinResponder: function (target) {
1523 validateResponderContext();
1524
1525 if (target != null) {
1526 var fiber = getClosestInstanceFromNode(target);
1527 var responderFiber = currentInstance.fiber;
1528
1529 while (fiber !== null) {
1530 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1531 return true;
1532 }
1533
1534 fiber = fiber.return;
1535 }
1536 }
1537
1538 return false;
1539 },
1540 isTargetWithinResponderScope: function (target) {
1541 validateResponderContext();
1542 var componentInstance = currentInstance;
1543 var responder = componentInstance.responder;
1544
1545 if (target != null) {
1546 var fiber = getClosestInstanceFromNode(target);
1547 var responderFiber = currentInstance.fiber;
1548
1549 while (fiber !== null) {
1550 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1551 return true;
1552 }
1553
1554 if (doesFiberHaveResponder(fiber, responder)) {
1555 return false;
1556 }
1557
1558 fiber = fiber.return;
1559 }
1560 }
1561
1562 return false;
1563 },
1564 isTargetWithinNode: function (childTarget, parentTarget) {
1565 validateResponderContext();
1566 var childFiber = getClosestInstanceFromNode(childTarget);
1567 var parentFiber = getClosestInstanceFromNode(parentTarget);
1568
1569 if (childFiber != null && parentFiber != null) {
1570 var parentAlternateFiber = parentFiber.alternate;
1571 var node = childFiber;
1572
1573 while (node !== null) {
1574 if (node === parentFiber || node === parentAlternateFiber) {
1575 return true;
1576 }
1577
1578 node = node.return;
1579 }
1580
1581 return false;
1582 } // Fallback to DOM APIs
1583
1584
1585 return parentTarget.contains(childTarget);
1586 },
1587 addRootEventTypes: function (rootEventTypes) {
1588 validateResponderContext();
1589 listenToResponderEventTypesImpl(rootEventTypes, currentDocument);
1590
1591 for (var i = 0; i < rootEventTypes.length; i++) {
1592 var rootEventType = rootEventTypes[i];
1593 var eventResponderInstance = currentInstance;
1594 registerRootEventType(rootEventType, eventResponderInstance);
1595 }
1596 },
1597 removeRootEventTypes: function (rootEventTypes) {
1598 validateResponderContext();
1599
1600 for (var i = 0; i < rootEventTypes.length; i++) {
1601 var rootEventType = rootEventTypes[i];
1602 var rootEventResponders = rootEventTypesToEventResponderInstances.get(rootEventType);
1603 var rootEventTypesSet = currentInstance.rootEventTypes;
1604
1605 if (rootEventTypesSet !== null) {
1606 rootEventTypesSet.delete(rootEventType);
1607 }
1608
1609 if (rootEventResponders !== undefined) {
1610 rootEventResponders.delete(currentInstance);
1611 }
1612 }
1613 },
1614 getActiveDocument: getActiveDocument,
1615 objectAssign: _assign,
1616 getTimeStamp: function () {
1617 validateResponderContext();
1618 return currentTimeStamp;
1619 },
1620 isTargetWithinHostComponent: function (target, elementType) {
1621 validateResponderContext();
1622 var fiber = getClosestInstanceFromNode(target);
1623
1624 while (fiber !== null) {
1625 if (fiber.tag === HostComponent && fiber.type === elementType) {
1626 return true;
1627 }
1628
1629 fiber = fiber.return;
1630 }
1631
1632 return false;
1633 },
1634 continuePropagation: function () {
1635 currentPropagationBehavior = PropagateToNextResponder;
1636 },
1637 enqueueStateRestore: enqueueStateRestore,
1638 getResponderNode: function () {
1639 validateResponderContext();
1640 var responderFiber = currentInstance.fiber;
1641
1642 if (responderFiber.tag === ScopeComponent) {
1643 return null;
1644 }
1645
1646 return responderFiber.stateNode;
1647 }
1648};
1649
1650function validateEventValue(eventValue) {
1651 if (typeof eventValue === 'object' && eventValue !== null) {
1652 var target = eventValue.target,
1653 type = eventValue.type,
1654 timeStamp = eventValue.timeStamp;
1655
1656 if (target == null || type == null || timeStamp == null) {
1657 throw new Error('context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.');
1658 }
1659
1660 var showWarning = function (name) {
1661 {
1662 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);
1663 }
1664 };
1665
1666 eventValue.isDefaultPrevented = function () {
1667 {
1668 showWarning('isDefaultPrevented()');
1669 }
1670 };
1671
1672 eventValue.isPropagationStopped = function () {
1673 {
1674 showWarning('isPropagationStopped()');
1675 }
1676 }; // $FlowFixMe: we don't need value, Flow thinks we do
1677
1678
1679 Object.defineProperty(eventValue, 'nativeEvent', {
1680 get: function () {
1681 {
1682 showWarning('nativeEvent');
1683 }
1684 }
1685 });
1686 }
1687}
1688
1689function doesFiberHaveResponder(fiber, responder) {
1690 var tag = fiber.tag;
1691
1692 if (tag === HostComponent || tag === ScopeComponent) {
1693 var dependencies = fiber.dependencies;
1694
1695 if (dependencies !== null) {
1696 var respondersMap = dependencies.responders;
1697
1698 if (respondersMap !== null && respondersMap.has(responder)) {
1699 return true;
1700 }
1701 }
1702 }
1703
1704 return false;
1705}
1706
1707function getActiveDocument() {
1708 return currentDocument;
1709}
1710
1711function createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, passive, passiveSupported) {
1712 var _ref = nativeEvent,
1713 buttons = _ref.buttons,
1714 pointerType = _ref.pointerType;
1715 var eventPointerType = '';
1716
1717 if (pointerType !== undefined) {
1718 eventPointerType = pointerType;
1719 } else if (nativeEvent.key !== undefined) {
1720 eventPointerType = 'keyboard';
1721 } else if (buttons !== undefined) {
1722 eventPointerType = 'mouse';
1723 } else if (nativeEvent.changedTouches !== undefined) {
1724 eventPointerType = 'touch';
1725 }
1726
1727 return {
1728 nativeEvent: nativeEvent,
1729 passive: passive,
1730 passiveSupported: passiveSupported,
1731 pointerType: eventPointerType,
1732 target: nativeEventTarget,
1733 type: topLevelType
1734 };
1735}
1736
1737function responderEventTypesContainType(eventTypes, type) {
1738 for (var i = 0, len = eventTypes.length; i < len; i++) {
1739 if (eventTypes[i] === type) {
1740 return true;
1741 }
1742 }
1743
1744 return false;
1745}
1746
1747function validateResponderTargetEventTypes(eventType, responder) {
1748 var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder
1749
1750 if (targetEventTypes !== null) {
1751 return responderEventTypesContainType(targetEventTypes, eventType);
1752 }
1753
1754 return false;
1755}
1756
1757function traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1758 var isPassiveEvent = (eventSystemFlags & IS_PASSIVE) !== 0;
1759 var isPassiveSupported = (eventSystemFlags & PASSIVE_NOT_SUPPORTED) === 0;
1760 var isPassive = isPassiveEvent || !isPassiveSupported;
1761 var eventType = isPassive ? topLevelType : topLevelType + '_active'; // Trigger event responders in this order:
1762 // - Bubble target responder phase
1763 // - Root responder phase
1764
1765 var visitedResponders = new Set();
1766 var responderEvent = createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, isPassiveEvent, isPassiveSupported);
1767 var node = targetFiber;
1768 var insidePortal = false;
1769
1770 while (node !== null) {
1771 var _node = node,
1772 dependencies = _node.dependencies,
1773 tag = _node.tag;
1774
1775 if (tag === HostPortal) {
1776 insidePortal = true;
1777 } else if ((tag === HostComponent || tag === ScopeComponent) && dependencies !== null) {
1778 var respondersMap = dependencies.responders;
1779
1780 if (respondersMap !== null) {
1781 var responderInstances = Array.from(respondersMap.values());
1782
1783 for (var i = 0, length = responderInstances.length; i < length; i++) {
1784 var responderInstance = responderInstances[i];
1785 var props = responderInstance.props,
1786 responder = responderInstance.responder,
1787 state = responderInstance.state;
1788
1789 if (!visitedResponders.has(responder) && validateResponderTargetEventTypes(eventType, responder) && (!insidePortal || responder.targetPortalPropagation)) {
1790 visitedResponders.add(responder);
1791 var onEvent = responder.onEvent;
1792
1793 if (onEvent !== null) {
1794 currentInstance = responderInstance;
1795 onEvent(responderEvent, eventResponderContext, props, state);
1796
1797 if (currentPropagationBehavior === PropagateToNextResponder) {
1798 visitedResponders.delete(responder);
1799 currentPropagationBehavior = DoNotPropagateToNextResponder;
1800 }
1801 }
1802 }
1803 }
1804 }
1805 }
1806
1807 node = node.return;
1808 } // Root phase
1809
1810
1811 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(eventType);
1812
1813 if (rootEventResponderInstances !== undefined) {
1814 var _responderInstances = Array.from(rootEventResponderInstances);
1815
1816 for (var _i = 0; _i < _responderInstances.length; _i++) {
1817 var _responderInstance = _responderInstances[_i];
1818 var props = _responderInstance.props,
1819 responder = _responderInstance.responder,
1820 state = _responderInstance.state;
1821 var onRootEvent = responder.onRootEvent;
1822
1823 if (onRootEvent !== null) {
1824 currentInstance = _responderInstance;
1825 onRootEvent(responderEvent, eventResponderContext, props, state);
1826 }
1827 }
1828 }
1829}
1830
1831function mountEventResponder(responder, responderInstance, props, state) {
1832 var onMount = responder.onMount;
1833
1834 if (onMount !== null) {
1835 var previousInstance = currentInstance;
1836 currentInstance = responderInstance;
1837
1838 try {
1839 batchedEventUpdates(function () {
1840 onMount(eventResponderContext, props, state);
1841 });
1842 } finally {
1843 currentInstance = previousInstance;
1844 }
1845 }
1846}
1847function unmountEventResponder(responderInstance) {
1848 var responder = responderInstance.responder;
1849 var onUnmount = responder.onUnmount;
1850
1851 if (onUnmount !== null) {
1852 var props = responderInstance.props,
1853 state = responderInstance.state;
1854 var previousInstance = currentInstance;
1855 currentInstance = responderInstance;
1856
1857 try {
1858 batchedEventUpdates(function () {
1859 onUnmount(eventResponderContext, props, state);
1860 });
1861 } finally {
1862 currentInstance = previousInstance;
1863 }
1864 }
1865
1866 var rootEventTypesSet = responderInstance.rootEventTypes;
1867
1868 if (rootEventTypesSet !== null) {
1869 var rootEventTypes = Array.from(rootEventTypesSet);
1870
1871 for (var i = 0; i < rootEventTypes.length; i++) {
1872 var topLevelEventType = rootEventTypes[i];
1873 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(topLevelEventType);
1874
1875 if (rootEventResponderInstances !== undefined) {
1876 rootEventResponderInstances.delete(responderInstance);
1877 }
1878 }
1879 }
1880}
1881
1882function validateResponderContext() {
1883 if (!(currentInstance !== null)) {
1884 {
1885 throw Error("An event responder context was used outside of an event cycle.");
1886 }
1887 }
1888}
1889
1890function dispatchEventForResponderEventSystem(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1891 if (enableFlareAPI) {
1892 var previousInstance = currentInstance;
1893 var previousTimeStamp = currentTimeStamp;
1894 var previousDocument = currentDocument;
1895 var previousPropagationBehavior = currentPropagationBehavior;
1896 currentPropagationBehavior = DoNotPropagateToNextResponder; // nodeType 9 is DOCUMENT_NODE
1897
1898 currentDocument = nativeEventTarget.nodeType === 9 ? nativeEventTarget : nativeEventTarget.ownerDocument; // We might want to control timeStamp another way here
1899
1900 currentTimeStamp = nativeEvent.timeStamp;
1901
1902 try {
1903 batchedEventUpdates(function () {
1904 traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags);
1905 });
1906 } finally {
1907 currentInstance = previousInstance;
1908 currentTimeStamp = previousTimeStamp;
1909 currentDocument = previousDocument;
1910 currentPropagationBehavior = previousPropagationBehavior;
1911 }
1912 }
1913}
1914function addRootEventTypesForResponderInstance(responderInstance, rootEventTypes) {
1915 for (var i = 0; i < rootEventTypes.length; i++) {
1916 var rootEventType = rootEventTypes[i];
1917 registerRootEventType(rootEventType, responderInstance);
1918 }
1919}
1920
1921function registerRootEventType(rootEventType, eventResponderInstance) {
1922 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(rootEventType);
1923
1924 if (rootEventResponderInstances === undefined) {
1925 rootEventResponderInstances = new Set();
1926 rootEventTypesToEventResponderInstances.set(rootEventType, rootEventResponderInstances);
1927 }
1928
1929 var rootEventTypesSet = eventResponderInstance.rootEventTypes;
1930
1931 if (rootEventTypesSet === null) {
1932 rootEventTypesSet = eventResponderInstance.rootEventTypes = new Set();
1933 }
1934
1935 if (!!rootEventTypesSet.has(rootEventType)) {
1936 {
1937 throw 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.");
1938 }
1939 }
1940
1941 rootEventTypesSet.add(rootEventType);
1942 rootEventResponderInstances.add(eventResponderInstance);
1943}
1944
1945// A reserved attribute.
1946// It is handled by React separately and shouldn't be written to the DOM.
1947var RESERVED = 0; // A simple string attribute.
1948// Attributes that aren't in the whitelist are presumed to have this type.
1949
1950var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
1951// "enumerated" attributes with "true" and "false" as possible values.
1952// When true, it should be set to a "true" string.
1953// When false, it should be set to a "false" string.
1954
1955var BOOLEANISH_STRING = 2; // A real boolean attribute.
1956// When true, it should be present (set either to an empty string or its name).
1957// When false, it should be omitted.
1958
1959var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
1960// When true, it should be present (set either to an empty string or its name).
1961// When false, it should be omitted.
1962// For any other value, should be present with that value.
1963
1964var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
1965// When falsy, it should be removed.
1966
1967var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
1968// When falsy, it should be removed.
1969
1970var POSITIVE_NUMERIC = 6;
1971
1972/* eslint-disable max-len */
1973var 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";
1974/* eslint-enable max-len */
1975
1976var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
1977
1978var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
1979var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
1980var hasOwnProperty = Object.prototype.hasOwnProperty;
1981var illegalAttributeNameCache = {};
1982var validatedAttributeNameCache = {};
1983function isAttributeNameSafe(attributeName) {
1984 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
1985 return true;
1986 }
1987
1988 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
1989 return false;
1990 }
1991
1992 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
1993 validatedAttributeNameCache[attributeName] = true;
1994 return true;
1995 }
1996
1997 illegalAttributeNameCache[attributeName] = true;
1998
1999 {
2000 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2001 }
2002
2003 return false;
2004}
2005function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2006 if (propertyInfo !== null) {
2007 return propertyInfo.type === RESERVED;
2008 }
2009
2010 if (isCustomComponentTag) {
2011 return false;
2012 }
2013
2014 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2015 return true;
2016 }
2017
2018 return false;
2019}
2020function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2021 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2022 return false;
2023 }
2024
2025 switch (typeof value) {
2026 case 'function': // $FlowIssue symbol is perfectly valid here
2027
2028 case 'symbol':
2029 // eslint-disable-line
2030 return true;
2031
2032 case 'boolean':
2033 {
2034 if (isCustomComponentTag) {
2035 return false;
2036 }
2037
2038 if (propertyInfo !== null) {
2039 return !propertyInfo.acceptsBooleans;
2040 } else {
2041 var prefix = name.toLowerCase().slice(0, 5);
2042 return prefix !== 'data-' && prefix !== 'aria-';
2043 }
2044 }
2045
2046 default:
2047 return false;
2048 }
2049}
2050function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2051 if (value === null || typeof value === 'undefined') {
2052 return true;
2053 }
2054
2055 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2056 return true;
2057 }
2058
2059 if (isCustomComponentTag) {
2060 return false;
2061 }
2062
2063 if (propertyInfo !== null) {
2064 switch (propertyInfo.type) {
2065 case BOOLEAN:
2066 return !value;
2067
2068 case OVERLOADED_BOOLEAN:
2069 return value === false;
2070
2071 case NUMERIC:
2072 return isNaN(value);
2073
2074 case POSITIVE_NUMERIC:
2075 return isNaN(value) || value < 1;
2076 }
2077 }
2078
2079 return false;
2080}
2081function getPropertyInfo(name) {
2082 return properties.hasOwnProperty(name) ? properties[name] : null;
2083}
2084
2085function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
2086 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2087 this.attributeName = attributeName;
2088 this.attributeNamespace = attributeNamespace;
2089 this.mustUseProperty = mustUseProperty;
2090 this.propertyName = name;
2091 this.type = type;
2092 this.sanitizeURL = sanitizeURL;
2093} // When adding attributes to this list, be sure to also add them to
2094// the `possibleStandardNames` module to ensure casing and incorrect
2095// name warnings.
2096
2097
2098var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
2099
2100['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
2101// elements (not just inputs). Now that ReactDOMInput assigns to the
2102// defaultValue property -- do we need this?
2103'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2104 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2105 name, // attributeName
2106 null, // attributeNamespace
2107 false);
2108}); // A few React string attributes have a different name.
2109// This is a mapping from React prop names to the attribute names.
2110
2111[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2112 var name = _ref[0],
2113 attributeName = _ref[1];
2114 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2115 attributeName, // attributeName
2116 null, // attributeNamespace
2117 false);
2118}); // These are "enumerated" HTML attributes that accept "true" and "false".
2119// In React, we let users pass `true` and `false` even though technically
2120// these aren't boolean attributes (they are coerced to strings).
2121
2122['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2123 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2124 name.toLowerCase(), // attributeName
2125 null, // attributeNamespace
2126 false);
2127}); // These are "enumerated" SVG attributes that accept "true" and "false".
2128// In React, we let users pass `true` and `false` even though technically
2129// these aren't boolean attributes (they are coerced to strings).
2130// Since these are SVG attributes, their attribute names are case-sensitive.
2131
2132['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2133 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2134 name, // attributeName
2135 null, // attributeNamespace
2136 false);
2137}); // These are HTML boolean attributes.
2138
2139['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
2140// on the client side because the browsers are inconsistent. Instead we call focus().
2141'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
2142'itemScope'].forEach(function (name) {
2143 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2144 name.toLowerCase(), // attributeName
2145 null, // attributeNamespace
2146 false);
2147}); // These are the few React props that we set as DOM properties
2148// rather than attributes. These are all booleans.
2149
2150['checked', // Note: `option.selected` is not updated if `select.multiple` is
2151// disabled with `removeAttribute`. We have special logic for handling this.
2152'multiple', 'muted', 'selected'].forEach(function (name) {
2153 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2154 name, // attributeName
2155 null, // attributeNamespace
2156 false);
2157}); // These are HTML attributes that are "overloaded booleans": they behave like
2158// booleans, but can also accept a string value.
2159
2160['capture', 'download'].forEach(function (name) {
2161 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2162 name, // attributeName
2163 null, // attributeNamespace
2164 false);
2165}); // These are HTML attributes that must be positive numbers.
2166
2167['cols', 'rows', 'size', 'span'].forEach(function (name) {
2168 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2169 name, // attributeName
2170 null, // attributeNamespace
2171 false);
2172}); // These are HTML attributes that must be numbers.
2173
2174['rowSpan', 'start'].forEach(function (name) {
2175 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2176 name.toLowerCase(), // attributeName
2177 null, // attributeNamespace
2178 false);
2179});
2180var CAMELIZE = /[\-\:]([a-z])/g;
2181
2182var capitalize = function (token) {
2183 return token[1].toUpperCase();
2184}; // This is a list of all SVG attributes that need special casing, namespacing,
2185// or boolean value assignment. Regular attributes that just accept strings
2186// and have the same names are omitted, just like in the HTML whitelist.
2187// Some of these attributes can be hard to find. This list was created by
2188// scrapping the MDN documentation.
2189
2190
2191['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) {
2192 var name = attributeName.replace(CAMELIZE, capitalize);
2193 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2194 attributeName, null, // attributeNamespace
2195 false);
2196}); // String SVG attributes with the xlink namespace.
2197
2198['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2199 var name = attributeName.replace(CAMELIZE, capitalize);
2200 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2201 attributeName, 'http://www.w3.org/1999/xlink', false);
2202}); // String SVG attributes with the xml namespace.
2203
2204['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2205 var name = attributeName.replace(CAMELIZE, capitalize);
2206 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2207 attributeName, 'http://www.w3.org/XML/1998/namespace', false);
2208}); // These attribute exists both in HTML and SVG.
2209// The attribute name is case-sensitive in SVG so we can't just use
2210// the React name like we do for attributes that exist only in HTML.
2211
2212['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
2213 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2214 attributeName.toLowerCase(), // attributeName
2215 null, // attributeNamespace
2216 false);
2217}); // These attributes accept URLs. These must not allow javascript: URLS.
2218// These will also need to accept Trusted Types object in the future.
2219
2220var xlinkHref = 'xlinkHref';
2221properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
2222'xlink:href', 'http://www.w3.org/1999/xlink', true);
2223['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
2224 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2225 attributeName.toLowerCase(), // attributeName
2226 null, // attributeNamespace
2227 true);
2228});
2229
2230var ReactDebugCurrentFrame$1 = null;
2231
2232{
2233 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2234} // A javascript: URL can contain leading C0 control or \u0020 SPACE,
2235// and any newline or tab are filtered out as if they're not part of the URL.
2236// https://url.spec.whatwg.org/#url-parsing
2237// Tab or newline are defined as \r\n\t:
2238// https://infra.spec.whatwg.org/#ascii-tab-or-newline
2239// A C0 control is a code point in the range \u0000 NULL to \u001F
2240// INFORMATION SEPARATOR ONE, inclusive:
2241// https://infra.spec.whatwg.org/#c0-control-or-space
2242
2243/* eslint-disable max-len */
2244
2245
2246var 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;
2247var didWarn = false;
2248
2249function sanitizeURL(url) {
2250 if (disableJavaScriptURLs) {
2251 if (!!isJavaScriptProtocol.test(url)) {
2252 {
2253 throw Error("React has blocked a javascript: URL as a security precaution." + (ReactDebugCurrentFrame$1.getStackAddendum()));
2254 }
2255 }
2256 } else if (true && !didWarn && isJavaScriptProtocol.test(url)) {
2257 didWarn = true;
2258 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));
2259 }
2260}
2261
2262// Flow does not allow string concatenation of most non-string types. To work
2263// around this limitation, we use an opaque type that can only be obtained by
2264// passing the value through getToStringValue first.
2265function toString(value) {
2266 return '' + value;
2267}
2268function getToStringValue(value) {
2269 switch (typeof value) {
2270 case 'boolean':
2271 case 'number':
2272 case 'object':
2273 case 'string':
2274 case 'undefined':
2275 return value;
2276
2277 default:
2278 // function, symbol are assigned as empty strings
2279 return '';
2280 }
2281}
2282/** Trusted value is a wrapper for "safe" values which can be assigned to DOM execution sinks. */
2283
2284/**
2285 * We allow passing objects with toString method as element attributes or in dangerouslySetInnerHTML
2286 * and we do validations that the value is safe. Once we do validation we want to use the validated
2287 * value instead of the object (because object.toString may return something else on next call).
2288 *
2289 * If application uses Trusted Types we don't stringify trusted values, but preserve them as objects.
2290 */
2291var toStringOrTrustedType = toString;
2292
2293if (enableTrustedTypesIntegration && typeof trustedTypes !== 'undefined') {
2294 toStringOrTrustedType = function (value) {
2295 if (typeof value === 'object' && (trustedTypes.isHTML(value) || trustedTypes.isScript(value) || trustedTypes.isScriptURL(value) ||
2296 /* TrustedURLs are deprecated and will be removed soon: https://github.com/WICG/trusted-types/pull/204 */
2297 trustedTypes.isURL && trustedTypes.isURL(value))) {
2298 // Pass Trusted Types through.
2299 return value;
2300 }
2301
2302 return toString(value);
2303 };
2304}
2305
2306/**
2307 * Set attribute for a node. The attribute value can be either string or
2308 * Trusted value (if application uses Trusted Types).
2309 */
2310function setAttribute(node, attributeName, attributeValue) {
2311 node.setAttribute(attributeName, attributeValue);
2312}
2313/**
2314 * Set attribute with namespace for a node. The attribute value can be either string or
2315 * Trusted value (if application uses Trusted Types).
2316 */
2317
2318function setAttributeNS(node, attributeNamespace, attributeName, attributeValue) {
2319 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
2320}
2321
2322/**
2323 * Get the value for a property on a node. Only used in DEV for SSR validation.
2324 * The "expected" argument is used as a hint of what the expected value is.
2325 * Some properties have multiple equivalent values.
2326 */
2327function getValueForProperty(node, name, expected, propertyInfo) {
2328 {
2329 if (propertyInfo.mustUseProperty) {
2330 var propertyName = propertyInfo.propertyName;
2331 return node[propertyName];
2332 } else {
2333 if (!disableJavaScriptURLs && propertyInfo.sanitizeURL) {
2334 // If we haven't fully disabled javascript: URLs, and if
2335 // the hydration is successful of a javascript: URL, we
2336 // still want to warn on the client.
2337 sanitizeURL('' + expected);
2338 }
2339
2340 var attributeName = propertyInfo.attributeName;
2341 var stringValue = null;
2342
2343 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2344 if (node.hasAttribute(attributeName)) {
2345 var value = node.getAttribute(attributeName);
2346
2347 if (value === '') {
2348 return true;
2349 }
2350
2351 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2352 return value;
2353 }
2354
2355 if (value === '' + expected) {
2356 return expected;
2357 }
2358
2359 return value;
2360 }
2361 } else if (node.hasAttribute(attributeName)) {
2362 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2363 // We had an attribute but shouldn't have had one, so read it
2364 // for the error message.
2365 return node.getAttribute(attributeName);
2366 }
2367
2368 if (propertyInfo.type === BOOLEAN) {
2369 // If this was a boolean, it doesn't matter what the value is
2370 // the fact that we have it is the same as the expected.
2371 return expected;
2372 } // Even if this property uses a namespace we use getAttribute
2373 // because we assume its namespaced name is the same as our config.
2374 // To use getAttributeNS we need the local name which we don't have
2375 // in our config atm.
2376
2377
2378 stringValue = node.getAttribute(attributeName);
2379 }
2380
2381 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2382 return stringValue === null ? expected : stringValue;
2383 } else if (stringValue === '' + expected) {
2384 return expected;
2385 } else {
2386 return stringValue;
2387 }
2388 }
2389 }
2390}
2391/**
2392 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2393 * The third argument is used as a hint of what the expected value is. Some
2394 * attributes have multiple equivalent values.
2395 */
2396
2397function getValueForAttribute(node, name, expected) {
2398 {
2399 if (!isAttributeNameSafe(name)) {
2400 return;
2401 }
2402
2403 if (!node.hasAttribute(name)) {
2404 return expected === undefined ? undefined : null;
2405 }
2406
2407 var value = node.getAttribute(name);
2408
2409 if (value === '' + expected) {
2410 return expected;
2411 }
2412
2413 return value;
2414 }
2415}
2416/**
2417 * Sets the value for a property on a node.
2418 *
2419 * @param {DOMElement} node
2420 * @param {string} name
2421 * @param {*} value
2422 */
2423
2424function setValueForProperty(node, name, value, isCustomComponentTag) {
2425 var propertyInfo = getPropertyInfo(name);
2426
2427 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
2428 return;
2429 }
2430
2431 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
2432 value = null;
2433 } // If the prop isn't in the special list, treat it as a simple attribute.
2434
2435
2436 if (isCustomComponentTag || propertyInfo === null) {
2437 if (isAttributeNameSafe(name)) {
2438 var _attributeName = name;
2439
2440 if (value === null) {
2441 node.removeAttribute(_attributeName);
2442 } else {
2443 setAttribute(node, _attributeName, toStringOrTrustedType(value));
2444 }
2445 }
2446
2447 return;
2448 }
2449
2450 var mustUseProperty = propertyInfo.mustUseProperty;
2451
2452 if (mustUseProperty) {
2453 var propertyName = propertyInfo.propertyName;
2454
2455 if (value === null) {
2456 var type = propertyInfo.type;
2457 node[propertyName] = type === BOOLEAN ? false : '';
2458 } else {
2459 // Contrary to `setAttribute`, object properties are properly
2460 // `toString`ed by IE8/9.
2461 node[propertyName] = value;
2462 }
2463
2464 return;
2465 } // The rest are treated as attributes with special cases.
2466
2467
2468 var attributeName = propertyInfo.attributeName,
2469 attributeNamespace = propertyInfo.attributeNamespace;
2470
2471 if (value === null) {
2472 node.removeAttribute(attributeName);
2473 } else {
2474 var _type = propertyInfo.type;
2475 var attributeValue;
2476
2477 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
2478 // If attribute type is boolean, we know for sure it won't be an execution sink
2479 // and we won't require Trusted Type here.
2480 attributeValue = '';
2481 } else {
2482 // `setAttribute` with objects becomes only `[object]` in IE8/9,
2483 // ('' + value) makes it output the correct toString()-value.
2484 attributeValue = toStringOrTrustedType(value);
2485
2486 if (propertyInfo.sanitizeURL) {
2487 sanitizeURL(attributeValue.toString());
2488 }
2489 }
2490
2491 if (attributeNamespace) {
2492 setAttributeNS(node, attributeNamespace, attributeName, attributeValue);
2493 } else {
2494 setAttribute(node, attributeName, attributeValue);
2495 }
2496 }
2497}
2498
2499var ReactDebugCurrentFrame$2 = null;
2500var ReactControlledValuePropTypes = {
2501 checkPropTypes: null
2502};
2503
2504{
2505 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
2506 var hasReadOnlyValue = {
2507 button: true,
2508 checkbox: true,
2509 image: true,
2510 hidden: true,
2511 radio: true,
2512 reset: true,
2513 submit: true
2514 };
2515 var propTypes = {
2516 value: function (props, propName, componentName) {
2517 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2518 return null;
2519 }
2520
2521 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`.');
2522 },
2523 checked: function (props, propName, componentName) {
2524 if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2525 return null;
2526 }
2527
2528 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`.');
2529 }
2530 };
2531 /**
2532 * Provide a linked `value` attribute for controlled forms. You should not use
2533 * this outside of the ReactDOM controlled form components.
2534 */
2535
2536 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
2537 checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
2538 };
2539}
2540
2541function isCheckable(elem) {
2542 var type = elem.type;
2543 var nodeName = elem.nodeName;
2544 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2545}
2546
2547function getTracker(node) {
2548 return node._valueTracker;
2549}
2550
2551function detachTracker(node) {
2552 node._valueTracker = null;
2553}
2554
2555function getValueFromNode(node) {
2556 var value = '';
2557
2558 if (!node) {
2559 return value;
2560 }
2561
2562 if (isCheckable(node)) {
2563 value = node.checked ? 'true' : 'false';
2564 } else {
2565 value = node.value;
2566 }
2567
2568 return value;
2569}
2570
2571function trackValueOnNode(node) {
2572 var valueField = isCheckable(node) ? 'checked' : 'value';
2573 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2574 var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
2575 // and don't track value will cause over reporting of changes,
2576 // but it's better then a hard failure
2577 // (needed for certain tests that spyOn input values and Safari)
2578
2579 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2580 return;
2581 }
2582
2583 var get = descriptor.get,
2584 set = descriptor.set;
2585 Object.defineProperty(node, valueField, {
2586 configurable: true,
2587 get: function () {
2588 return get.call(this);
2589 },
2590 set: function (value) {
2591 currentValue = '' + value;
2592 set.call(this, value);
2593 }
2594 }); // We could've passed this the first time
2595 // but it triggers a bug in IE11 and Edge 14/15.
2596 // Calling defineProperty() again should be equivalent.
2597 // https://github.com/facebook/react/issues/11768
2598
2599 Object.defineProperty(node, valueField, {
2600 enumerable: descriptor.enumerable
2601 });
2602 var tracker = {
2603 getValue: function () {
2604 return currentValue;
2605 },
2606 setValue: function (value) {
2607 currentValue = '' + value;
2608 },
2609 stopTracking: function () {
2610 detachTracker(node);
2611 delete node[valueField];
2612 }
2613 };
2614 return tracker;
2615}
2616
2617function track(node) {
2618 if (getTracker(node)) {
2619 return;
2620 } // TODO: Once it's just Fiber we can move this to node._wrapperState
2621
2622
2623 node._valueTracker = trackValueOnNode(node);
2624}
2625function updateValueIfChanged(node) {
2626 if (!node) {
2627 return false;
2628 }
2629
2630 var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
2631 // that trying again will succeed
2632
2633 if (!tracker) {
2634 return true;
2635 }
2636
2637 var lastValue = tracker.getValue();
2638 var nextValue = getValueFromNode(node);
2639
2640 if (nextValue !== lastValue) {
2641 tracker.setValue(nextValue);
2642 return true;
2643 }
2644
2645 return false;
2646}
2647
2648// TODO: direct imports like some-package/src/* are bad. Fix me.
2649var didWarnValueDefaultValue = false;
2650var didWarnCheckedDefaultChecked = false;
2651var didWarnControlledToUncontrolled = false;
2652var didWarnUncontrolledToControlled = false;
2653
2654function isControlled(props) {
2655 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
2656 return usesChecked ? props.checked != null : props.value != null;
2657}
2658/**
2659 * Implements an <input> host component that allows setting these optional
2660 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
2661 *
2662 * If `checked` or `value` are not supplied (or null/undefined), user actions
2663 * that affect the checked state or value will trigger updates to the element.
2664 *
2665 * If they are supplied (and not null/undefined), the rendered element will not
2666 * trigger updates to the element. Instead, the props must change in order for
2667 * the rendered element to be updated.
2668 *
2669 * The rendered element will be initialized as unchecked (or `defaultChecked`)
2670 * with an empty value (or `defaultValue`).
2671 *
2672 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
2673 */
2674
2675
2676function getHostProps(element, props) {
2677 var node = element;
2678 var checked = props.checked;
2679
2680 var hostProps = _assign({}, props, {
2681 defaultChecked: undefined,
2682 defaultValue: undefined,
2683 value: undefined,
2684 checked: checked != null ? checked : node._wrapperState.initialChecked
2685 });
2686
2687 return hostProps;
2688}
2689function initWrapperState(element, props) {
2690 {
2691 ReactControlledValuePropTypes.checkPropTypes('input', props);
2692
2693 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
2694 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);
2695 didWarnCheckedDefaultChecked = true;
2696 }
2697
2698 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
2699 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);
2700 didWarnValueDefaultValue = true;
2701 }
2702 }
2703
2704 var node = element;
2705 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
2706 node._wrapperState = {
2707 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
2708 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
2709 controlled: isControlled(props)
2710 };
2711}
2712function updateChecked(element, props) {
2713 var node = element;
2714 var checked = props.checked;
2715
2716 if (checked != null) {
2717 setValueForProperty(node, 'checked', checked, false);
2718 }
2719}
2720function updateWrapper(element, props) {
2721 var node = element;
2722
2723 {
2724 var controlled = isControlled(props);
2725
2726 if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
2727 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);
2728 didWarnUncontrolledToControlled = true;
2729 }
2730
2731 if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
2732 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);
2733 didWarnControlledToUncontrolled = true;
2734 }
2735 }
2736
2737 updateChecked(element, props);
2738 var value = getToStringValue(props.value);
2739 var type = props.type;
2740
2741 if (value != null) {
2742 if (type === 'number') {
2743 if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
2744 // eslint-disable-next-line
2745 node.value != value) {
2746 node.value = toString(value);
2747 }
2748 } else if (node.value !== toString(value)) {
2749 node.value = toString(value);
2750 }
2751 } else if (type === 'submit' || type === 'reset') {
2752 // Submit/reset inputs need the attribute removed completely to avoid
2753 // blank-text buttons.
2754 node.removeAttribute('value');
2755 return;
2756 }
2757
2758 if (disableInputAttributeSyncing) {
2759 // When not syncing the value attribute, React only assigns a new value
2760 // whenever the defaultValue React prop has changed. When not present,
2761 // React does nothing
2762 if (props.hasOwnProperty('defaultValue')) {
2763 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2764 }
2765 } else {
2766 // When syncing the value attribute, the value comes from a cascade of
2767 // properties:
2768 // 1. The value React property
2769 // 2. The defaultValue React property
2770 // 3. Otherwise there should be no change
2771 if (props.hasOwnProperty('value')) {
2772 setDefaultValue(node, props.type, value);
2773 } else if (props.hasOwnProperty('defaultValue')) {
2774 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2775 }
2776 }
2777
2778 if (disableInputAttributeSyncing) {
2779 // When not syncing the checked attribute, the attribute is directly
2780 // controllable from the defaultValue React property. It needs to be
2781 // updated as new props come in.
2782 if (props.defaultChecked == null) {
2783 node.removeAttribute('checked');
2784 } else {
2785 node.defaultChecked = !!props.defaultChecked;
2786 }
2787 } else {
2788 // When syncing the checked attribute, it only changes when it needs
2789 // to be removed, such as transitioning from a checkbox into a text input
2790 if (props.checked == null && props.defaultChecked != null) {
2791 node.defaultChecked = !!props.defaultChecked;
2792 }
2793 }
2794}
2795function postMountWrapper(element, props, isHydrating) {
2796 var node = element; // Do not assign value if it is already set. This prevents user text input
2797 // from being lost during SSR hydration.
2798
2799 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
2800 var type = props.type;
2801 var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
2802 // default value provided by the browser. See: #12872
2803
2804 if (isButton && (props.value === undefined || props.value === null)) {
2805 return;
2806 }
2807
2808 var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
2809 // from being lost during SSR hydration.
2810
2811 if (!isHydrating) {
2812 if (disableInputAttributeSyncing) {
2813 var value = getToStringValue(props.value); // When not syncing the value attribute, the value property points
2814 // directly to the React prop. Only assign it if it exists.
2815
2816 if (value != null) {
2817 // Always assign on buttons so that it is possible to assign an
2818 // empty string to clear button text.
2819 //
2820 // Otherwise, do not re-assign the value property if is empty. This
2821 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
2822 // prematurely marking required inputs as invalid. Equality is compared
2823 // to the current value in case the browser provided value is not an
2824 // empty string.
2825 if (isButton || value !== node.value) {
2826 node.value = toString(value);
2827 }
2828 }
2829 } else {
2830 // When syncing the value attribute, the value property should use
2831 // the wrapperState._initialValue property. This uses:
2832 //
2833 // 1. The value React property when present
2834 // 2. The defaultValue React property when present
2835 // 3. An empty string
2836 if (initialValue !== node.value) {
2837 node.value = initialValue;
2838 }
2839 }
2840 }
2841
2842 if (disableInputAttributeSyncing) {
2843 // When not syncing the value attribute, assign the value attribute
2844 // directly from the defaultValue React property (when present)
2845 var defaultValue = getToStringValue(props.defaultValue);
2846
2847 if (defaultValue != null) {
2848 node.defaultValue = toString(defaultValue);
2849 }
2850 } else {
2851 // Otherwise, the value attribute is synchronized to the property,
2852 // so we assign defaultValue to the same thing as the value property
2853 // assignment step above.
2854 node.defaultValue = initialValue;
2855 }
2856 } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
2857 // this is needed to work around a chrome bug where setting defaultChecked
2858 // will sometimes influence the value of checked (even after detachment).
2859 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
2860 // We need to temporarily unset name to avoid disrupting radio button groups.
2861
2862
2863 var name = node.name;
2864
2865 if (name !== '') {
2866 node.name = '';
2867 }
2868
2869 if (disableInputAttributeSyncing) {
2870 // When not syncing the checked attribute, the checked property
2871 // never gets assigned. It must be manually set. We don't want
2872 // to do this when hydrating so that existing user input isn't
2873 // modified
2874 if (!isHydrating) {
2875 updateChecked(element, props);
2876 } // Only assign the checked attribute if it is defined. This saves
2877 // a DOM write when controlling the checked attribute isn't needed
2878 // (text inputs, submit/reset)
2879
2880
2881 if (props.hasOwnProperty('defaultChecked')) {
2882 node.defaultChecked = !node.defaultChecked;
2883 node.defaultChecked = !!props.defaultChecked;
2884 }
2885 } else {
2886 // When syncing the checked attribute, both the checked property and
2887 // attribute are assigned at the same time using defaultChecked. This uses:
2888 //
2889 // 1. The checked React property when present
2890 // 2. The defaultChecked React property when present
2891 // 3. Otherwise, false
2892 node.defaultChecked = !node.defaultChecked;
2893 node.defaultChecked = !!node._wrapperState.initialChecked;
2894 }
2895
2896 if (name !== '') {
2897 node.name = name;
2898 }
2899}
2900function restoreControlledState$1(element, props) {
2901 var node = element;
2902 updateWrapper(node, props);
2903 updateNamedCousins(node, props);
2904}
2905
2906function updateNamedCousins(rootNode, props) {
2907 var name = props.name;
2908
2909 if (props.type === 'radio' && name != null) {
2910 var queryRoot = rootNode;
2911
2912 while (queryRoot.parentNode) {
2913 queryRoot = queryRoot.parentNode;
2914 } // If `rootNode.form` was non-null, then we could try `form.elements`,
2915 // but that sometimes behaves strangely in IE8. We could also try using
2916 // `form.getElementsByName`, but that will only return direct children
2917 // and won't include inputs that use the HTML5 `form=` attribute. Since
2918 // the input might not even be in a form. It might not even be in the
2919 // document. Let's just use the local `querySelectorAll` to ensure we don't
2920 // miss anything.
2921
2922
2923 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
2924
2925 for (var i = 0; i < group.length; i++) {
2926 var otherNode = group[i];
2927
2928 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
2929 continue;
2930 } // This will throw if radio buttons rendered by different copies of React
2931 // and the same name are rendered into the same form (same as #1939).
2932 // That's probably okay; we don't support it just as we don't support
2933 // mixing React radio buttons with non-React ones.
2934
2935
2936 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
2937
2938 if (!otherProps) {
2939 {
2940 throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
2941 }
2942 } // We need update the tracked value on the named cousin since the value
2943 // was changed but the input saw no event or value set
2944
2945
2946 updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
2947 // was previously checked to update will cause it to be come re-checked
2948 // as appropriate.
2949
2950 updateWrapper(otherNode, otherProps);
2951 }
2952 }
2953} // In Chrome, assigning defaultValue to certain input types triggers input validation.
2954// For number inputs, the display value loses trailing decimal points. For email inputs,
2955// Chrome raises "The specified value <x> is not a valid email address".
2956//
2957// Here we check to see if the defaultValue has actually changed, avoiding these problems
2958// when the user is inputting text
2959//
2960// https://github.com/facebook/react/issues/7253
2961
2962
2963function setDefaultValue(node, type, value) {
2964 if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
2965 type !== 'number' || node.ownerDocument.activeElement !== node) {
2966 if (value == null) {
2967 node.defaultValue = toString(node._wrapperState.initialValue);
2968 } else if (node.defaultValue !== toString(value)) {
2969 node.defaultValue = toString(value);
2970 }
2971 }
2972}
2973
2974var didWarnSelectedSetOnOption = false;
2975var didWarnInvalidChild = false;
2976
2977function flattenChildren(children) {
2978 var content = ''; // Flatten children. We'll warn if they are invalid
2979 // during validateProps() which runs for hydration too.
2980 // Note that this would throw on non-element objects.
2981 // Elements are stringified (which is normally irrelevant
2982 // but matters for <fbt>).
2983
2984 React.Children.forEach(children, function (child) {
2985 if (child == null) {
2986 return;
2987 }
2988
2989 content += child; // Note: we don't warn about invalid children here.
2990 // Instead, this is done separately below so that
2991 // it happens during the hydration codepath too.
2992 });
2993 return content;
2994}
2995/**
2996 * Implements an <option> host component that warns when `selected` is set.
2997 */
2998
2999
3000function validateProps(element, props) {
3001 {
3002 // This mirrors the codepath above, but runs for hydration too.
3003 // Warn about invalid children here so that client and hydration are consistent.
3004 // TODO: this seems like it could cause a DEV-only throw for hydration
3005 // if children contains a non-element object. We should try to avoid that.
3006 if (typeof props.children === 'object' && props.children !== null) {
3007 React.Children.forEach(props.children, function (child) {
3008 if (child == null) {
3009 return;
3010 }
3011
3012 if (typeof child === 'string' || typeof child === 'number') {
3013 return;
3014 }
3015
3016 if (typeof child.type !== 'string') {
3017 return;
3018 }
3019
3020 if (!didWarnInvalidChild) {
3021 didWarnInvalidChild = true;
3022 warning$1(false, 'Only strings and numbers are supported as <option> children.');
3023 }
3024 });
3025 } // TODO: Remove support for `selected` in <option>.
3026
3027
3028 if (props.selected != null && !didWarnSelectedSetOnOption) {
3029 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
3030 didWarnSelectedSetOnOption = true;
3031 }
3032 }
3033}
3034function postMountWrapper$1(element, props) {
3035 // value="" should make a value attribute (#6219)
3036 if (props.value != null) {
3037 element.setAttribute('value', toString(getToStringValue(props.value)));
3038 }
3039}
3040function getHostProps$1(element, props) {
3041 var hostProps = _assign({
3042 children: undefined
3043 }, props);
3044
3045 var content = flattenChildren(props.children);
3046
3047 if (content) {
3048 hostProps.children = content;
3049 }
3050
3051 return hostProps;
3052}
3053
3054// TODO: direct imports like some-package/src/* are bad. Fix me.
3055var didWarnValueDefaultValue$1;
3056
3057{
3058 didWarnValueDefaultValue$1 = false;
3059}
3060
3061function getDeclarationErrorAddendum() {
3062 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
3063
3064 if (ownerName) {
3065 return '\n\nCheck the render method of `' + ownerName + '`.';
3066 }
3067
3068 return '';
3069}
3070
3071var valuePropNames = ['value', 'defaultValue'];
3072/**
3073 * Validation function for `value` and `defaultValue`.
3074 */
3075
3076function checkSelectPropTypes(props) {
3077 ReactControlledValuePropTypes.checkPropTypes('select', props);
3078
3079 for (var i = 0; i < valuePropNames.length; i++) {
3080 var propName = valuePropNames[i];
3081
3082 if (props[propName] == null) {
3083 continue;
3084 }
3085
3086 var isArray = Array.isArray(props[propName]);
3087
3088 if (props.multiple && !isArray) {
3089 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
3090 } else if (!props.multiple && isArray) {
3091 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
3092 }
3093 }
3094}
3095
3096function updateOptions(node, multiple, propValue, setDefaultSelected) {
3097 var options = node.options;
3098
3099 if (multiple) {
3100 var selectedValues = propValue;
3101 var selectedValue = {};
3102
3103 for (var i = 0; i < selectedValues.length; i++) {
3104 // Prefix to avoid chaos with special keys.
3105 selectedValue['$' + selectedValues[i]] = true;
3106 }
3107
3108 for (var _i = 0; _i < options.length; _i++) {
3109 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
3110
3111 if (options[_i].selected !== selected) {
3112 options[_i].selected = selected;
3113 }
3114
3115 if (selected && setDefaultSelected) {
3116 options[_i].defaultSelected = true;
3117 }
3118 }
3119 } else {
3120 // Do not set `select.value` as exact behavior isn't consistent across all
3121 // browsers for all cases.
3122 var _selectedValue = toString(getToStringValue(propValue));
3123
3124 var defaultSelected = null;
3125
3126 for (var _i2 = 0; _i2 < options.length; _i2++) {
3127 if (options[_i2].value === _selectedValue) {
3128 options[_i2].selected = true;
3129
3130 if (setDefaultSelected) {
3131 options[_i2].defaultSelected = true;
3132 }
3133
3134 return;
3135 }
3136
3137 if (defaultSelected === null && !options[_i2].disabled) {
3138 defaultSelected = options[_i2];
3139 }
3140 }
3141
3142 if (defaultSelected !== null) {
3143 defaultSelected.selected = true;
3144 }
3145 }
3146}
3147/**
3148 * Implements a <select> host component that allows optionally setting the
3149 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
3150 * stringable. If `multiple` is true, the prop must be an array of stringables.
3151 *
3152 * If `value` is not supplied (or null/undefined), user actions that change the
3153 * selected option will trigger updates to the rendered options.
3154 *
3155 * If it is supplied (and not null/undefined), the rendered options will not
3156 * update in response to user actions. Instead, the `value` prop must change in
3157 * order for the rendered options to update.
3158 *
3159 * If `defaultValue` is provided, any options with the supplied values will be
3160 * selected.
3161 */
3162
3163
3164function getHostProps$2(element, props) {
3165 return _assign({}, props, {
3166 value: undefined
3167 });
3168}
3169function initWrapperState$1(element, props) {
3170 var node = element;
3171
3172 {
3173 checkSelectPropTypes(props);
3174 }
3175
3176 node._wrapperState = {
3177 wasMultiple: !!props.multiple
3178 };
3179
3180 {
3181 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
3182 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');
3183 didWarnValueDefaultValue$1 = true;
3184 }
3185 }
3186}
3187function postMountWrapper$2(element, props) {
3188 var node = element;
3189 node.multiple = !!props.multiple;
3190 var value = props.value;
3191
3192 if (value != null) {
3193 updateOptions(node, !!props.multiple, value, false);
3194 } else if (props.defaultValue != null) {
3195 updateOptions(node, !!props.multiple, props.defaultValue, true);
3196 }
3197}
3198function postUpdateWrapper(element, props) {
3199 var node = element;
3200 var wasMultiple = node._wrapperState.wasMultiple;
3201 node._wrapperState.wasMultiple = !!props.multiple;
3202 var value = props.value;
3203
3204 if (value != null) {
3205 updateOptions(node, !!props.multiple, value, false);
3206 } else if (wasMultiple !== !!props.multiple) {
3207 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
3208 if (props.defaultValue != null) {
3209 updateOptions(node, !!props.multiple, props.defaultValue, true);
3210 } else {
3211 // Revert the select back to its default unselected state.
3212 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
3213 }
3214 }
3215}
3216function restoreControlledState$2(element, props) {
3217 var node = element;
3218 var value = props.value;
3219
3220 if (value != null) {
3221 updateOptions(node, !!props.multiple, value, false);
3222 }
3223}
3224
3225var didWarnValDefaultVal = false;
3226
3227/**
3228 * Implements a <textarea> host component that allows setting `value`, and
3229 * `defaultValue`. This differs from the traditional DOM API because value is
3230 * usually set as PCDATA children.
3231 *
3232 * If `value` is not supplied (or null/undefined), user actions that affect the
3233 * value will trigger updates to the element.
3234 *
3235 * If `value` is supplied (and not null/undefined), the rendered element will
3236 * not trigger updates to the element. Instead, the `value` prop must change in
3237 * order for the rendered element to be updated.
3238 *
3239 * The rendered element will be initialized with an empty value, the prop
3240 * `defaultValue` if specified, or the children content (deprecated).
3241 */
3242function getHostProps$3(element, props) {
3243 var node = element;
3244
3245 if (!(props.dangerouslySetInnerHTML == null)) {
3246 {
3247 throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
3248 }
3249 } // Always set children to the same thing. In IE9, the selection range will
3250 // get reset if `textContent` is mutated. We could add a check in setTextContent
3251 // to only set the value if/when the value differs from the node value (which would
3252 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
3253 // solution. The value can be a boolean or object so that's why it's forced
3254 // to be a string.
3255
3256
3257 var hostProps = _assign({}, props, {
3258 value: undefined,
3259 defaultValue: undefined,
3260 children: toString(node._wrapperState.initialValue)
3261 });
3262
3263 return hostProps;
3264}
3265function initWrapperState$2(element, props) {
3266 var node = element;
3267
3268 {
3269 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
3270
3271 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
3272 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');
3273 didWarnValDefaultVal = true;
3274 }
3275 }
3276
3277 var initialValue = props.value; // Only bother fetching default value if we're going to use it
3278
3279 if (initialValue == null) {
3280 var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>.
3281
3282 var children = props.children;
3283
3284 if (children != null) {
3285 {
3286 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
3287 }
3288
3289 if (!(defaultValue == null)) {
3290 {
3291 throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
3292 }
3293 }
3294
3295 if (Array.isArray(children)) {
3296 if (!(children.length <= 1)) {
3297 {
3298 throw Error("<textarea> can only have at most one child.");
3299 }
3300 }
3301
3302 children = children[0];
3303 }
3304
3305 defaultValue = children;
3306 }
3307
3308 if (defaultValue == null) {
3309 defaultValue = '';
3310 }
3311
3312 initialValue = defaultValue;
3313 }
3314
3315 node._wrapperState = {
3316 initialValue: getToStringValue(initialValue)
3317 };
3318}
3319function updateWrapper$1(element, props) {
3320 var node = element;
3321 var value = getToStringValue(props.value);
3322 var defaultValue = getToStringValue(props.defaultValue);
3323
3324 if (value != null) {
3325 // Cast `value` to a string to ensure the value is set correctly. While
3326 // browsers typically do this as necessary, jsdom doesn't.
3327 var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
3328
3329 if (newValue !== node.value) {
3330 node.value = newValue;
3331 }
3332
3333 if (props.defaultValue == null && node.defaultValue !== newValue) {
3334 node.defaultValue = newValue;
3335 }
3336 }
3337
3338 if (defaultValue != null) {
3339 node.defaultValue = toString(defaultValue);
3340 }
3341}
3342function postMountWrapper$3(element, props) {
3343 var node = element; // This is in postMount because we need access to the DOM node, which is not
3344 // available until after the component has mounted.
3345
3346 var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
3347 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
3348 // will populate textContent as well.
3349 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
3350
3351 if (textContent === node._wrapperState.initialValue) {
3352 if (textContent !== '' && textContent !== null) {
3353 node.value = textContent;
3354 }
3355 }
3356}
3357function restoreControlledState$3(element, props) {
3358 // DOM component is still mounted; update
3359 updateWrapper$1(element, props);
3360}
3361
3362var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
3363var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3364var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
3365var Namespaces = {
3366 html: HTML_NAMESPACE$1,
3367 mathml: MATH_NAMESPACE,
3368 svg: SVG_NAMESPACE
3369}; // Assumes there is no parent namespace.
3370
3371function getIntrinsicNamespace(type) {
3372 switch (type) {
3373 case 'svg':
3374 return SVG_NAMESPACE;
3375
3376 case 'math':
3377 return MATH_NAMESPACE;
3378
3379 default:
3380 return HTML_NAMESPACE$1;
3381 }
3382}
3383function getChildNamespace(parentNamespace, type) {
3384 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
3385 // No (or default) parent namespace: potential entry point.
3386 return getIntrinsicNamespace(type);
3387 }
3388
3389 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
3390 // We're leaving SVG.
3391 return HTML_NAMESPACE$1;
3392 } // By default, pass namespace below.
3393
3394
3395 return parentNamespace;
3396}
3397
3398/* globals MSApp */
3399
3400/**
3401 * Create a function which has 'unsafe' privileges (required by windows8 apps)
3402 */
3403var createMicrosoftUnsafeLocalFunction = function (func) {
3404 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
3405 return function (arg0, arg1, arg2, arg3) {
3406 MSApp.execUnsafeLocalFunction(function () {
3407 return func(arg0, arg1, arg2, arg3);
3408 });
3409 };
3410 } else {
3411 return func;
3412 }
3413};
3414
3415var reusableSVGContainer;
3416/**
3417 * Set the innerHTML property of a node
3418 *
3419 * @param {DOMElement} node
3420 * @param {string} html
3421 * @internal
3422 */
3423
3424var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
3425 if (node.namespaceURI === Namespaces.svg) {
3426 {
3427 if (enableTrustedTypesIntegration) {
3428 // TODO: reconsider the text of this warning and when it should show
3429 // before enabling the feature flag.
3430 !(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;
3431 }
3432 }
3433
3434 if (!('innerHTML' in node)) {
3435 // IE does not have innerHTML for SVG nodes, so instead we inject the
3436 // new markup in a temp node and then move the child nodes across into
3437 // the target node
3438 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
3439 reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
3440 var svgNode = reusableSVGContainer.firstChild;
3441
3442 while (node.firstChild) {
3443 node.removeChild(node.firstChild);
3444 }
3445
3446 while (svgNode.firstChild) {
3447 node.appendChild(svgNode.firstChild);
3448 }
3449
3450 return;
3451 }
3452 }
3453
3454 node.innerHTML = html;
3455});
3456
3457/**
3458 * HTML nodeType values that represent the type of the node
3459 */
3460var ELEMENT_NODE = 1;
3461var TEXT_NODE = 3;
3462var COMMENT_NODE = 8;
3463var DOCUMENT_NODE = 9;
3464var DOCUMENT_FRAGMENT_NODE = 11;
3465
3466/**
3467 * Set the textContent property of a node. For text updates, it's faster
3468 * to set the `nodeValue` of the Text node directly instead of using
3469 * `.textContent` which will remove the existing node and create a new one.
3470 *
3471 * @param {DOMElement} node
3472 * @param {string} text
3473 * @internal
3474 */
3475
3476var setTextContent = function (node, text) {
3477 if (text) {
3478 var firstChild = node.firstChild;
3479
3480 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
3481 firstChild.nodeValue = text;
3482 return;
3483 }
3484 }
3485
3486 node.textContent = text;
3487};
3488
3489// Do not use the below two methods directly!
3490// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
3491// (It is the only module that is allowed to access these methods.)
3492function unsafeCastStringToDOMTopLevelType(topLevelType) {
3493 return topLevelType;
3494}
3495function unsafeCastDOMTopLevelTypeToString(topLevelType) {
3496 return topLevelType;
3497}
3498
3499/**
3500 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
3501 *
3502 * @param {string} styleProp
3503 * @param {string} eventName
3504 * @returns {object}
3505 */
3506
3507function makePrefixMap(styleProp, eventName) {
3508 var prefixes = {};
3509 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
3510 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
3511 prefixes['Moz' + styleProp] = 'moz' + eventName;
3512 return prefixes;
3513}
3514/**
3515 * A list of event names to a configurable list of vendor prefixes.
3516 */
3517
3518
3519var vendorPrefixes = {
3520 animationend: makePrefixMap('Animation', 'AnimationEnd'),
3521 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
3522 animationstart: makePrefixMap('Animation', 'AnimationStart'),
3523 transitionend: makePrefixMap('Transition', 'TransitionEnd')
3524};
3525/**
3526 * Event names that have already been detected and prefixed (if applicable).
3527 */
3528
3529var prefixedEventNames = {};
3530/**
3531 * Element to check for prefixes on.
3532 */
3533
3534var style = {};
3535/**
3536 * Bootstrap if a DOM exists.
3537 */
3538
3539if (canUseDOM) {
3540 style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
3541 // the un-prefixed "animation" and "transition" properties are defined on the
3542 // style object but the events that fire will still be prefixed, so we need
3543 // to check if the un-prefixed events are usable, and if not remove them from the map.
3544
3545 if (!('AnimationEvent' in window)) {
3546 delete vendorPrefixes.animationend.animation;
3547 delete vendorPrefixes.animationiteration.animation;
3548 delete vendorPrefixes.animationstart.animation;
3549 } // Same as above
3550
3551
3552 if (!('TransitionEvent' in window)) {
3553 delete vendorPrefixes.transitionend.transition;
3554 }
3555}
3556/**
3557 * Attempts to determine the correct vendor prefixed event name.
3558 *
3559 * @param {string} eventName
3560 * @returns {string}
3561 */
3562
3563
3564function getVendorPrefixedEventName(eventName) {
3565 if (prefixedEventNames[eventName]) {
3566 return prefixedEventNames[eventName];
3567 } else if (!vendorPrefixes[eventName]) {
3568 return eventName;
3569 }
3570
3571 var prefixMap = vendorPrefixes[eventName];
3572
3573 for (var styleProp in prefixMap) {
3574 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
3575 return prefixedEventNames[eventName] = prefixMap[styleProp];
3576 }
3577 }
3578
3579 return eventName;
3580}
3581
3582/**
3583 * To identify top level events in ReactDOM, we use constants defined by this
3584 * module. This is the only module that uses the unsafe* methods to express
3585 * that the constants actually correspond to the browser event names. This lets
3586 * us save some bundle size by avoiding a top level type -> event name map.
3587 * The rest of ReactDOM code should import top level types from this file.
3588 */
3589
3590var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
3591var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
3592var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
3593var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
3594var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
3595var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
3596var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
3597var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
3598var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
3599var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
3600var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
3601var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
3602var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
3603var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
3604var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
3605var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
3606var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
3607var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
3608var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
3609var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
3610var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
3611var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
3612var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
3613var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
3614var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
3615var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
3616var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
3617var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
3618var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
3619var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
3620var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
3621var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
3622var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
3623var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
3624var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
3625var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
3626var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
3627var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
3628var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
3629var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
3630var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
3631var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
3632var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
3633var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
3634var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
3635var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
3636var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
3637var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
3638var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
3639var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
3640var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
3641var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
3642var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
3643var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
3644var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
3645
3646
3647var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
3648var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
3649var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
3650var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
3651var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
3652var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
3653var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
3654var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
3655var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
3656var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
3657var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
3658var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
3659var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
3660var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
3661var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
3662var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
3663var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
3664var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
3665var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
3666var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
3667var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
3668var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
3669var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
3670var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
3671var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
3672// Note that events in this list will *not* be listened to at the top level
3673// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
3674
3675var 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];
3676function getRawEventName(topLevelType) {
3677 return unsafeCastDOMTopLevelTypeToString(topLevelType);
3678}
3679
3680/**
3681 * `ReactInstanceMap` maintains a mapping from a public facing stateful
3682 * instance (key) and the internal representation (value). This allows public
3683 * methods to accept the user facing instance as an argument and map them back
3684 * to internal methods.
3685 *
3686 * Note that this module is currently shared and assumed to be stateless.
3687 * If this becomes an actual Map, that will break.
3688 */
3689
3690/**
3691 * This API should be called `delete` but we'd have to make sure to always
3692 * transform these to strings for IE support. When this transform is fully
3693 * supported we can rename it.
3694 */
3695
3696function get(key) {
3697 return key._reactInternalFiber;
3698}
3699function has(key) {
3700 return key._reactInternalFiber !== undefined;
3701}
3702function set(key, value) {
3703 key._reactInternalFiber = value;
3704}
3705
3706// Don't change these two values. They're used by React Dev Tools.
3707var NoEffect =
3708/* */
37090;
3710var PerformedWork =
3711/* */
37121; // You can change the rest (and add more).
3713
3714var Placement =
3715/* */
37162;
3717var Update =
3718/* */
37194;
3720var PlacementAndUpdate =
3721/* */
37226;
3723var Deletion =
3724/* */
37258;
3726var ContentReset =
3727/* */
372816;
3729var Callback =
3730/* */
373132;
3732var DidCapture =
3733/* */
373464;
3735var Ref =
3736/* */
3737128;
3738var Snapshot =
3739/* */
3740256;
3741var Passive =
3742/* */
3743512;
3744var Hydrating =
3745/* */
37461024;
3747var HydratingAndUpdate =
3748/* */
37491028; // Passive & Update & Callback & Ref & Snapshot
3750
3751var LifecycleEffectMask =
3752/* */
3753932; // Union of all host effects
3754
3755var HostEffectMask =
3756/* */
37572047;
3758var Incomplete =
3759/* */
37602048;
3761var ShouldCapture =
3762/* */
37634096;
3764
3765var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
3766function getNearestMountedFiber(fiber) {
3767 var node = fiber;
3768 var nearestMounted = fiber;
3769
3770 if (!fiber.alternate) {
3771 // If there is no alternate, this might be a new tree that isn't inserted
3772 // yet. If it is, then it will have a pending insertion effect on it.
3773 var nextNode = node;
3774
3775 do {
3776 node = nextNode;
3777
3778 if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
3779 // This is an insertion or in-progress hydration. The nearest possible
3780 // mounted fiber is the parent but we need to continue to figure out
3781 // if that one is still mounted.
3782 nearestMounted = node.return;
3783 }
3784
3785 nextNode = node.return;
3786 } while (nextNode);
3787 } else {
3788 while (node.return) {
3789 node = node.return;
3790 }
3791 }
3792
3793 if (node.tag === HostRoot) {
3794 // TODO: Check if this was a nested HostRoot when used with
3795 // renderContainerIntoSubtree.
3796 return nearestMounted;
3797 } // If we didn't hit the root, that means that we're in an disconnected tree
3798 // that has been unmounted.
3799
3800
3801 return null;
3802}
3803function getSuspenseInstanceFromFiber(fiber) {
3804 if (fiber.tag === SuspenseComponent) {
3805 var suspenseState = fiber.memoizedState;
3806
3807 if (suspenseState === null) {
3808 var current = fiber.alternate;
3809
3810 if (current !== null) {
3811 suspenseState = current.memoizedState;
3812 }
3813 }
3814
3815 if (suspenseState !== null) {
3816 return suspenseState.dehydrated;
3817 }
3818 }
3819
3820 return null;
3821}
3822function getContainerFromFiber(fiber) {
3823 return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
3824}
3825function isFiberMounted(fiber) {
3826 return getNearestMountedFiber(fiber) === fiber;
3827}
3828function isMounted(component) {
3829 {
3830 var owner = ReactCurrentOwner.current;
3831
3832 if (owner !== null && owner.tag === ClassComponent) {
3833 var ownerFiber = owner;
3834 var instance = ownerFiber.stateNode;
3835 !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;
3836 instance._warnedAboutRefsInRender = true;
3837 }
3838 }
3839
3840 var fiber = get(component);
3841
3842 if (!fiber) {
3843 return false;
3844 }
3845
3846 return getNearestMountedFiber(fiber) === fiber;
3847}
3848
3849function assertIsMounted(fiber) {
3850 if (!(getNearestMountedFiber(fiber) === fiber)) {
3851 {
3852 throw Error("Unable to find node on an unmounted component.");
3853 }
3854 }
3855}
3856
3857function findCurrentFiberUsingSlowPath(fiber) {
3858 var alternate = fiber.alternate;
3859
3860 if (!alternate) {
3861 // If there is no alternate, then we only need to check if it is mounted.
3862 var nearestMounted = getNearestMountedFiber(fiber);
3863
3864 if (!(nearestMounted !== null)) {
3865 {
3866 throw Error("Unable to find node on an unmounted component.");
3867 }
3868 }
3869
3870 if (nearestMounted !== fiber) {
3871 return null;
3872 }
3873
3874 return fiber;
3875 } // If we have two possible branches, we'll walk backwards up to the root
3876 // to see what path the root points to. On the way we may hit one of the
3877 // special cases and we'll deal with them.
3878
3879
3880 var a = fiber;
3881 var b = alternate;
3882
3883 while (true) {
3884 var parentA = a.return;
3885
3886 if (parentA === null) {
3887 // We're at the root.
3888 break;
3889 }
3890
3891 var parentB = parentA.alternate;
3892
3893 if (parentB === null) {
3894 // There is no alternate. This is an unusual case. Currently, it only
3895 // happens when a Suspense component is hidden. An extra fragment fiber
3896 // is inserted in between the Suspense fiber and its children. Skip
3897 // over this extra fragment fiber and proceed to the next parent.
3898 var nextParent = parentA.return;
3899
3900 if (nextParent !== null) {
3901 a = b = nextParent;
3902 continue;
3903 } // If there's no parent, we're at the root.
3904
3905
3906 break;
3907 } // If both copies of the parent fiber point to the same child, we can
3908 // assume that the child is current. This happens when we bailout on low
3909 // priority: the bailed out fiber's child reuses the current child.
3910
3911
3912 if (parentA.child === parentB.child) {
3913 var child = parentA.child;
3914
3915 while (child) {
3916 if (child === a) {
3917 // We've determined that A is the current branch.
3918 assertIsMounted(parentA);
3919 return fiber;
3920 }
3921
3922 if (child === b) {
3923 // We've determined that B is the current branch.
3924 assertIsMounted(parentA);
3925 return alternate;
3926 }
3927
3928 child = child.sibling;
3929 } // We should never have an alternate for any mounting node. So the only
3930 // way this could possibly happen is if this was unmounted, if at all.
3931
3932
3933 {
3934 {
3935 throw Error("Unable to find node on an unmounted component.");
3936 }
3937 }
3938 }
3939
3940 if (a.return !== b.return) {
3941 // The return pointer of A and the return pointer of B point to different
3942 // fibers. We assume that return pointers never criss-cross, so A must
3943 // belong to the child set of A.return, and B must belong to the child
3944 // set of B.return.
3945 a = parentA;
3946 b = parentB;
3947 } else {
3948 // The return pointers point to the same fiber. We'll have to use the
3949 // default, slow path: scan the child sets of each parent alternate to see
3950 // which child belongs to which set.
3951 //
3952 // Search parent A's child set
3953 var didFindChild = false;
3954 var _child = parentA.child;
3955
3956 while (_child) {
3957 if (_child === a) {
3958 didFindChild = true;
3959 a = parentA;
3960 b = parentB;
3961 break;
3962 }
3963
3964 if (_child === b) {
3965 didFindChild = true;
3966 b = parentA;
3967 a = parentB;
3968 break;
3969 }
3970
3971 _child = _child.sibling;
3972 }
3973
3974 if (!didFindChild) {
3975 // Search parent B's child set
3976 _child = parentB.child;
3977
3978 while (_child) {
3979 if (_child === a) {
3980 didFindChild = true;
3981 a = parentB;
3982 b = parentA;
3983 break;
3984 }
3985
3986 if (_child === b) {
3987 didFindChild = true;
3988 b = parentB;
3989 a = parentA;
3990 break;
3991 }
3992
3993 _child = _child.sibling;
3994 }
3995
3996 if (!didFindChild) {
3997 {
3998 throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
3999 }
4000 }
4001 }
4002 }
4003
4004 if (!(a.alternate === b)) {
4005 {
4006 throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
4007 }
4008 }
4009 } // If the root is not a host container, we're in a disconnected tree. I.e.
4010 // unmounted.
4011
4012
4013 if (!(a.tag === HostRoot)) {
4014 {
4015 throw Error("Unable to find node on an unmounted component.");
4016 }
4017 }
4018
4019 if (a.stateNode.current === a) {
4020 // We've determined that A is the current branch.
4021 return fiber;
4022 } // Otherwise B has to be current branch.
4023
4024
4025 return alternate;
4026}
4027function findCurrentHostFiber(parent) {
4028 var currentParent = findCurrentFiberUsingSlowPath(parent);
4029
4030 if (!currentParent) {
4031 return null;
4032 } // Next we'll drill down this component to find the first HostComponent/Text.
4033
4034
4035 var node = currentParent;
4036
4037 while (true) {
4038 if (node.tag === HostComponent || node.tag === HostText) {
4039 return node;
4040 } else if (node.child) {
4041 node.child.return = node;
4042 node = node.child;
4043 continue;
4044 }
4045
4046 if (node === currentParent) {
4047 return null;
4048 }
4049
4050 while (!node.sibling) {
4051 if (!node.return || node.return === currentParent) {
4052 return null;
4053 }
4054
4055 node = node.return;
4056 }
4057
4058 node.sibling.return = node.return;
4059 node = node.sibling;
4060 } // Flow needs the return null here, but ESLint complains about it.
4061 // eslint-disable-next-line no-unreachable
4062
4063
4064 return null;
4065}
4066function findCurrentHostFiberWithNoPortals(parent) {
4067 var currentParent = findCurrentFiberUsingSlowPath(parent);
4068
4069 if (!currentParent) {
4070 return null;
4071 } // Next we'll drill down this component to find the first HostComponent/Text.
4072
4073
4074 var node = currentParent;
4075
4076 while (true) {
4077 if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI && node.tag === FundamentalComponent) {
4078 return node;
4079 } else if (node.child && node.tag !== HostPortal) {
4080 node.child.return = node;
4081 node = node.child;
4082 continue;
4083 }
4084
4085 if (node === currentParent) {
4086 return null;
4087 }
4088
4089 while (!node.sibling) {
4090 if (!node.return || node.return === currentParent) {
4091 return null;
4092 }
4093
4094 node = node.return;
4095 }
4096
4097 node.sibling.return = node.return;
4098 node = node.sibling;
4099 } // Flow needs the return null here, but ESLint complains about it.
4100 // eslint-disable-next-line no-unreachable
4101
4102
4103 return null;
4104}
4105
4106var attemptSynchronousHydration;
4107function setAttemptSynchronousHydration(fn) {
4108 attemptSynchronousHydration = fn;
4109}
4110var attemptUserBlockingHydration;
4111function setAttemptUserBlockingHydration(fn) {
4112 attemptUserBlockingHydration = fn;
4113}
4114var attemptContinuousHydration;
4115function setAttemptContinuousHydration(fn) {
4116 attemptContinuousHydration = fn;
4117}
4118var attemptHydrationAtCurrentPriority;
4119function setAttemptHydrationAtCurrentPriority(fn) {
4120 attemptHydrationAtCurrentPriority = fn;
4121} // TODO: Upgrade this definition once we're on a newer version of Flow that
4122// has this definition built-in.
4123
4124var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
4125
4126var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
4127
4128// if the last target was dehydrated.
4129
4130var queuedFocus = null;
4131var queuedDrag = null;
4132var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
4133
4134var queuedPointers = new Map();
4135var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
4136
4137var queuedExplicitHydrationTargets = [];
4138function hasQueuedDiscreteEvents() {
4139 return queuedDiscreteEvents.length > 0;
4140}
4141
4142var 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];
4143var 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];
4144function isReplayableDiscreteEvent(eventType) {
4145 return discreteReplayableEvents.indexOf(eventType) > -1;
4146}
4147
4148function trapReplayableEvent(topLevelType, document, listeningSet) {
4149 listenToTopLevel(topLevelType, document, listeningSet);
4150
4151 if (enableFlareAPI) {
4152 // Trap events for the responder system.
4153 var passiveEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_passive';
4154
4155 if (!listeningSet.has(passiveEventKey)) {
4156 trapEventForResponderEventSystem(document, topLevelType, true);
4157 listeningSet.add(passiveEventKey);
4158 } // TODO: This listens to all events as active which might have
4159 // undesirable effects. It's also unnecessary to have both
4160 // passive and active listeners. Instead, we could start with
4161 // a passive and upgrade it to an active one if needed.
4162 // For replaying purposes the active is never needed since we
4163 // currently don't preventDefault.
4164
4165
4166 var activeEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_active';
4167
4168 if (!listeningSet.has(activeEventKey)) {
4169 trapEventForResponderEventSystem(document, topLevelType, false);
4170 listeningSet.add(activeEventKey);
4171 }
4172 }
4173}
4174
4175function eagerlyTrapReplayableEvents(document) {
4176 var listeningSet = getListeningSetForElement(document); // Discrete
4177
4178 discreteReplayableEvents.forEach(function (topLevelType) {
4179 trapReplayableEvent(topLevelType, document, listeningSet);
4180 }); // Continuous
4181
4182 continuousReplayableEvents.forEach(function (topLevelType) {
4183 trapReplayableEvent(topLevelType, document, listeningSet);
4184 });
4185}
4186
4187function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4188 return {
4189 blockedOn: blockedOn,
4190 topLevelType: topLevelType,
4191 eventSystemFlags: eventSystemFlags | IS_REPLAYED,
4192 nativeEvent: nativeEvent
4193 };
4194}
4195
4196function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4197 var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4198 queuedDiscreteEvents.push(queuedEvent);
4199
4200 if (enableSelectiveHydration) {
4201 if (queuedDiscreteEvents.length === 1) {
4202 // If this was the first discrete event, we might be able to
4203 // synchronously unblock it so that preventDefault still works.
4204 while (queuedEvent.blockedOn !== null) {
4205 var _fiber = getInstanceFromNode$1(queuedEvent.blockedOn);
4206
4207 if (_fiber === null) {
4208 break;
4209 }
4210
4211 attemptSynchronousHydration(_fiber);
4212
4213 if (queuedEvent.blockedOn === null) {
4214 // We got unblocked by hydration. Let's try again.
4215 replayUnblockedEvents(); // If we're reblocked, on an inner boundary, we might need
4216 // to attempt hydrating that one.
4217
4218 continue;
4219 } else {
4220 // We're still blocked from hydation, we have to give up
4221 // and replay later.
4222 break;
4223 }
4224 }
4225 }
4226 }
4227} // Resets the replaying for this type of continuous event to no event.
4228
4229function clearIfContinuousEvent(topLevelType, nativeEvent) {
4230 switch (topLevelType) {
4231 case TOP_FOCUS:
4232 case TOP_BLUR:
4233 queuedFocus = null;
4234 break;
4235
4236 case TOP_DRAG_ENTER:
4237 case TOP_DRAG_LEAVE:
4238 queuedDrag = null;
4239 break;
4240
4241 case TOP_MOUSE_OVER:
4242 case TOP_MOUSE_OUT:
4243 queuedMouse = null;
4244 break;
4245
4246 case TOP_POINTER_OVER:
4247 case TOP_POINTER_OUT:
4248 {
4249 var pointerId = nativeEvent.pointerId;
4250 queuedPointers.delete(pointerId);
4251 break;
4252 }
4253
4254 case TOP_GOT_POINTER_CAPTURE:
4255 case TOP_LOST_POINTER_CAPTURE:
4256 {
4257 var _pointerId = nativeEvent.pointerId;
4258 queuedPointerCaptures.delete(_pointerId);
4259 break;
4260 }
4261 }
4262}
4263
4264function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4265 if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
4266 var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4267
4268 if (blockedOn !== null) {
4269 var _fiber2 = getInstanceFromNode$1(blockedOn);
4270
4271 if (_fiber2 !== null) {
4272 // Attempt to increase the priority of this target.
4273 attemptContinuousHydration(_fiber2);
4274 }
4275 }
4276
4277 return queuedEvent;
4278 } // If we have already queued this exact event, then it's because
4279 // the different event systems have different DOM event listeners.
4280 // We can accumulate the flags and store a single event to be
4281 // replayed.
4282
4283
4284 existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
4285 return existingQueuedEvent;
4286}
4287
4288function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4289 // These set relatedTarget to null because the replayed event will be treated as if we
4290 // moved from outside the window (no target) onto the target once it hydrates.
4291 // Instead of mutating we could clone the event.
4292 switch (topLevelType) {
4293 case TOP_FOCUS:
4294 {
4295 var focusEvent = nativeEvent;
4296 queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, focusEvent);
4297 return true;
4298 }
4299
4300 case TOP_DRAG_ENTER:
4301 {
4302 var dragEvent = nativeEvent;
4303 queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, dragEvent);
4304 return true;
4305 }
4306
4307 case TOP_MOUSE_OVER:
4308 {
4309 var mouseEvent = nativeEvent;
4310 queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, mouseEvent);
4311 return true;
4312 }
4313
4314 case TOP_POINTER_OVER:
4315 {
4316 var pointerEvent = nativeEvent;
4317 var pointerId = pointerEvent.pointerId;
4318 queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, pointerEvent));
4319 return true;
4320 }
4321
4322 case TOP_GOT_POINTER_CAPTURE:
4323 {
4324 var _pointerEvent = nativeEvent;
4325 var _pointerId2 = _pointerEvent.pointerId;
4326 queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, _pointerEvent));
4327 return true;
4328 }
4329 }
4330
4331 return false;
4332} // Check if this target is unblocked. Returns true if it's unblocked.
4333
4334function attemptExplicitHydrationTarget(queuedTarget) {
4335 // TODO: This function shares a lot of logic with attemptToDispatchEvent.
4336 // Try to unify them. It's a bit tricky since it would require two return
4337 // values.
4338 var targetInst = getClosestInstanceFromNode(queuedTarget.target);
4339
4340 if (targetInst !== null) {
4341 var nearestMounted = getNearestMountedFiber(targetInst);
4342
4343 if (nearestMounted !== null) {
4344 var tag = nearestMounted.tag;
4345
4346 if (tag === SuspenseComponent) {
4347 var instance = getSuspenseInstanceFromFiber(nearestMounted);
4348
4349 if (instance !== null) {
4350 // We're blocked on hydrating this boundary.
4351 // Increase its priority.
4352 queuedTarget.blockedOn = instance;
4353 Scheduler.unstable_runWithPriority(queuedTarget.priority, function () {
4354 attemptHydrationAtCurrentPriority(nearestMounted);
4355 });
4356 return;
4357 }
4358 } else if (tag === HostRoot) {
4359 var root = nearestMounted.stateNode;
4360
4361 if (root.hydrate) {
4362 queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
4363 // a root other than sync.
4364
4365 return;
4366 }
4367 }
4368 }
4369 }
4370
4371 queuedTarget.blockedOn = null;
4372}
4373
4374function queueExplicitHydrationTarget(target) {
4375 if (enableSelectiveHydration) {
4376 var priority = Scheduler.unstable_getCurrentPriorityLevel();
4377 var queuedTarget = {
4378 blockedOn: null,
4379 target: target,
4380 priority: priority
4381 };
4382 var i = 0;
4383
4384 for (; i < queuedExplicitHydrationTargets.length; i++) {
4385 if (priority <= queuedExplicitHydrationTargets[i].priority) {
4386 break;
4387 }
4388 }
4389
4390 queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
4391
4392 if (i === 0) {
4393 attemptExplicitHydrationTarget(queuedTarget);
4394 }
4395 }
4396}
4397
4398function attemptReplayContinuousQueuedEvent(queuedEvent) {
4399 if (queuedEvent.blockedOn !== null) {
4400 return false;
4401 }
4402
4403 var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.nativeEvent);
4404
4405 if (nextBlockedOn !== null) {
4406 // We're still blocked. Try again later.
4407 var _fiber3 = getInstanceFromNode$1(nextBlockedOn);
4408
4409 if (_fiber3 !== null) {
4410 attemptContinuousHydration(_fiber3);
4411 }
4412
4413 queuedEvent.blockedOn = nextBlockedOn;
4414 return false;
4415 }
4416
4417 return true;
4418}
4419
4420function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
4421 if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
4422 map.delete(key);
4423 }
4424}
4425
4426function replayUnblockedEvents() {
4427 hasScheduledReplayAttempt = false; // First replay discrete events.
4428
4429 while (queuedDiscreteEvents.length > 0) {
4430 var nextDiscreteEvent = queuedDiscreteEvents[0];
4431
4432 if (nextDiscreteEvent.blockedOn !== null) {
4433 // We're still blocked.
4434 // Increase the priority of this boundary to unblock
4435 // the next discrete event.
4436 var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);
4437
4438 if (_fiber4 !== null) {
4439 attemptUserBlockingHydration(_fiber4);
4440 }
4441
4442 break;
4443 }
4444
4445 var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.nativeEvent);
4446
4447 if (nextBlockedOn !== null) {
4448 // We're still blocked. Try again later.
4449 nextDiscreteEvent.blockedOn = nextBlockedOn;
4450 } else {
4451 // We've successfully replayed the first event. Let's try the next one.
4452 queuedDiscreteEvents.shift();
4453 }
4454 } // Next replay any continuous events.
4455
4456
4457 if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
4458 queuedFocus = null;
4459 }
4460
4461 if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
4462 queuedDrag = null;
4463 }
4464
4465 if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
4466 queuedMouse = null;
4467 }
4468
4469 queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
4470 queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
4471}
4472
4473function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
4474 if (queuedEvent.blockedOn === unblocked) {
4475 queuedEvent.blockedOn = null;
4476
4477 if (!hasScheduledReplayAttempt) {
4478 hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
4479 // now unblocked. This first might not actually be unblocked yet.
4480 // We could check it early to avoid scheduling an unnecessary callback.
4481
4482 Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
4483 }
4484 }
4485}
4486
4487function retryIfBlockedOn(unblocked) {
4488 // Mark anything that was blocked on this as no longer blocked
4489 // and eligible for a replay.
4490 if (queuedDiscreteEvents.length > 0) {
4491 scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
4492 // worth it because we expect very few discrete events to queue up and once
4493 // we are actually fully unblocked it will be fast to replay them.
4494
4495 for (var i = 1; i < queuedDiscreteEvents.length; i++) {
4496 var queuedEvent = queuedDiscreteEvents[i];
4497
4498 if (queuedEvent.blockedOn === unblocked) {
4499 queuedEvent.blockedOn = null;
4500 }
4501 }
4502 }
4503
4504 if (queuedFocus !== null) {
4505 scheduleCallbackIfUnblocked(queuedFocus, unblocked);
4506 }
4507
4508 if (queuedDrag !== null) {
4509 scheduleCallbackIfUnblocked(queuedDrag, unblocked);
4510 }
4511
4512 if (queuedMouse !== null) {
4513 scheduleCallbackIfUnblocked(queuedMouse, unblocked);
4514 }
4515
4516 var unblock = function (queuedEvent) {
4517 return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
4518 };
4519
4520 queuedPointers.forEach(unblock);
4521 queuedPointerCaptures.forEach(unblock);
4522
4523 for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
4524 var queuedTarget = queuedExplicitHydrationTargets[_i];
4525
4526 if (queuedTarget.blockedOn === unblocked) {
4527 queuedTarget.blockedOn = null;
4528 }
4529 }
4530
4531 while (queuedExplicitHydrationTargets.length > 0) {
4532 var nextExplicitTarget = queuedExplicitHydrationTargets[0];
4533
4534 if (nextExplicitTarget.blockedOn !== null) {
4535 // We're still blocked.
4536 break;
4537 } else {
4538 attemptExplicitHydrationTarget(nextExplicitTarget);
4539
4540 if (nextExplicitTarget.blockedOn === null) {
4541 // We're unblocked.
4542 queuedExplicitHydrationTargets.shift();
4543 }
4544 }
4545 }
4546}
4547
4548function addEventBubbleListener(element, eventType, listener) {
4549 element.addEventListener(eventType, listener, false);
4550}
4551function addEventCaptureListener(element, eventType, listener) {
4552 element.addEventListener(eventType, listener, true);
4553}
4554function addEventCaptureListenerWithPassiveFlag(element, eventType, listener, passive) {
4555 element.addEventListener(eventType, listener, {
4556 capture: true,
4557 passive: passive
4558 });
4559}
4560
4561/**
4562 * Gets the target node from a native browser event by accounting for
4563 * inconsistencies in browser DOM APIs.
4564 *
4565 * @param {object} nativeEvent Native browser event.
4566 * @return {DOMEventTarget} Target node.
4567 */
4568
4569function getEventTarget(nativeEvent) {
4570 // Fallback to nativeEvent.srcElement for IE9
4571 // https://github.com/facebook/react/issues/12506
4572 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
4573
4574 if (target.correspondingUseElement) {
4575 target = target.correspondingUseElement;
4576 } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
4577 // @see http://www.quirksmode.org/js/events_properties.html
4578
4579
4580 return target.nodeType === TEXT_NODE ? target.parentNode : target;
4581}
4582
4583function getParent(inst) {
4584 do {
4585 inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
4586 // That is depending on if we want nested subtrees (layers) to bubble
4587 // events to their parent. We could also go through parentNode on the
4588 // host node but that wouldn't work for React Native and doesn't let us
4589 // do the portal feature.
4590 } while (inst && inst.tag !== HostComponent);
4591
4592 if (inst) {
4593 return inst;
4594 }
4595
4596 return null;
4597}
4598/**
4599 * Return the lowest common ancestor of A and B, or null if they are in
4600 * different trees.
4601 */
4602
4603
4604function getLowestCommonAncestor(instA, instB) {
4605 var depthA = 0;
4606
4607 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
4608 depthA++;
4609 }
4610
4611 var depthB = 0;
4612
4613 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
4614 depthB++;
4615 } // If A is deeper, crawl up.
4616
4617
4618 while (depthA - depthB > 0) {
4619 instA = getParent(instA);
4620 depthA--;
4621 } // If B is deeper, crawl up.
4622
4623
4624 while (depthB - depthA > 0) {
4625 instB = getParent(instB);
4626 depthB--;
4627 } // Walk in lockstep until we find a match.
4628
4629
4630 var depth = depthA;
4631
4632 while (depth--) {
4633 if (instA === instB || instA === instB.alternate) {
4634 return instA;
4635 }
4636
4637 instA = getParent(instA);
4638 instB = getParent(instB);
4639 }
4640
4641 return null;
4642}
4643/**
4644 * Return if A is an ancestor of B.
4645 */
4646
4647
4648/**
4649 * Return the parent instance of the passed-in instance.
4650 */
4651
4652
4653/**
4654 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
4655 */
4656
4657function traverseTwoPhase(inst, fn, arg) {
4658 var path = [];
4659
4660 while (inst) {
4661 path.push(inst);
4662 inst = getParent(inst);
4663 }
4664
4665 var i;
4666
4667 for (i = path.length; i-- > 0;) {
4668 fn(path[i], 'captured', arg);
4669 }
4670
4671 for (i = 0; i < path.length; i++) {
4672 fn(path[i], 'bubbled', arg);
4673 }
4674}
4675/**
4676 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
4677 * should would receive a `mouseEnter` or `mouseLeave` event.
4678 *
4679 * Does not invoke the callback on the nearest common ancestor because nothing
4680 * "entered" or "left" that element.
4681 */
4682
4683function traverseEnterLeave(from, to, fn, argFrom, argTo) {
4684 var common = from && to ? getLowestCommonAncestor(from, to) : null;
4685 var pathFrom = [];
4686
4687 while (true) {
4688 if (!from) {
4689 break;
4690 }
4691
4692 if (from === common) {
4693 break;
4694 }
4695
4696 var alternate = from.alternate;
4697
4698 if (alternate !== null && alternate === common) {
4699 break;
4700 }
4701
4702 pathFrom.push(from);
4703 from = getParent(from);
4704 }
4705
4706 var pathTo = [];
4707
4708 while (true) {
4709 if (!to) {
4710 break;
4711 }
4712
4713 if (to === common) {
4714 break;
4715 }
4716
4717 var _alternate = to.alternate;
4718
4719 if (_alternate !== null && _alternate === common) {
4720 break;
4721 }
4722
4723 pathTo.push(to);
4724 to = getParent(to);
4725 }
4726
4727 for (var i = 0; i < pathFrom.length; i++) {
4728 fn(pathFrom[i], 'bubbled', argFrom);
4729 }
4730
4731 for (var _i = pathTo.length; _i-- > 0;) {
4732 fn(pathTo[_i], 'captured', argTo);
4733 }
4734}
4735
4736/**
4737 * Some event types have a notion of different registration names for different
4738 * "phases" of propagation. This finds listeners by a given phase.
4739 */
4740function listenerAtPhase(inst, event, propagationPhase) {
4741 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
4742 return getListener(inst, registrationName);
4743}
4744/**
4745 * A small set of propagation patterns, each of which will accept a small amount
4746 * of information, and generate a set of "dispatch ready event objects" - which
4747 * are sets of events that have already been annotated with a set of dispatched
4748 * listener functions/ids. The API is designed this way to discourage these
4749 * propagation strategies from actually executing the dispatches, since we
4750 * always want to collect the entire set of dispatches before executing even a
4751 * single one.
4752 */
4753
4754/**
4755 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
4756 * here, allows us to not have to bind or create functions for each event.
4757 * Mutating the event's members allows us to not have to create a wrapping
4758 * "dispatch" object that pairs the event with the listener.
4759 */
4760
4761
4762function accumulateDirectionalDispatches(inst, phase, event) {
4763 {
4764 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
4765 }
4766
4767 var listener = listenerAtPhase(inst, event, phase);
4768
4769 if (listener) {
4770 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4771 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4772 }
4773}
4774/**
4775 * Collect dispatches (must be entirely collected before dispatching - see unit
4776 * tests). Lazily allocate the array to conserve memory. We must loop through
4777 * each event and perform the traversal for each one. We cannot perform a
4778 * single traversal for the entire collection of events because each event may
4779 * have a different target.
4780 */
4781
4782
4783function accumulateTwoPhaseDispatchesSingle(event) {
4784 if (event && event.dispatchConfig.phasedRegistrationNames) {
4785 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
4786 }
4787}
4788/**
4789 * Accumulates without regard to direction, does not look for phased
4790 * registration names. Same as `accumulateDirectDispatchesSingle` but without
4791 * requiring that the `dispatchMarker` be the same as the dispatched ID.
4792 */
4793
4794
4795function accumulateDispatches(inst, ignoredDirection, event) {
4796 if (inst && event && event.dispatchConfig.registrationName) {
4797 var registrationName = event.dispatchConfig.registrationName;
4798 var listener = getListener(inst, registrationName);
4799
4800 if (listener) {
4801 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4802 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4803 }
4804 }
4805}
4806/**
4807 * Accumulates dispatches on an `SyntheticEvent`, but only for the
4808 * `dispatchMarker`.
4809 * @param {SyntheticEvent} event
4810 */
4811
4812
4813function accumulateDirectDispatchesSingle(event) {
4814 if (event && event.dispatchConfig.registrationName) {
4815 accumulateDispatches(event._targetInst, null, event);
4816 }
4817}
4818
4819function accumulateTwoPhaseDispatches(events) {
4820 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
4821}
4822
4823function accumulateEnterLeaveDispatches(leave, enter, from, to) {
4824 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
4825}
4826function accumulateDirectDispatches(events) {
4827 forEachAccumulated(events, accumulateDirectDispatchesSingle);
4828}
4829
4830/* eslint valid-typeof: 0 */
4831var EVENT_POOL_SIZE = 10;
4832/**
4833 * @interface Event
4834 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4835 */
4836
4837var EventInterface = {
4838 type: null,
4839 target: null,
4840 // currentTarget is set when dispatching; no use in copying it here
4841 currentTarget: function () {
4842 return null;
4843 },
4844 eventPhase: null,
4845 bubbles: null,
4846 cancelable: null,
4847 timeStamp: function (event) {
4848 return event.timeStamp || Date.now();
4849 },
4850 defaultPrevented: null,
4851 isTrusted: null
4852};
4853
4854function functionThatReturnsTrue() {
4855 return true;
4856}
4857
4858function functionThatReturnsFalse() {
4859 return false;
4860}
4861/**
4862 * Synthetic events are dispatched by event plugins, typically in response to a
4863 * top-level event delegation handler.
4864 *
4865 * These systems should generally use pooling to reduce the frequency of garbage
4866 * collection. The system should check `isPersistent` to determine whether the
4867 * event should be released into the pool after being dispatched. Users that
4868 * need a persisted event should invoke `persist`.
4869 *
4870 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
4871 * normalizing browser quirks. Subclasses do not necessarily have to implement a
4872 * DOM interface; custom application-specific events can also subclass this.
4873 *
4874 * @param {object} dispatchConfig Configuration used to dispatch this event.
4875 * @param {*} targetInst Marker identifying the event target.
4876 * @param {object} nativeEvent Native browser event.
4877 * @param {DOMEventTarget} nativeEventTarget Target node.
4878 */
4879
4880
4881function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
4882 {
4883 // these have a getter/setter for warnings
4884 delete this.nativeEvent;
4885 delete this.preventDefault;
4886 delete this.stopPropagation;
4887 delete this.isDefaultPrevented;
4888 delete this.isPropagationStopped;
4889 }
4890
4891 this.dispatchConfig = dispatchConfig;
4892 this._targetInst = targetInst;
4893 this.nativeEvent = nativeEvent;
4894 var Interface = this.constructor.Interface;
4895
4896 for (var propName in Interface) {
4897 if (!Interface.hasOwnProperty(propName)) {
4898 continue;
4899 }
4900
4901 {
4902 delete this[propName]; // this has a getter/setter for warnings
4903 }
4904
4905 var normalize = Interface[propName];
4906
4907 if (normalize) {
4908 this[propName] = normalize(nativeEvent);
4909 } else {
4910 if (propName === 'target') {
4911 this.target = nativeEventTarget;
4912 } else {
4913 this[propName] = nativeEvent[propName];
4914 }
4915 }
4916 }
4917
4918 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
4919
4920 if (defaultPrevented) {
4921 this.isDefaultPrevented = functionThatReturnsTrue;
4922 } else {
4923 this.isDefaultPrevented = functionThatReturnsFalse;
4924 }
4925
4926 this.isPropagationStopped = functionThatReturnsFalse;
4927 return this;
4928}
4929
4930_assign(SyntheticEvent.prototype, {
4931 preventDefault: function () {
4932 this.defaultPrevented = true;
4933 var event = this.nativeEvent;
4934
4935 if (!event) {
4936 return;
4937 }
4938
4939 if (event.preventDefault) {
4940 event.preventDefault();
4941 } else if (typeof event.returnValue !== 'unknown') {
4942 event.returnValue = false;
4943 }
4944
4945 this.isDefaultPrevented = functionThatReturnsTrue;
4946 },
4947 stopPropagation: function () {
4948 var event = this.nativeEvent;
4949
4950 if (!event) {
4951 return;
4952 }
4953
4954 if (event.stopPropagation) {
4955 event.stopPropagation();
4956 } else if (typeof event.cancelBubble !== 'unknown') {
4957 // The ChangeEventPlugin registers a "propertychange" event for
4958 // IE. This event does not support bubbling or cancelling, and
4959 // any references to cancelBubble throw "Member not found". A
4960 // typeof check of "unknown" circumvents this issue (and is also
4961 // IE specific).
4962 event.cancelBubble = true;
4963 }
4964
4965 this.isPropagationStopped = functionThatReturnsTrue;
4966 },
4967
4968 /**
4969 * We release all dispatched `SyntheticEvent`s after each event loop, adding
4970 * them back into the pool. This allows a way to hold onto a reference that
4971 * won't be added back into the pool.
4972 */
4973 persist: function () {
4974 this.isPersistent = functionThatReturnsTrue;
4975 },
4976
4977 /**
4978 * Checks if this event should be released back into the pool.
4979 *
4980 * @return {boolean} True if this should not be released, false otherwise.
4981 */
4982 isPersistent: functionThatReturnsFalse,
4983
4984 /**
4985 * `PooledClass` looks for `destructor` on each instance it releases.
4986 */
4987 destructor: function () {
4988 var Interface = this.constructor.Interface;
4989
4990 for (var propName in Interface) {
4991 {
4992 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
4993 }
4994 }
4995
4996 this.dispatchConfig = null;
4997 this._targetInst = null;
4998 this.nativeEvent = null;
4999 this.isDefaultPrevented = functionThatReturnsFalse;
5000 this.isPropagationStopped = functionThatReturnsFalse;
5001 this._dispatchListeners = null;
5002 this._dispatchInstances = null;
5003
5004 {
5005 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
5006 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
5007 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
5008 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
5009 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
5010 }
5011 }
5012});
5013
5014SyntheticEvent.Interface = EventInterface;
5015/**
5016 * Helper to reduce boilerplate when creating subclasses.
5017 */
5018
5019SyntheticEvent.extend = function (Interface) {
5020 var Super = this;
5021
5022 var E = function () {};
5023
5024 E.prototype = Super.prototype;
5025 var prototype = new E();
5026
5027 function Class() {
5028 return Super.apply(this, arguments);
5029 }
5030
5031 _assign(prototype, Class.prototype);
5032
5033 Class.prototype = prototype;
5034 Class.prototype.constructor = Class;
5035 Class.Interface = _assign({}, Super.Interface, Interface);
5036 Class.extend = Super.extend;
5037 addEventPoolingTo(Class);
5038 return Class;
5039};
5040
5041addEventPoolingTo(SyntheticEvent);
5042/**
5043 * Helper to nullify syntheticEvent instance properties when destructing
5044 *
5045 * @param {String} propName
5046 * @param {?object} getVal
5047 * @return {object} defineProperty object
5048 */
5049
5050function getPooledWarningPropertyDefinition(propName, getVal) {
5051 var isFunction = typeof getVal === 'function';
5052 return {
5053 configurable: true,
5054 set: set,
5055 get: get
5056 };
5057
5058 function set(val) {
5059 var action = isFunction ? 'setting the method' : 'setting the property';
5060 warn(action, 'This is effectively a no-op');
5061 return val;
5062 }
5063
5064 function get() {
5065 var action = isFunction ? 'accessing the method' : 'accessing the property';
5066 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
5067 warn(action, result);
5068 return getVal;
5069 }
5070
5071 function warn(action, result) {
5072 var warningCondition = false;
5073 !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;
5074 }
5075}
5076
5077function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
5078 var EventConstructor = this;
5079
5080 if (EventConstructor.eventPool.length) {
5081 var instance = EventConstructor.eventPool.pop();
5082 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
5083 return instance;
5084 }
5085
5086 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
5087}
5088
5089function releasePooledEvent(event) {
5090 var EventConstructor = this;
5091
5092 if (!(event instanceof EventConstructor)) {
5093 {
5094 throw Error("Trying to release an event instance into a pool of a different type.");
5095 }
5096 }
5097
5098 event.destructor();
5099
5100 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
5101 EventConstructor.eventPool.push(event);
5102 }
5103}
5104
5105function addEventPoolingTo(EventConstructor) {
5106 EventConstructor.eventPool = [];
5107 EventConstructor.getPooled = getPooledEvent;
5108 EventConstructor.release = releasePooledEvent;
5109}
5110
5111/**
5112 * @interface Event
5113 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
5114 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
5115 */
5116
5117var SyntheticAnimationEvent = SyntheticEvent.extend({
5118 animationName: null,
5119 elapsedTime: null,
5120 pseudoElement: null
5121});
5122
5123/**
5124 * @interface Event
5125 * @see http://www.w3.org/TR/clipboard-apis/
5126 */
5127
5128var SyntheticClipboardEvent = SyntheticEvent.extend({
5129 clipboardData: function (event) {
5130 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
5131 }
5132});
5133
5134var SyntheticUIEvent = SyntheticEvent.extend({
5135 view: null,
5136 detail: null
5137});
5138
5139/**
5140 * @interface FocusEvent
5141 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5142 */
5143
5144var SyntheticFocusEvent = SyntheticUIEvent.extend({
5145 relatedTarget: null
5146});
5147
5148/**
5149 * `charCode` represents the actual "character code" and is safe to use with
5150 * `String.fromCharCode`. As such, only keys that correspond to printable
5151 * characters produce a valid `charCode`, the only exception to this is Enter.
5152 * The Tab-key is considered non-printable and does not have a `charCode`,
5153 * presumably because it does not produce a tab-character in browsers.
5154 *
5155 * @param {object} nativeEvent Native browser event.
5156 * @return {number} Normalized `charCode` property.
5157 */
5158function getEventCharCode(nativeEvent) {
5159 var charCode;
5160 var keyCode = nativeEvent.keyCode;
5161
5162 if ('charCode' in nativeEvent) {
5163 charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
5164
5165 if (charCode === 0 && keyCode === 13) {
5166 charCode = 13;
5167 }
5168 } else {
5169 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
5170 charCode = keyCode;
5171 } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
5172 // report Enter as charCode 10 when ctrl is pressed.
5173
5174
5175 if (charCode === 10) {
5176 charCode = 13;
5177 } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
5178 // Must not discard the (non-)printable Enter-key.
5179
5180
5181 if (charCode >= 32 || charCode === 13) {
5182 return charCode;
5183 }
5184
5185 return 0;
5186}
5187
5188/**
5189 * Normalization of deprecated HTML5 `key` values
5190 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5191 */
5192
5193var normalizeKey = {
5194 Esc: 'Escape',
5195 Spacebar: ' ',
5196 Left: 'ArrowLeft',
5197 Up: 'ArrowUp',
5198 Right: 'ArrowRight',
5199 Down: 'ArrowDown',
5200 Del: 'Delete',
5201 Win: 'OS',
5202 Menu: 'ContextMenu',
5203 Apps: 'ContextMenu',
5204 Scroll: 'ScrollLock',
5205 MozPrintableKey: 'Unidentified'
5206};
5207/**
5208 * Translation from legacy `keyCode` to HTML5 `key`
5209 * Only special keys supported, all others depend on keyboard layout or browser
5210 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5211 */
5212
5213var translateToKey = {
5214 '8': 'Backspace',
5215 '9': 'Tab',
5216 '12': 'Clear',
5217 '13': 'Enter',
5218 '16': 'Shift',
5219 '17': 'Control',
5220 '18': 'Alt',
5221 '19': 'Pause',
5222 '20': 'CapsLock',
5223 '27': 'Escape',
5224 '32': ' ',
5225 '33': 'PageUp',
5226 '34': 'PageDown',
5227 '35': 'End',
5228 '36': 'Home',
5229 '37': 'ArrowLeft',
5230 '38': 'ArrowUp',
5231 '39': 'ArrowRight',
5232 '40': 'ArrowDown',
5233 '45': 'Insert',
5234 '46': 'Delete',
5235 '112': 'F1',
5236 '113': 'F2',
5237 '114': 'F3',
5238 '115': 'F4',
5239 '116': 'F5',
5240 '117': 'F6',
5241 '118': 'F7',
5242 '119': 'F8',
5243 '120': 'F9',
5244 '121': 'F10',
5245 '122': 'F11',
5246 '123': 'F12',
5247 '144': 'NumLock',
5248 '145': 'ScrollLock',
5249 '224': 'Meta'
5250};
5251/**
5252 * @param {object} nativeEvent Native browser event.
5253 * @return {string} Normalized `key` property.
5254 */
5255
5256function getEventKey(nativeEvent) {
5257 if (nativeEvent.key) {
5258 // Normalize inconsistent values reported by browsers due to
5259 // implementations of a working draft specification.
5260 // FireFox implements `key` but returns `MozPrintableKey` for all
5261 // printable characters (normalized to `Unidentified`), ignore it.
5262 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
5263
5264 if (key !== 'Unidentified') {
5265 return key;
5266 }
5267 } // Browser does not implement `key`, polyfill as much of it as we can.
5268
5269
5270 if (nativeEvent.type === 'keypress') {
5271 var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
5272 // thus be captured by `keypress`, no other non-printable key should.
5273
5274 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
5275 }
5276
5277 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
5278 // While user keyboard layout determines the actual meaning of each
5279 // `keyCode` value, almost all function keys have a universal value.
5280 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
5281 }
5282
5283 return '';
5284}
5285
5286/**
5287 * Translation from modifier key to the associated property in the event.
5288 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
5289 */
5290var modifierKeyToProp = {
5291 Alt: 'altKey',
5292 Control: 'ctrlKey',
5293 Meta: 'metaKey',
5294 Shift: 'shiftKey'
5295}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
5296// getModifierState. If getModifierState is not supported, we map it to a set of
5297// modifier keys exposed by the event. In this case, Lock-keys are not supported.
5298
5299function modifierStateGetter(keyArg) {
5300 var syntheticEvent = this;
5301 var nativeEvent = syntheticEvent.nativeEvent;
5302
5303 if (nativeEvent.getModifierState) {
5304 return nativeEvent.getModifierState(keyArg);
5305 }
5306
5307 var keyProp = modifierKeyToProp[keyArg];
5308 return keyProp ? !!nativeEvent[keyProp] : false;
5309}
5310
5311function getEventModifierState(nativeEvent) {
5312 return modifierStateGetter;
5313}
5314
5315/**
5316 * @interface KeyboardEvent
5317 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5318 */
5319
5320var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
5321 key: getEventKey,
5322 location: null,
5323 ctrlKey: null,
5324 shiftKey: null,
5325 altKey: null,
5326 metaKey: null,
5327 repeat: null,
5328 locale: null,
5329 getModifierState: getEventModifierState,
5330 // Legacy Interface
5331 charCode: function (event) {
5332 // `charCode` is the result of a KeyPress event and represents the value of
5333 // the actual printable character.
5334 // KeyPress is deprecated, but its replacement is not yet final and not
5335 // implemented in any major browser. Only KeyPress has charCode.
5336 if (event.type === 'keypress') {
5337 return getEventCharCode(event);
5338 }
5339
5340 return 0;
5341 },
5342 keyCode: function (event) {
5343 // `keyCode` is the result of a KeyDown/Up event and represents the value of
5344 // physical keyboard key.
5345 // The actual meaning of the value depends on the users' keyboard layout
5346 // which cannot be detected. Assuming that it is a US keyboard layout
5347 // provides a surprisingly accurate mapping for US and European users.
5348 // Due to this, it is left to the user to implement at this time.
5349 if (event.type === 'keydown' || event.type === 'keyup') {
5350 return event.keyCode;
5351 }
5352
5353 return 0;
5354 },
5355 which: function (event) {
5356 // `which` is an alias for either `keyCode` or `charCode` depending on the
5357 // type of the event.
5358 if (event.type === 'keypress') {
5359 return getEventCharCode(event);
5360 }
5361
5362 if (event.type === 'keydown' || event.type === 'keyup') {
5363 return event.keyCode;
5364 }
5365
5366 return 0;
5367 }
5368});
5369
5370var previousScreenX = 0;
5371var previousScreenY = 0; // Use flags to signal movementX/Y has already been set
5372
5373var isMovementXSet = false;
5374var isMovementYSet = false;
5375/**
5376 * @interface MouseEvent
5377 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5378 */
5379
5380var SyntheticMouseEvent = SyntheticUIEvent.extend({
5381 screenX: null,
5382 screenY: null,
5383 clientX: null,
5384 clientY: null,
5385 pageX: null,
5386 pageY: null,
5387 ctrlKey: null,
5388 shiftKey: null,
5389 altKey: null,
5390 metaKey: null,
5391 getModifierState: getEventModifierState,
5392 button: null,
5393 buttons: null,
5394 relatedTarget: function (event) {
5395 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
5396 },
5397 movementX: function (event) {
5398 if ('movementX' in event) {
5399 return event.movementX;
5400 }
5401
5402 var screenX = previousScreenX;
5403 previousScreenX = event.screenX;
5404
5405 if (!isMovementXSet) {
5406 isMovementXSet = true;
5407 return 0;
5408 }
5409
5410 return event.type === 'mousemove' ? event.screenX - screenX : 0;
5411 },
5412 movementY: function (event) {
5413 if ('movementY' in event) {
5414 return event.movementY;
5415 }
5416
5417 var screenY = previousScreenY;
5418 previousScreenY = event.screenY;
5419
5420 if (!isMovementYSet) {
5421 isMovementYSet = true;
5422 return 0;
5423 }
5424
5425 return event.type === 'mousemove' ? event.screenY - screenY : 0;
5426 }
5427});
5428
5429/**
5430 * @interface PointerEvent
5431 * @see http://www.w3.org/TR/pointerevents/
5432 */
5433
5434var SyntheticPointerEvent = SyntheticMouseEvent.extend({
5435 pointerId: null,
5436 width: null,
5437 height: null,
5438 pressure: null,
5439 tangentialPressure: null,
5440 tiltX: null,
5441 tiltY: null,
5442 twist: null,
5443 pointerType: null,
5444 isPrimary: null
5445});
5446
5447/**
5448 * @interface DragEvent
5449 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5450 */
5451
5452var SyntheticDragEvent = SyntheticMouseEvent.extend({
5453 dataTransfer: null
5454});
5455
5456/**
5457 * @interface TouchEvent
5458 * @see http://www.w3.org/TR/touch-events/
5459 */
5460
5461var SyntheticTouchEvent = SyntheticUIEvent.extend({
5462 touches: null,
5463 targetTouches: null,
5464 changedTouches: null,
5465 altKey: null,
5466 metaKey: null,
5467 ctrlKey: null,
5468 shiftKey: null,
5469 getModifierState: getEventModifierState
5470});
5471
5472/**
5473 * @interface Event
5474 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
5475 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
5476 */
5477
5478var SyntheticTransitionEvent = SyntheticEvent.extend({
5479 propertyName: null,
5480 elapsedTime: null,
5481 pseudoElement: null
5482});
5483
5484/**
5485 * @interface WheelEvent
5486 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5487 */
5488
5489var SyntheticWheelEvent = SyntheticMouseEvent.extend({
5490 deltaX: function (event) {
5491 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
5492 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
5493 },
5494 deltaY: function (event) {
5495 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
5496 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
5497 'wheelDelta' in event ? -event.wheelDelta : 0;
5498 },
5499 deltaZ: null,
5500 // Browsers without "deltaMode" is reporting in raw wheel delta where one
5501 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
5502 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
5503 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
5504 deltaMode: null
5505});
5506
5507/**
5508 * Turns
5509 * ['abort', ...]
5510 * into
5511 * eventTypes = {
5512 * 'abort': {
5513 * phasedRegistrationNames: {
5514 * bubbled: 'onAbort',
5515 * captured: 'onAbortCapture',
5516 * },
5517 * dependencies: [TOP_ABORT],
5518 * },
5519 * ...
5520 * };
5521 * topLevelEventsToDispatchConfig = new Map([
5522 * [TOP_ABORT, { sameConfig }],
5523 * ]);
5524 */
5525
5526var eventTuples = [// Discrete events
5527[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
5528[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
5529[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]];
5530var eventTypes = {};
5531var topLevelEventsToDispatchConfig = {};
5532
5533for (var i = 0; i < eventTuples.length; i++) {
5534 var eventTuple = eventTuples[i];
5535 var topEvent = eventTuple[0];
5536 var event = eventTuple[1];
5537 var eventPriority = eventTuple[2];
5538 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
5539 var onEvent = 'on' + capitalizedEvent;
5540 var config = {
5541 phasedRegistrationNames: {
5542 bubbled: onEvent,
5543 captured: onEvent + 'Capture'
5544 },
5545 dependencies: [topEvent],
5546 eventPriority: eventPriority
5547 };
5548 eventTypes[event] = config;
5549 topLevelEventsToDispatchConfig[topEvent] = config;
5550} // Only used in DEV for exhaustiveness validation.
5551
5552
5553var 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];
5554var SimpleEventPlugin = {
5555 eventTypes: eventTypes,
5556 getEventPriority: function (topLevelType) {
5557 var config = topLevelEventsToDispatchConfig[topLevelType];
5558 return config !== undefined ? config.eventPriority : ContinuousEvent;
5559 },
5560 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
5561 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
5562
5563 if (!dispatchConfig) {
5564 return null;
5565 }
5566
5567 var EventConstructor;
5568
5569 switch (topLevelType) {
5570 case TOP_KEY_PRESS:
5571 // Firefox creates a keypress event for function keys too. This removes
5572 // the unwanted keypress events. Enter is however both printable and
5573 // non-printable. One would expect Tab to be as well (but it isn't).
5574 if (getEventCharCode(nativeEvent) === 0) {
5575 return null;
5576 }
5577
5578 /* falls through */
5579
5580 case TOP_KEY_DOWN:
5581 case TOP_KEY_UP:
5582 EventConstructor = SyntheticKeyboardEvent;
5583 break;
5584
5585 case TOP_BLUR:
5586 case TOP_FOCUS:
5587 EventConstructor = SyntheticFocusEvent;
5588 break;
5589
5590 case TOP_CLICK:
5591 // Firefox creates a click event on right mouse clicks. This removes the
5592 // unwanted click events.
5593 if (nativeEvent.button === 2) {
5594 return null;
5595 }
5596
5597 /* falls through */
5598
5599 case TOP_AUX_CLICK:
5600 case TOP_DOUBLE_CLICK:
5601 case TOP_MOUSE_DOWN:
5602 case TOP_MOUSE_MOVE:
5603 case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events
5604
5605 /* falls through */
5606
5607 case TOP_MOUSE_OUT:
5608 case TOP_MOUSE_OVER:
5609 case TOP_CONTEXT_MENU:
5610 EventConstructor = SyntheticMouseEvent;
5611 break;
5612
5613 case TOP_DRAG:
5614 case TOP_DRAG_END:
5615 case TOP_DRAG_ENTER:
5616 case TOP_DRAG_EXIT:
5617 case TOP_DRAG_LEAVE:
5618 case TOP_DRAG_OVER:
5619 case TOP_DRAG_START:
5620 case TOP_DROP:
5621 EventConstructor = SyntheticDragEvent;
5622 break;
5623
5624 case TOP_TOUCH_CANCEL:
5625 case TOP_TOUCH_END:
5626 case TOP_TOUCH_MOVE:
5627 case TOP_TOUCH_START:
5628 EventConstructor = SyntheticTouchEvent;
5629 break;
5630
5631 case TOP_ANIMATION_END:
5632 case TOP_ANIMATION_ITERATION:
5633 case TOP_ANIMATION_START:
5634 EventConstructor = SyntheticAnimationEvent;
5635 break;
5636
5637 case TOP_TRANSITION_END:
5638 EventConstructor = SyntheticTransitionEvent;
5639 break;
5640
5641 case TOP_SCROLL:
5642 EventConstructor = SyntheticUIEvent;
5643 break;
5644
5645 case TOP_WHEEL:
5646 EventConstructor = SyntheticWheelEvent;
5647 break;
5648
5649 case TOP_COPY:
5650 case TOP_CUT:
5651 case TOP_PASTE:
5652 EventConstructor = SyntheticClipboardEvent;
5653 break;
5654
5655 case TOP_GOT_POINTER_CAPTURE:
5656 case TOP_LOST_POINTER_CAPTURE:
5657 case TOP_POINTER_CANCEL:
5658 case TOP_POINTER_DOWN:
5659 case TOP_POINTER_MOVE:
5660 case TOP_POINTER_OUT:
5661 case TOP_POINTER_OVER:
5662 case TOP_POINTER_UP:
5663 EventConstructor = SyntheticPointerEvent;
5664 break;
5665
5666 default:
5667 {
5668 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
5669 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
5670 }
5671 } // HTML Events
5672 // @see http://www.w3.org/TR/html5/index.html#events-0
5673
5674
5675 EventConstructor = SyntheticEvent;
5676 break;
5677 }
5678
5679 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
5680 accumulateTwoPhaseDispatches(event);
5681 return event;
5682 }
5683};
5684
5685var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
5686// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
5687
5688if (enableFlareAPI && canUseDOM) {
5689 try {
5690 var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
5691
5692 Object.defineProperty(options, 'passive', {
5693 get: function () {
5694 passiveBrowserEventsSupported = true;
5695 }
5696 });
5697 window.addEventListener('test', options, options);
5698 window.removeEventListener('test', options, options);
5699 } catch (e) {
5700 passiveBrowserEventsSupported = false;
5701 }
5702}
5703
5704// Intentionally not named imports because Rollup would use dynamic dispatch for
5705// CommonJS interop named imports.
5706var UserBlockingPriority$1 = Scheduler.unstable_UserBlockingPriority;
5707var runWithPriority$1 = Scheduler.unstable_runWithPriority;
5708var getEventPriority = SimpleEventPlugin.getEventPriority;
5709var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
5710var callbackBookkeepingPool = [];
5711
5712/**
5713 * Find the deepest React component completely containing the root of the
5714 * passed-in instance (for use when entire React trees are nested within each
5715 * other). If React trees are not nested, returns null.
5716 */
5717function findRootContainerNode(inst) {
5718 if (inst.tag === HostRoot) {
5719 return inst.stateNode.containerInfo;
5720 } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
5721 // traversal, but caching is difficult to do correctly without using a
5722 // mutation observer to listen for all DOM changes.
5723
5724
5725 while (inst.return) {
5726 inst = inst.return;
5727 }
5728
5729 if (inst.tag !== HostRoot) {
5730 // This can happen if we're in a detached tree.
5731 return null;
5732 }
5733
5734 return inst.stateNode.containerInfo;
5735} // Used to store ancestor hierarchy in top level callback
5736
5737
5738function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
5739 if (callbackBookkeepingPool.length) {
5740 var instance = callbackBookkeepingPool.pop();
5741 instance.topLevelType = topLevelType;
5742 instance.eventSystemFlags = eventSystemFlags;
5743 instance.nativeEvent = nativeEvent;
5744 instance.targetInst = targetInst;
5745 return instance;
5746 }
5747
5748 return {
5749 topLevelType: topLevelType,
5750 eventSystemFlags: eventSystemFlags,
5751 nativeEvent: nativeEvent,
5752 targetInst: targetInst,
5753 ancestors: []
5754 };
5755}
5756
5757function releaseTopLevelCallbackBookKeeping(instance) {
5758 instance.topLevelType = null;
5759 instance.nativeEvent = null;
5760 instance.targetInst = null;
5761 instance.ancestors.length = 0;
5762
5763 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
5764 callbackBookkeepingPool.push(instance);
5765 }
5766}
5767
5768function handleTopLevel(bookKeeping) {
5769 var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
5770 // It's important that we build the array of ancestors before calling any
5771 // event handlers, because event handlers can modify the DOM, leading to
5772 // inconsistencies with ReactMount's node cache. See #1105.
5773
5774 var ancestor = targetInst;
5775
5776 do {
5777 if (!ancestor) {
5778 var ancestors = bookKeeping.ancestors;
5779 ancestors.push(ancestor);
5780 break;
5781 }
5782
5783 var root = findRootContainerNode(ancestor);
5784
5785 if (!root) {
5786 break;
5787 }
5788
5789 var tag = ancestor.tag;
5790
5791 if (tag === HostComponent || tag === HostText) {
5792 bookKeeping.ancestors.push(ancestor);
5793 }
5794
5795 ancestor = getClosestInstanceFromNode(root);
5796 } while (ancestor);
5797
5798 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
5799 targetInst = bookKeeping.ancestors[i];
5800 var eventTarget = getEventTarget(bookKeeping.nativeEvent);
5801 var topLevelType = bookKeeping.topLevelType;
5802 var nativeEvent = bookKeeping.nativeEvent;
5803 runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, bookKeeping.eventSystemFlags);
5804 }
5805} // TODO: can we stop exporting these?
5806
5807
5808var _enabled = true;
5809function setEnabled(enabled) {
5810 _enabled = !!enabled;
5811}
5812function isEnabled() {
5813 return _enabled;
5814}
5815function trapBubbledEvent(topLevelType, element) {
5816 trapEventForPluginEventSystem(element, topLevelType, false);
5817}
5818function trapCapturedEvent(topLevelType, element) {
5819 trapEventForPluginEventSystem(element, topLevelType, true);
5820}
5821function trapEventForResponderEventSystem(element, topLevelType, passive) {
5822 if (enableFlareAPI) {
5823 var rawEventName = getRawEventName(topLevelType);
5824 var eventFlags = RESPONDER_EVENT_SYSTEM; // If passive option is not supported, then the event will be
5825 // active and not passive, but we flag it as using not being
5826 // supported too. This way the responder event plugins know,
5827 // and can provide polyfills if needed.
5828
5829 if (passive) {
5830 if (passiveBrowserEventsSupported) {
5831 eventFlags |= IS_PASSIVE;
5832 } else {
5833 eventFlags |= IS_ACTIVE;
5834 eventFlags |= PASSIVE_NOT_SUPPORTED;
5835 passive = false;
5836 }
5837 } else {
5838 eventFlags |= IS_ACTIVE;
5839 } // Check if interactive and wrap in discreteUpdates
5840
5841
5842 var listener = dispatchEvent.bind(null, topLevelType, eventFlags);
5843
5844 if (passiveBrowserEventsSupported) {
5845 addEventCaptureListenerWithPassiveFlag(element, rawEventName, listener, passive);
5846 } else {
5847 addEventCaptureListener(element, rawEventName, listener);
5848 }
5849 }
5850}
5851
5852function trapEventForPluginEventSystem(element, topLevelType, capture) {
5853 var listener;
5854
5855 switch (getEventPriority(topLevelType)) {
5856 case DiscreteEvent:
5857 listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5858 break;
5859
5860 case UserBlockingEvent:
5861 listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5862 break;
5863
5864 case ContinuousEvent:
5865 default:
5866 listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5867 break;
5868 }
5869
5870 var rawEventName = getRawEventName(topLevelType);
5871
5872 if (capture) {
5873 addEventCaptureListener(element, rawEventName, listener);
5874 } else {
5875 addEventBubbleListener(element, rawEventName, listener);
5876 }
5877}
5878
5879function dispatchDiscreteEvent(topLevelType, eventSystemFlags, nativeEvent) {
5880 flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
5881 discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
5882}
5883
5884function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, nativeEvent) {
5885 runWithPriority$1(UserBlockingPriority$1, dispatchEvent.bind(null, topLevelType, eventSystemFlags, nativeEvent));
5886}
5887
5888function dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
5889 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
5890
5891 try {
5892 // Event queue being processed in the same cycle allows
5893 // `preventDefault`.
5894 batchedEventUpdates(handleTopLevel, bookKeeping);
5895 } finally {
5896 releaseTopLevelCallbackBookKeeping(bookKeeping);
5897 }
5898}
5899
5900function dispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
5901 if (!_enabled) {
5902 return;
5903 }
5904
5905 if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
5906 // If we already have a queue of discrete events, and this is another discrete
5907 // event, then we can't dispatch it regardless of its target, since they
5908 // need to dispatch in order.
5909 queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
5910 topLevelType, eventSystemFlags, nativeEvent);
5911 return;
5912 }
5913
5914 var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
5915
5916 if (blockedOn === null) {
5917 // We successfully dispatched this event.
5918 clearIfContinuousEvent(topLevelType, nativeEvent);
5919 return;
5920 }
5921
5922 if (isReplayableDiscreteEvent(topLevelType)) {
5923 // This this to be replayed later once the target is available.
5924 queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
5925 return;
5926 }
5927
5928 if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent)) {
5929 return;
5930 } // We need to clear only if we didn't queue because
5931 // queueing is accummulative.
5932
5933
5934 clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
5935 // in case the event system needs to trace it.
5936
5937 if (enableFlareAPI) {
5938 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
5939 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
5940 }
5941
5942 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
5943 // React Flare event system
5944 dispatchEventForResponderEventSystem(topLevelType, null, nativeEvent, getEventTarget(nativeEvent), eventSystemFlags);
5945 }
5946 } else {
5947 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
5948 }
5949} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
5950
5951function attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
5952 // TODO: Warn if _enabled is false.
5953 var nativeEventTarget = getEventTarget(nativeEvent);
5954 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
5955
5956 if (targetInst !== null) {
5957 var nearestMounted = getNearestMountedFiber(targetInst);
5958
5959 if (nearestMounted === null) {
5960 // This tree has been unmounted already. Dispatch without a target.
5961 targetInst = null;
5962 } else {
5963 var tag = nearestMounted.tag;
5964
5965 if (tag === SuspenseComponent) {
5966 var instance = getSuspenseInstanceFromFiber(nearestMounted);
5967
5968 if (instance !== null) {
5969 // Queue the event to be replayed later. Abort dispatching since we
5970 // don't want this event dispatched twice through the event system.
5971 // TODO: If this is the first discrete event in the queue. Schedule an increased
5972 // priority for this boundary.
5973 return instance;
5974 } // This shouldn't happen, something went wrong but to avoid blocking
5975 // the whole system, dispatch the event without a target.
5976 // TODO: Warn.
5977
5978
5979 targetInst = null;
5980 } else if (tag === HostRoot) {
5981 var root = nearestMounted.stateNode;
5982
5983 if (root.hydrate) {
5984 // If this happens during a replay something went wrong and it might block
5985 // the whole system.
5986 return getContainerFromFiber(nearestMounted);
5987 }
5988
5989 targetInst = null;
5990 } else if (nearestMounted !== targetInst) {
5991 // If we get an event (ex: img onload) before committing that
5992 // component's mount, ignore it for now (that is, treat it as if it was an
5993 // event on a non-React tree). We might also consider queueing events and
5994 // dispatching them after the mount.
5995 targetInst = null;
5996 }
5997 }
5998 }
5999
6000 if (enableFlareAPI) {
6001 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6002 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6003 }
6004
6005 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6006 // React Flare event system
6007 dispatchEventForResponderEventSystem(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
6008 }
6009 } else {
6010 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6011 } // We're not blocked on anything.
6012
6013
6014 return null;
6015}
6016
6017/**
6018 * Checks if an event is supported in the current execution environment.
6019 *
6020 * NOTE: This will not work correctly for non-generic events such as `change`,
6021 * `reset`, `load`, `error`, and `select`.
6022 *
6023 * Borrows from Modernizr.
6024 *
6025 * @param {string} eventNameSuffix Event name, e.g. "click".
6026 * @return {boolean} True if the event is supported.
6027 * @internal
6028 * @license Modernizr 3.0.0pre (Custom Build) | MIT
6029 */
6030
6031function isEventSupported(eventNameSuffix) {
6032 if (!canUseDOM) {
6033 return false;
6034 }
6035
6036 var eventName = 'on' + eventNameSuffix;
6037 var isSupported = eventName in document;
6038
6039 if (!isSupported) {
6040 var element = document.createElement('div');
6041 element.setAttribute(eventName, 'return;');
6042 isSupported = typeof element[eventName] === 'function';
6043 }
6044
6045 return isSupported;
6046}
6047
6048/**
6049 * Summary of `ReactBrowserEventEmitter` event handling:
6050 *
6051 * - Top-level delegation is used to trap most native browser events. This
6052 * may only occur in the main thread and is the responsibility of
6053 * ReactDOMEventListener, which is injected and can therefore support
6054 * pluggable event sources. This is the only work that occurs in the main
6055 * thread.
6056 *
6057 * - We normalize and de-duplicate events to account for browser quirks. This
6058 * may be done in the worker thread.
6059 *
6060 * - Forward these native events (with the associated top-level type used to
6061 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
6062 * to extract any synthetic events.
6063 *
6064 * - The `EventPluginHub` will then process each event by annotating them with
6065 * "dispatches", a sequence of listeners and IDs that care about that event.
6066 *
6067 * - The `EventPluginHub` then dispatches the events.
6068 *
6069 * Overview of React and the event system:
6070 *
6071 * +------------+ .
6072 * | DOM | .
6073 * +------------+ .
6074 * | .
6075 * v .
6076 * +------------+ .
6077 * | ReactEvent | .
6078 * | Listener | .
6079 * +------------+ . +-----------+
6080 * | . +--------+|SimpleEvent|
6081 * | . | |Plugin |
6082 * +-----|------+ . v +-----------+
6083 * | | | . +--------------+ +------------+
6084 * | +-----------.--->|EventPluginHub| | Event |
6085 * | | . | | +-----------+ | Propagators|
6086 * | ReactEvent | . | | |TapEvent | |------------|
6087 * | Emitter | . | |<---+|Plugin | |other plugin|
6088 * | | . | | +-----------+ | utilities |
6089 * | +-----------.--->| | +------------+
6090 * | | | . +--------------+
6091 * +-----|------+ . ^ +-----------+
6092 * | . | |Enter/Leave|
6093 * + . +-------+|Plugin |
6094 * +-------------+ . +-----------+
6095 * | application | .
6096 * |-------------| .
6097 * | | .
6098 * | | .
6099 * +-------------+ .
6100 * .
6101 * React Core . General Purpose Event Plugin System
6102 */
6103
6104var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
6105var elementListeningSets = new PossiblyWeakMap();
6106function getListeningSetForElement(element) {
6107 var listeningSet = elementListeningSets.get(element);
6108
6109 if (listeningSet === undefined) {
6110 listeningSet = new Set();
6111 elementListeningSets.set(element, listeningSet);
6112 }
6113
6114 return listeningSet;
6115}
6116/**
6117 * We listen for bubbled touch events on the document object.
6118 *
6119 * Firefox v8.01 (and possibly others) exhibited strange behavior when
6120 * mounting `onmousemove` events at some node that was not the document
6121 * element. The symptoms were that if your mouse is not moving over something
6122 * contained within that mount point (for example on the background) the
6123 * top-level listeners for `onmousemove` won't be called. However, if you
6124 * register the `mousemove` on the document object, then it will of course
6125 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
6126 * top-level listeners to the document object only, at least for these
6127 * movement types of events and possibly all events.
6128 *
6129 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
6130 *
6131 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
6132 * they bubble to document.
6133 *
6134 * @param {string} registrationName Name of listener (e.g. `onClick`).
6135 * @param {object} mountAt Container where to mount the listener
6136 */
6137
6138function listenTo(registrationName, mountAt) {
6139 var listeningSet = getListeningSetForElement(mountAt);
6140 var dependencies = registrationNameDependencies[registrationName];
6141
6142 for (var i = 0; i < dependencies.length; i++) {
6143 var dependency = dependencies[i];
6144 listenToTopLevel(dependency, mountAt, listeningSet);
6145 }
6146}
6147function listenToTopLevel(topLevelType, mountAt, listeningSet) {
6148 if (!listeningSet.has(topLevelType)) {
6149 switch (topLevelType) {
6150 case TOP_SCROLL:
6151 trapCapturedEvent(TOP_SCROLL, mountAt);
6152 break;
6153
6154 case TOP_FOCUS:
6155 case TOP_BLUR:
6156 trapCapturedEvent(TOP_FOCUS, mountAt);
6157 trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
6158 // but this ensures we mark both as attached rather than just one.
6159
6160 listeningSet.add(TOP_BLUR);
6161 listeningSet.add(TOP_FOCUS);
6162 break;
6163
6164 case TOP_CANCEL:
6165 case TOP_CLOSE:
6166 if (isEventSupported(getRawEventName(topLevelType))) {
6167 trapCapturedEvent(topLevelType, mountAt);
6168 }
6169
6170 break;
6171
6172 case TOP_INVALID:
6173 case TOP_SUBMIT:
6174 case TOP_RESET:
6175 // We listen to them on the target DOM elements.
6176 // Some of them bubble so we don't want them to fire twice.
6177 break;
6178
6179 default:
6180 // By default, listen on the top level to all non-media events.
6181 // Media events don't bubble so adding the listener wouldn't do anything.
6182 var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;
6183
6184 if (!isMediaEvent) {
6185 trapBubbledEvent(topLevelType, mountAt);
6186 }
6187
6188 break;
6189 }
6190
6191 listeningSet.add(topLevelType);
6192 }
6193}
6194function isListeningToAllDependencies(registrationName, mountAt) {
6195 var listeningSet = getListeningSetForElement(mountAt);
6196 var dependencies = registrationNameDependencies[registrationName];
6197
6198 for (var i = 0; i < dependencies.length; i++) {
6199 var dependency = dependencies[i];
6200
6201 if (!listeningSet.has(dependency)) {
6202 return false;
6203 }
6204 }
6205
6206 return true;
6207}
6208
6209// List derived from Gecko source code:
6210// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6211var shorthandToLonghand = {
6212 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6213 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6214 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6215 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6216 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6217 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6218 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6219 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6220 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6221 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6222 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6223 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6224 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6225 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6226 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6227 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6228 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6229 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6230 columns: ['columnCount', 'columnWidth'],
6231 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6232 flexFlow: ['flexDirection', 'flexWrap'],
6233 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6234 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6235 gap: ['columnGap', 'rowGap'],
6236 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6237 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6238 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6239 gridColumnGap: ['columnGap'],
6240 gridGap: ['columnGap', 'rowGap'],
6241 gridRow: ['gridRowEnd', 'gridRowStart'],
6242 gridRowGap: ['rowGap'],
6243 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6244 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6245 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6246 marker: ['markerEnd', 'markerMid', 'markerStart'],
6247 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6248 maskPosition: ['maskPositionX', 'maskPositionY'],
6249 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6250 overflow: ['overflowX', 'overflowY'],
6251 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6252 placeContent: ['alignContent', 'justifyContent'],
6253 placeItems: ['alignItems', 'justifyItems'],
6254 placeSelf: ['alignSelf', 'justifySelf'],
6255 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6256 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6257 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6258 wordWrap: ['overflowWrap']
6259};
6260
6261/**
6262 * CSS properties which accept numbers but are not in units of "px".
6263 */
6264var isUnitlessNumber = {
6265 animationIterationCount: true,
6266 borderImageOutset: true,
6267 borderImageSlice: true,
6268 borderImageWidth: true,
6269 boxFlex: true,
6270 boxFlexGroup: true,
6271 boxOrdinalGroup: true,
6272 columnCount: true,
6273 columns: true,
6274 flex: true,
6275 flexGrow: true,
6276 flexPositive: true,
6277 flexShrink: true,
6278 flexNegative: true,
6279 flexOrder: true,
6280 gridArea: true,
6281 gridRow: true,
6282 gridRowEnd: true,
6283 gridRowSpan: true,
6284 gridRowStart: true,
6285 gridColumn: true,
6286 gridColumnEnd: true,
6287 gridColumnSpan: true,
6288 gridColumnStart: true,
6289 fontWeight: true,
6290 lineClamp: true,
6291 lineHeight: true,
6292 opacity: true,
6293 order: true,
6294 orphans: true,
6295 tabSize: true,
6296 widows: true,
6297 zIndex: true,
6298 zoom: true,
6299 // SVG-related properties
6300 fillOpacity: true,
6301 floodOpacity: true,
6302 stopOpacity: true,
6303 strokeDasharray: true,
6304 strokeDashoffset: true,
6305 strokeMiterlimit: true,
6306 strokeOpacity: true,
6307 strokeWidth: true
6308};
6309/**
6310 * @param {string} prefix vendor-specific prefix, eg: Webkit
6311 * @param {string} key style name, eg: transitionDuration
6312 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6313 * WebkitTransitionDuration
6314 */
6315
6316function prefixKey(prefix, key) {
6317 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6318}
6319/**
6320 * Support style names that may come passed in prefixed by adding permutations
6321 * of vendor prefixes.
6322 */
6323
6324
6325var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6326// infinite loop, because it iterates over the newly added props too.
6327
6328Object.keys(isUnitlessNumber).forEach(function (prop) {
6329 prefixes.forEach(function (prefix) {
6330 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6331 });
6332});
6333
6334/**
6335 * Convert a value into the proper css writable value. The style name `name`
6336 * should be logical (no hyphens), as specified
6337 * in `CSSProperty.isUnitlessNumber`.
6338 *
6339 * @param {string} name CSS property name such as `topMargin`.
6340 * @param {*} value CSS property value such as `10px`.
6341 * @return {string} Normalized style value with dimensions applied.
6342 */
6343
6344function dangerousStyleValue(name, value, isCustomProperty) {
6345 // Note that we've removed escapeTextForBrowser() calls here since the
6346 // whole string will be escaped when the attribute is injected into
6347 // the markup. If you provide unsafe user data here they can inject
6348 // arbitrary CSS which may be problematic (I couldn't repro this):
6349 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6350 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6351 // This is not an XSS hole but instead a potential CSS injection issue
6352 // which has lead to a greater discussion about how we're going to
6353 // trust URLs moving forward. See #2115901
6354 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6355
6356 if (isEmpty) {
6357 return '';
6358 }
6359
6360 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6361 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6362 }
6363
6364 return ('' + value).trim();
6365}
6366
6367var uppercasePattern = /([A-Z])/g;
6368var msPattern = /^ms-/;
6369/**
6370 * Hyphenates a camelcased CSS property name, for example:
6371 *
6372 * > hyphenateStyleName('backgroundColor')
6373 * < "background-color"
6374 * > hyphenateStyleName('MozTransition')
6375 * < "-moz-transition"
6376 * > hyphenateStyleName('msTransition')
6377 * < "-ms-transition"
6378 *
6379 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6380 * is converted to `-ms-`.
6381 */
6382
6383function hyphenateStyleName(name) {
6384 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6385}
6386
6387var warnValidStyle = function () {};
6388
6389{
6390 // 'msTransform' is correct, but the other prefixes should be capitalized
6391 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6392 var msPattern$1 = /^-ms-/;
6393 var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
6394
6395 var badStyleValueWithSemicolonPattern = /;\s*$/;
6396 var warnedStyleNames = {};
6397 var warnedStyleValues = {};
6398 var warnedForNaNValue = false;
6399 var warnedForInfinityValue = false;
6400
6401 var camelize = function (string) {
6402 return string.replace(hyphenPattern, function (_, character) {
6403 return character.toUpperCase();
6404 });
6405 };
6406
6407 var warnHyphenatedStyleName = function (name) {
6408 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6409 return;
6410 }
6411
6412 warnedStyleNames[name] = true;
6413 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
6414 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6415 // is converted to lowercase `ms`.
6416 camelize(name.replace(msPattern$1, 'ms-')));
6417 };
6418
6419 var warnBadVendoredStyleName = function (name) {
6420 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6421 return;
6422 }
6423
6424 warnedStyleNames[name] = true;
6425 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6426 };
6427
6428 var warnStyleValueWithSemicolon = function (name, value) {
6429 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6430 return;
6431 }
6432
6433 warnedStyleValues[value] = true;
6434 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6435 };
6436
6437 var warnStyleValueIsNaN = function (name, value) {
6438 if (warnedForNaNValue) {
6439 return;
6440 }
6441
6442 warnedForNaNValue = true;
6443 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6444 };
6445
6446 var warnStyleValueIsInfinity = function (name, value) {
6447 if (warnedForInfinityValue) {
6448 return;
6449 }
6450
6451 warnedForInfinityValue = true;
6452 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6453 };
6454
6455 warnValidStyle = function (name, value) {
6456 if (name.indexOf('-') > -1) {
6457 warnHyphenatedStyleName(name);
6458 } else if (badVendoredStyleNamePattern.test(name)) {
6459 warnBadVendoredStyleName(name);
6460 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6461 warnStyleValueWithSemicolon(name, value);
6462 }
6463
6464 if (typeof value === 'number') {
6465 if (isNaN(value)) {
6466 warnStyleValueIsNaN(name, value);
6467 } else if (!isFinite(value)) {
6468 warnStyleValueIsInfinity(name, value);
6469 }
6470 }
6471 };
6472}
6473
6474var warnValidStyle$1 = warnValidStyle;
6475
6476/**
6477 * Operations for dealing with CSS properties.
6478 */
6479
6480/**
6481 * This creates a string that is expected to be equivalent to the style
6482 * attribute generated by server-side rendering. It by-passes warnings and
6483 * security checks so it's not safe to use this value for anything other than
6484 * comparison. It is only used in DEV for SSR validation.
6485 */
6486
6487function createDangerousStringForStyles(styles) {
6488 {
6489 var serialized = '';
6490 var delimiter = '';
6491
6492 for (var styleName in styles) {
6493 if (!styles.hasOwnProperty(styleName)) {
6494 continue;
6495 }
6496
6497 var styleValue = styles[styleName];
6498
6499 if (styleValue != null) {
6500 var isCustomProperty = styleName.indexOf('--') === 0;
6501 serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
6502 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6503 delimiter = ';';
6504 }
6505 }
6506
6507 return serialized || null;
6508 }
6509}
6510/**
6511 * Sets the value for multiple styles on a node. If a value is specified as
6512 * '' (empty string), the corresponding style property will be unset.
6513 *
6514 * @param {DOMElement} node
6515 * @param {object} styles
6516 */
6517
6518function setValueForStyles(node, styles) {
6519 var style = node.style;
6520
6521 for (var styleName in styles) {
6522 if (!styles.hasOwnProperty(styleName)) {
6523 continue;
6524 }
6525
6526 var isCustomProperty = styleName.indexOf('--') === 0;
6527
6528 {
6529 if (!isCustomProperty) {
6530 warnValidStyle$1(styleName, styles[styleName]);
6531 }
6532 }
6533
6534 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6535
6536 if (styleName === 'float') {
6537 styleName = 'cssFloat';
6538 }
6539
6540 if (isCustomProperty) {
6541 style.setProperty(styleName, styleValue);
6542 } else {
6543 style[styleName] = styleValue;
6544 }
6545 }
6546}
6547
6548function isValueEmpty(value) {
6549 return value == null || typeof value === 'boolean' || value === '';
6550}
6551/**
6552 * Given {color: 'red', overflow: 'hidden'} returns {
6553 * color: 'color',
6554 * overflowX: 'overflow',
6555 * overflowY: 'overflow',
6556 * }. This can be read as "the overflowY property was set by the overflow
6557 * shorthand". That is, the values are the property that each was derived from.
6558 */
6559
6560
6561function expandShorthandMap(styles) {
6562 var expanded = {};
6563
6564 for (var key in styles) {
6565 var longhands = shorthandToLonghand[key] || [key];
6566
6567 for (var i = 0; i < longhands.length; i++) {
6568 expanded[longhands[i]] = key;
6569 }
6570 }
6571
6572 return expanded;
6573}
6574/**
6575 * When mixing shorthand and longhand property names, we warn during updates if
6576 * we expect an incorrect result to occur. In particular, we warn for:
6577 *
6578 * Updating a shorthand property (longhand gets overwritten):
6579 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6580 * becomes .style.font = 'baz'
6581 * Removing a shorthand property (longhand gets lost too):
6582 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6583 * becomes .style.font = ''
6584 * Removing a longhand property (should revert to shorthand; doesn't):
6585 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6586 * becomes .style.fontVariant = ''
6587 */
6588
6589
6590function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6591 if (!warnAboutShorthandPropertyCollision) {
6592 return;
6593 }
6594
6595 if (!nextStyles) {
6596 return;
6597 }
6598
6599 var expandedUpdates = expandShorthandMap(styleUpdates);
6600 var expandedStyles = expandShorthandMap(nextStyles);
6601 var warnedAbout = {};
6602
6603 for (var key in expandedUpdates) {
6604 var originalKey = expandedUpdates[key];
6605 var correctOriginalKey = expandedStyles[key];
6606
6607 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6608 var warningKey = originalKey + ',' + correctOriginalKey;
6609
6610 if (warnedAbout[warningKey]) {
6611 continue;
6612 }
6613
6614 warnedAbout[warningKey] = true;
6615 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);
6616 }
6617 }
6618}
6619
6620// For HTML, certain tags should omit their close tag. We keep a whitelist for
6621// those special-case tags.
6622var omittedCloseTags = {
6623 area: true,
6624 base: true,
6625 br: true,
6626 col: true,
6627 embed: true,
6628 hr: true,
6629 img: true,
6630 input: true,
6631 keygen: true,
6632 link: true,
6633 meta: true,
6634 param: true,
6635 source: true,
6636 track: true,
6637 wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
6638
6639};
6640
6641// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6642
6643var voidElementTags = _assign({
6644 menuitem: true
6645}, omittedCloseTags);
6646
6647// or add stack by default to invariants where possible.
6648
6649var HTML$1 = '__html';
6650var ReactDebugCurrentFrame$3 = null;
6651
6652{
6653 ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
6654}
6655
6656function assertValidProps(tag, props) {
6657 if (!props) {
6658 return;
6659 } // Note the use of `==` which checks for null or undefined.
6660
6661
6662 if (voidElementTags[tag]) {
6663 if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
6664 {
6665 throw Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + (ReactDebugCurrentFrame$3.getStackAddendum()));
6666 }
6667 }
6668 }
6669
6670 if (props.dangerouslySetInnerHTML != null) {
6671 if (!(props.children == null)) {
6672 {
6673 throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
6674 }
6675 }
6676
6677 if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML)) {
6678 {
6679 throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.");
6680 }
6681 }
6682 }
6683
6684 {
6685 !(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;
6686 }
6687
6688 if (!(props.style == null || typeof props.style === 'object')) {
6689 {
6690 throw 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()));
6691 }
6692 }
6693}
6694
6695function isCustomComponent(tagName, props) {
6696 if (tagName.indexOf('-') === -1) {
6697 return typeof props.is === 'string';
6698 }
6699
6700 switch (tagName) {
6701 // These are reserved SVG and MathML elements.
6702 // We don't mind this whitelist too much because we expect it to never grow.
6703 // The alternative is to track the namespace in a few places which is convoluted.
6704 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6705 case 'annotation-xml':
6706 case 'color-profile':
6707 case 'font-face':
6708 case 'font-face-src':
6709 case 'font-face-uri':
6710 case 'font-face-format':
6711 case 'font-face-name':
6712 case 'missing-glyph':
6713 return false;
6714
6715 default:
6716 return true;
6717 }
6718}
6719
6720// When adding attributes to the HTML or SVG whitelist, be sure to
6721// also add them to this module to ensure casing and incorrect name
6722// warnings.
6723var possibleStandardNames = {
6724 // HTML
6725 accept: 'accept',
6726 acceptcharset: 'acceptCharset',
6727 'accept-charset': 'acceptCharset',
6728 accesskey: 'accessKey',
6729 action: 'action',
6730 allowfullscreen: 'allowFullScreen',
6731 alt: 'alt',
6732 as: 'as',
6733 async: 'async',
6734 autocapitalize: 'autoCapitalize',
6735 autocomplete: 'autoComplete',
6736 autocorrect: 'autoCorrect',
6737 autofocus: 'autoFocus',
6738 autoplay: 'autoPlay',
6739 autosave: 'autoSave',
6740 capture: 'capture',
6741 cellpadding: 'cellPadding',
6742 cellspacing: 'cellSpacing',
6743 challenge: 'challenge',
6744 charset: 'charSet',
6745 checked: 'checked',
6746 children: 'children',
6747 cite: 'cite',
6748 class: 'className',
6749 classid: 'classID',
6750 classname: 'className',
6751 cols: 'cols',
6752 colspan: 'colSpan',
6753 content: 'content',
6754 contenteditable: 'contentEditable',
6755 contextmenu: 'contextMenu',
6756 controls: 'controls',
6757 controlslist: 'controlsList',
6758 coords: 'coords',
6759 crossorigin: 'crossOrigin',
6760 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6761 data: 'data',
6762 datetime: 'dateTime',
6763 default: 'default',
6764 defaultchecked: 'defaultChecked',
6765 defaultvalue: 'defaultValue',
6766 defer: 'defer',
6767 dir: 'dir',
6768 disabled: 'disabled',
6769 disablepictureinpicture: 'disablePictureInPicture',
6770 download: 'download',
6771 draggable: 'draggable',
6772 enctype: 'encType',
6773 for: 'htmlFor',
6774 form: 'form',
6775 formmethod: 'formMethod',
6776 formaction: 'formAction',
6777 formenctype: 'formEncType',
6778 formnovalidate: 'formNoValidate',
6779 formtarget: 'formTarget',
6780 frameborder: 'frameBorder',
6781 headers: 'headers',
6782 height: 'height',
6783 hidden: 'hidden',
6784 high: 'high',
6785 href: 'href',
6786 hreflang: 'hrefLang',
6787 htmlfor: 'htmlFor',
6788 httpequiv: 'httpEquiv',
6789 'http-equiv': 'httpEquiv',
6790 icon: 'icon',
6791 id: 'id',
6792 innerhtml: 'innerHTML',
6793 inputmode: 'inputMode',
6794 integrity: 'integrity',
6795 is: 'is',
6796 itemid: 'itemID',
6797 itemprop: 'itemProp',
6798 itemref: 'itemRef',
6799 itemscope: 'itemScope',
6800 itemtype: 'itemType',
6801 keyparams: 'keyParams',
6802 keytype: 'keyType',
6803 kind: 'kind',
6804 label: 'label',
6805 lang: 'lang',
6806 list: 'list',
6807 loop: 'loop',
6808 low: 'low',
6809 manifest: 'manifest',
6810 marginwidth: 'marginWidth',
6811 marginheight: 'marginHeight',
6812 max: 'max',
6813 maxlength: 'maxLength',
6814 media: 'media',
6815 mediagroup: 'mediaGroup',
6816 method: 'method',
6817 min: 'min',
6818 minlength: 'minLength',
6819 multiple: 'multiple',
6820 muted: 'muted',
6821 name: 'name',
6822 nomodule: 'noModule',
6823 nonce: 'nonce',
6824 novalidate: 'noValidate',
6825 open: 'open',
6826 optimum: 'optimum',
6827 pattern: 'pattern',
6828 placeholder: 'placeholder',
6829 playsinline: 'playsInline',
6830 poster: 'poster',
6831 preload: 'preload',
6832 profile: 'profile',
6833 radiogroup: 'radioGroup',
6834 readonly: 'readOnly',
6835 referrerpolicy: 'referrerPolicy',
6836 rel: 'rel',
6837 required: 'required',
6838 reversed: 'reversed',
6839 role: 'role',
6840 rows: 'rows',
6841 rowspan: 'rowSpan',
6842 sandbox: 'sandbox',
6843 scope: 'scope',
6844 scoped: 'scoped',
6845 scrolling: 'scrolling',
6846 seamless: 'seamless',
6847 selected: 'selected',
6848 shape: 'shape',
6849 size: 'size',
6850 sizes: 'sizes',
6851 span: 'span',
6852 spellcheck: 'spellCheck',
6853 src: 'src',
6854 srcdoc: 'srcDoc',
6855 srclang: 'srcLang',
6856 srcset: 'srcSet',
6857 start: 'start',
6858 step: 'step',
6859 style: 'style',
6860 summary: 'summary',
6861 tabindex: 'tabIndex',
6862 target: 'target',
6863 title: 'title',
6864 type: 'type',
6865 usemap: 'useMap',
6866 value: 'value',
6867 width: 'width',
6868 wmode: 'wmode',
6869 wrap: 'wrap',
6870 // SVG
6871 about: 'about',
6872 accentheight: 'accentHeight',
6873 'accent-height': 'accentHeight',
6874 accumulate: 'accumulate',
6875 additive: 'additive',
6876 alignmentbaseline: 'alignmentBaseline',
6877 'alignment-baseline': 'alignmentBaseline',
6878 allowreorder: 'allowReorder',
6879 alphabetic: 'alphabetic',
6880 amplitude: 'amplitude',
6881 arabicform: 'arabicForm',
6882 'arabic-form': 'arabicForm',
6883 ascent: 'ascent',
6884 attributename: 'attributeName',
6885 attributetype: 'attributeType',
6886 autoreverse: 'autoReverse',
6887 azimuth: 'azimuth',
6888 basefrequency: 'baseFrequency',
6889 baselineshift: 'baselineShift',
6890 'baseline-shift': 'baselineShift',
6891 baseprofile: 'baseProfile',
6892 bbox: 'bbox',
6893 begin: 'begin',
6894 bias: 'bias',
6895 by: 'by',
6896 calcmode: 'calcMode',
6897 capheight: 'capHeight',
6898 'cap-height': 'capHeight',
6899 clip: 'clip',
6900 clippath: 'clipPath',
6901 'clip-path': 'clipPath',
6902 clippathunits: 'clipPathUnits',
6903 cliprule: 'clipRule',
6904 'clip-rule': 'clipRule',
6905 color: 'color',
6906 colorinterpolation: 'colorInterpolation',
6907 'color-interpolation': 'colorInterpolation',
6908 colorinterpolationfilters: 'colorInterpolationFilters',
6909 'color-interpolation-filters': 'colorInterpolationFilters',
6910 colorprofile: 'colorProfile',
6911 'color-profile': 'colorProfile',
6912 colorrendering: 'colorRendering',
6913 'color-rendering': 'colorRendering',
6914 contentscripttype: 'contentScriptType',
6915 contentstyletype: 'contentStyleType',
6916 cursor: 'cursor',
6917 cx: 'cx',
6918 cy: 'cy',
6919 d: 'd',
6920 datatype: 'datatype',
6921 decelerate: 'decelerate',
6922 descent: 'descent',
6923 diffuseconstant: 'diffuseConstant',
6924 direction: 'direction',
6925 display: 'display',
6926 divisor: 'divisor',
6927 dominantbaseline: 'dominantBaseline',
6928 'dominant-baseline': 'dominantBaseline',
6929 dur: 'dur',
6930 dx: 'dx',
6931 dy: 'dy',
6932 edgemode: 'edgeMode',
6933 elevation: 'elevation',
6934 enablebackground: 'enableBackground',
6935 'enable-background': 'enableBackground',
6936 end: 'end',
6937 exponent: 'exponent',
6938 externalresourcesrequired: 'externalResourcesRequired',
6939 fill: 'fill',
6940 fillopacity: 'fillOpacity',
6941 'fill-opacity': 'fillOpacity',
6942 fillrule: 'fillRule',
6943 'fill-rule': 'fillRule',
6944 filter: 'filter',
6945 filterres: 'filterRes',
6946 filterunits: 'filterUnits',
6947 floodopacity: 'floodOpacity',
6948 'flood-opacity': 'floodOpacity',
6949 floodcolor: 'floodColor',
6950 'flood-color': 'floodColor',
6951 focusable: 'focusable',
6952 fontfamily: 'fontFamily',
6953 'font-family': 'fontFamily',
6954 fontsize: 'fontSize',
6955 'font-size': 'fontSize',
6956 fontsizeadjust: 'fontSizeAdjust',
6957 'font-size-adjust': 'fontSizeAdjust',
6958 fontstretch: 'fontStretch',
6959 'font-stretch': 'fontStretch',
6960 fontstyle: 'fontStyle',
6961 'font-style': 'fontStyle',
6962 fontvariant: 'fontVariant',
6963 'font-variant': 'fontVariant',
6964 fontweight: 'fontWeight',
6965 'font-weight': 'fontWeight',
6966 format: 'format',
6967 from: 'from',
6968 fx: 'fx',
6969 fy: 'fy',
6970 g1: 'g1',
6971 g2: 'g2',
6972 glyphname: 'glyphName',
6973 'glyph-name': 'glyphName',
6974 glyphorientationhorizontal: 'glyphOrientationHorizontal',
6975 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
6976 glyphorientationvertical: 'glyphOrientationVertical',
6977 'glyph-orientation-vertical': 'glyphOrientationVertical',
6978 glyphref: 'glyphRef',
6979 gradienttransform: 'gradientTransform',
6980 gradientunits: 'gradientUnits',
6981 hanging: 'hanging',
6982 horizadvx: 'horizAdvX',
6983 'horiz-adv-x': 'horizAdvX',
6984 horizoriginx: 'horizOriginX',
6985 'horiz-origin-x': 'horizOriginX',
6986 ideographic: 'ideographic',
6987 imagerendering: 'imageRendering',
6988 'image-rendering': 'imageRendering',
6989 in2: 'in2',
6990 in: 'in',
6991 inlist: 'inlist',
6992 intercept: 'intercept',
6993 k1: 'k1',
6994 k2: 'k2',
6995 k3: 'k3',
6996 k4: 'k4',
6997 k: 'k',
6998 kernelmatrix: 'kernelMatrix',
6999 kernelunitlength: 'kernelUnitLength',
7000 kerning: 'kerning',
7001 keypoints: 'keyPoints',
7002 keysplines: 'keySplines',
7003 keytimes: 'keyTimes',
7004 lengthadjust: 'lengthAdjust',
7005 letterspacing: 'letterSpacing',
7006 'letter-spacing': 'letterSpacing',
7007 lightingcolor: 'lightingColor',
7008 'lighting-color': 'lightingColor',
7009 limitingconeangle: 'limitingConeAngle',
7010 local: 'local',
7011 markerend: 'markerEnd',
7012 'marker-end': 'markerEnd',
7013 markerheight: 'markerHeight',
7014 markermid: 'markerMid',
7015 'marker-mid': 'markerMid',
7016 markerstart: 'markerStart',
7017 'marker-start': 'markerStart',
7018 markerunits: 'markerUnits',
7019 markerwidth: 'markerWidth',
7020 mask: 'mask',
7021 maskcontentunits: 'maskContentUnits',
7022 maskunits: 'maskUnits',
7023 mathematical: 'mathematical',
7024 mode: 'mode',
7025 numoctaves: 'numOctaves',
7026 offset: 'offset',
7027 opacity: 'opacity',
7028 operator: 'operator',
7029 order: 'order',
7030 orient: 'orient',
7031 orientation: 'orientation',
7032 origin: 'origin',
7033 overflow: 'overflow',
7034 overlineposition: 'overlinePosition',
7035 'overline-position': 'overlinePosition',
7036 overlinethickness: 'overlineThickness',
7037 'overline-thickness': 'overlineThickness',
7038 paintorder: 'paintOrder',
7039 'paint-order': 'paintOrder',
7040 panose1: 'panose1',
7041 'panose-1': 'panose1',
7042 pathlength: 'pathLength',
7043 patterncontentunits: 'patternContentUnits',
7044 patterntransform: 'patternTransform',
7045 patternunits: 'patternUnits',
7046 pointerevents: 'pointerEvents',
7047 'pointer-events': 'pointerEvents',
7048 points: 'points',
7049 pointsatx: 'pointsAtX',
7050 pointsaty: 'pointsAtY',
7051 pointsatz: 'pointsAtZ',
7052 prefix: 'prefix',
7053 preservealpha: 'preserveAlpha',
7054 preserveaspectratio: 'preserveAspectRatio',
7055 primitiveunits: 'primitiveUnits',
7056 property: 'property',
7057 r: 'r',
7058 radius: 'radius',
7059 refx: 'refX',
7060 refy: 'refY',
7061 renderingintent: 'renderingIntent',
7062 'rendering-intent': 'renderingIntent',
7063 repeatcount: 'repeatCount',
7064 repeatdur: 'repeatDur',
7065 requiredextensions: 'requiredExtensions',
7066 requiredfeatures: 'requiredFeatures',
7067 resource: 'resource',
7068 restart: 'restart',
7069 result: 'result',
7070 results: 'results',
7071 rotate: 'rotate',
7072 rx: 'rx',
7073 ry: 'ry',
7074 scale: 'scale',
7075 security: 'security',
7076 seed: 'seed',
7077 shaperendering: 'shapeRendering',
7078 'shape-rendering': 'shapeRendering',
7079 slope: 'slope',
7080 spacing: 'spacing',
7081 specularconstant: 'specularConstant',
7082 specularexponent: 'specularExponent',
7083 speed: 'speed',
7084 spreadmethod: 'spreadMethod',
7085 startoffset: 'startOffset',
7086 stddeviation: 'stdDeviation',
7087 stemh: 'stemh',
7088 stemv: 'stemv',
7089 stitchtiles: 'stitchTiles',
7090 stopcolor: 'stopColor',
7091 'stop-color': 'stopColor',
7092 stopopacity: 'stopOpacity',
7093 'stop-opacity': 'stopOpacity',
7094 strikethroughposition: 'strikethroughPosition',
7095 'strikethrough-position': 'strikethroughPosition',
7096 strikethroughthickness: 'strikethroughThickness',
7097 'strikethrough-thickness': 'strikethroughThickness',
7098 string: 'string',
7099 stroke: 'stroke',
7100 strokedasharray: 'strokeDasharray',
7101 'stroke-dasharray': 'strokeDasharray',
7102 strokedashoffset: 'strokeDashoffset',
7103 'stroke-dashoffset': 'strokeDashoffset',
7104 strokelinecap: 'strokeLinecap',
7105 'stroke-linecap': 'strokeLinecap',
7106 strokelinejoin: 'strokeLinejoin',
7107 'stroke-linejoin': 'strokeLinejoin',
7108 strokemiterlimit: 'strokeMiterlimit',
7109 'stroke-miterlimit': 'strokeMiterlimit',
7110 strokewidth: 'strokeWidth',
7111 'stroke-width': 'strokeWidth',
7112 strokeopacity: 'strokeOpacity',
7113 'stroke-opacity': 'strokeOpacity',
7114 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7115 suppresshydrationwarning: 'suppressHydrationWarning',
7116 surfacescale: 'surfaceScale',
7117 systemlanguage: 'systemLanguage',
7118 tablevalues: 'tableValues',
7119 targetx: 'targetX',
7120 targety: 'targetY',
7121 textanchor: 'textAnchor',
7122 'text-anchor': 'textAnchor',
7123 textdecoration: 'textDecoration',
7124 'text-decoration': 'textDecoration',
7125 textlength: 'textLength',
7126 textrendering: 'textRendering',
7127 'text-rendering': 'textRendering',
7128 to: 'to',
7129 transform: 'transform',
7130 typeof: 'typeof',
7131 u1: 'u1',
7132 u2: 'u2',
7133 underlineposition: 'underlinePosition',
7134 'underline-position': 'underlinePosition',
7135 underlinethickness: 'underlineThickness',
7136 'underline-thickness': 'underlineThickness',
7137 unicode: 'unicode',
7138 unicodebidi: 'unicodeBidi',
7139 'unicode-bidi': 'unicodeBidi',
7140 unicoderange: 'unicodeRange',
7141 'unicode-range': 'unicodeRange',
7142 unitsperem: 'unitsPerEm',
7143 'units-per-em': 'unitsPerEm',
7144 unselectable: 'unselectable',
7145 valphabetic: 'vAlphabetic',
7146 'v-alphabetic': 'vAlphabetic',
7147 values: 'values',
7148 vectoreffect: 'vectorEffect',
7149 'vector-effect': 'vectorEffect',
7150 version: 'version',
7151 vertadvy: 'vertAdvY',
7152 'vert-adv-y': 'vertAdvY',
7153 vertoriginx: 'vertOriginX',
7154 'vert-origin-x': 'vertOriginX',
7155 vertoriginy: 'vertOriginY',
7156 'vert-origin-y': 'vertOriginY',
7157 vhanging: 'vHanging',
7158 'v-hanging': 'vHanging',
7159 videographic: 'vIdeographic',
7160 'v-ideographic': 'vIdeographic',
7161 viewbox: 'viewBox',
7162 viewtarget: 'viewTarget',
7163 visibility: 'visibility',
7164 vmathematical: 'vMathematical',
7165 'v-mathematical': 'vMathematical',
7166 vocab: 'vocab',
7167 widths: 'widths',
7168 wordspacing: 'wordSpacing',
7169 'word-spacing': 'wordSpacing',
7170 writingmode: 'writingMode',
7171 'writing-mode': 'writingMode',
7172 x1: 'x1',
7173 x2: 'x2',
7174 x: 'x',
7175 xchannelselector: 'xChannelSelector',
7176 xheight: 'xHeight',
7177 'x-height': 'xHeight',
7178 xlinkactuate: 'xlinkActuate',
7179 'xlink:actuate': 'xlinkActuate',
7180 xlinkarcrole: 'xlinkArcrole',
7181 'xlink:arcrole': 'xlinkArcrole',
7182 xlinkhref: 'xlinkHref',
7183 'xlink:href': 'xlinkHref',
7184 xlinkrole: 'xlinkRole',
7185 'xlink:role': 'xlinkRole',
7186 xlinkshow: 'xlinkShow',
7187 'xlink:show': 'xlinkShow',
7188 xlinktitle: 'xlinkTitle',
7189 'xlink:title': 'xlinkTitle',
7190 xlinktype: 'xlinkType',
7191 'xlink:type': 'xlinkType',
7192 xmlbase: 'xmlBase',
7193 'xml:base': 'xmlBase',
7194 xmllang: 'xmlLang',
7195 'xml:lang': 'xmlLang',
7196 xmlns: 'xmlns',
7197 'xml:space': 'xmlSpace',
7198 xmlnsxlink: 'xmlnsXlink',
7199 'xmlns:xlink': 'xmlnsXlink',
7200 xmlspace: 'xmlSpace',
7201 y1: 'y1',
7202 y2: 'y2',
7203 y: 'y',
7204 ychannelselector: 'yChannelSelector',
7205 z: 'z',
7206 zoomandpan: 'zoomAndPan'
7207};
7208
7209var ariaProperties = {
7210 'aria-current': 0,
7211 // state
7212 'aria-details': 0,
7213 'aria-disabled': 0,
7214 // state
7215 'aria-hidden': 0,
7216 // state
7217 'aria-invalid': 0,
7218 // state
7219 'aria-keyshortcuts': 0,
7220 'aria-label': 0,
7221 'aria-roledescription': 0,
7222 // Widget Attributes
7223 'aria-autocomplete': 0,
7224 'aria-checked': 0,
7225 'aria-expanded': 0,
7226 'aria-haspopup': 0,
7227 'aria-level': 0,
7228 'aria-modal': 0,
7229 'aria-multiline': 0,
7230 'aria-multiselectable': 0,
7231 'aria-orientation': 0,
7232 'aria-placeholder': 0,
7233 'aria-pressed': 0,
7234 'aria-readonly': 0,
7235 'aria-required': 0,
7236 'aria-selected': 0,
7237 'aria-sort': 0,
7238 'aria-valuemax': 0,
7239 'aria-valuemin': 0,
7240 'aria-valuenow': 0,
7241 'aria-valuetext': 0,
7242 // Live Region Attributes
7243 'aria-atomic': 0,
7244 'aria-busy': 0,
7245 'aria-live': 0,
7246 'aria-relevant': 0,
7247 // Drag-and-Drop Attributes
7248 'aria-dropeffect': 0,
7249 'aria-grabbed': 0,
7250 // Relationship Attributes
7251 'aria-activedescendant': 0,
7252 'aria-colcount': 0,
7253 'aria-colindex': 0,
7254 'aria-colspan': 0,
7255 'aria-controls': 0,
7256 'aria-describedby': 0,
7257 'aria-errormessage': 0,
7258 'aria-flowto': 0,
7259 'aria-labelledby': 0,
7260 'aria-owns': 0,
7261 'aria-posinset': 0,
7262 'aria-rowcount': 0,
7263 'aria-rowindex': 0,
7264 'aria-rowspan': 0,
7265 'aria-setsize': 0
7266};
7267
7268var warnedProperties = {};
7269var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7270var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7271var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
7272
7273function validateProperty(tagName, name) {
7274 if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
7275 return true;
7276 }
7277
7278 if (rARIACamel.test(name)) {
7279 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7280 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7281 // DOM properties, then it is an invalid aria-* attribute.
7282
7283 if (correctName == null) {
7284 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7285 warnedProperties[name] = true;
7286 return true;
7287 } // aria-* attributes should be lowercase; suggest the lowercase version.
7288
7289
7290 if (name !== correctName) {
7291 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7292 warnedProperties[name] = true;
7293 return true;
7294 }
7295 }
7296
7297 if (rARIA.test(name)) {
7298 var lowerCasedName = name.toLowerCase();
7299 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7300 // DOM properties, then it is an invalid aria-* attribute.
7301
7302 if (standardName == null) {
7303 warnedProperties[name] = true;
7304 return false;
7305 } // aria-* attributes should be lowercase; suggest the lowercase version.
7306
7307
7308 if (name !== standardName) {
7309 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7310 warnedProperties[name] = true;
7311 return true;
7312 }
7313 }
7314
7315 return true;
7316}
7317
7318function warnInvalidARIAProps(type, props) {
7319 var invalidProps = [];
7320
7321 for (var key in props) {
7322 var isValid = validateProperty(type, key);
7323
7324 if (!isValid) {
7325 invalidProps.push(key);
7326 }
7327 }
7328
7329 var unknownPropString = invalidProps.map(function (prop) {
7330 return '`' + prop + '`';
7331 }).join(', ');
7332
7333 if (invalidProps.length === 1) {
7334 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7335 } else if (invalidProps.length > 1) {
7336 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7337 }
7338}
7339
7340function validateProperties(type, props) {
7341 if (isCustomComponent(type, props)) {
7342 return;
7343 }
7344
7345 warnInvalidARIAProps(type, props);
7346}
7347
7348var didWarnValueNull = false;
7349function validateProperties$1(type, props) {
7350 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7351 return;
7352 }
7353
7354 if (props != null && props.value === null && !didWarnValueNull) {
7355 didWarnValueNull = true;
7356
7357 if (type === 'select' && props.multiple) {
7358 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);
7359 } else {
7360 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);
7361 }
7362 }
7363}
7364
7365var validateProperty$1 = function () {};
7366
7367{
7368 var warnedProperties$1 = {};
7369 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7370 var EVENT_NAME_REGEX = /^on./;
7371 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7372 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7373 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7374
7375 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7376 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7377 return true;
7378 }
7379
7380 var lowerCasedName = name.toLowerCase();
7381
7382 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7383 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.');
7384 warnedProperties$1[name] = true;
7385 return true;
7386 } // We can't rely on the event system being injected on the server.
7387
7388
7389 if (canUseEventSystem) {
7390 if (registrationNameModules.hasOwnProperty(name)) {
7391 return true;
7392 }
7393
7394 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7395
7396 if (registrationName != null) {
7397 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7398 warnedProperties$1[name] = true;
7399 return true;
7400 }
7401
7402 if (EVENT_NAME_REGEX.test(name)) {
7403 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7404 warnedProperties$1[name] = true;
7405 return true;
7406 }
7407 } else if (EVENT_NAME_REGEX.test(name)) {
7408 // If no event plugins have been injected, we are in a server environment.
7409 // So we can't tell if the event name is correct for sure, but we can filter
7410 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7411 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7412 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7413 }
7414
7415 warnedProperties$1[name] = true;
7416 return true;
7417 } // Let the ARIA attribute hook validate ARIA attributes
7418
7419
7420 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7421 return true;
7422 }
7423
7424 if (lowerCasedName === 'innerhtml') {
7425 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7426 warnedProperties$1[name] = true;
7427 return true;
7428 }
7429
7430 if (lowerCasedName === 'aria') {
7431 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7432 warnedProperties$1[name] = true;
7433 return true;
7434 }
7435
7436 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7437 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7438 warnedProperties$1[name] = true;
7439 return true;
7440 }
7441
7442 if (typeof value === 'number' && isNaN(value)) {
7443 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7444 warnedProperties$1[name] = true;
7445 return true;
7446 }
7447
7448 var propertyInfo = getPropertyInfo(name);
7449 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
7450
7451 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7452 var standardName = possibleStandardNames[lowerCasedName];
7453
7454 if (standardName !== name) {
7455 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7456 warnedProperties$1[name] = true;
7457 return true;
7458 }
7459 } else if (!isReserved && name !== lowerCasedName) {
7460 // Unknown attributes should have lowercase casing since that's how they
7461 // will be cased anyway with server rendering.
7462 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);
7463 warnedProperties$1[name] = true;
7464 return true;
7465 }
7466
7467 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7468 if (value) {
7469 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);
7470 } else {
7471 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);
7472 }
7473
7474 warnedProperties$1[name] = true;
7475 return true;
7476 } // Now that we've validated casing, do not validate
7477 // data types for reserved props
7478
7479
7480 if (isReserved) {
7481 return true;
7482 } // Warn when a known attribute is a bad type
7483
7484
7485 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7486 warnedProperties$1[name] = true;
7487 return false;
7488 } // Warn when passing the strings 'false' or 'true' into a boolean prop
7489
7490
7491 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7492 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);
7493 warnedProperties$1[name] = true;
7494 return true;
7495 }
7496
7497 return true;
7498 };
7499}
7500
7501var warnUnknownProperties = function (type, props, canUseEventSystem) {
7502 var unknownProps = [];
7503
7504 for (var key in props) {
7505 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7506
7507 if (!isValid) {
7508 unknownProps.push(key);
7509 }
7510 }
7511
7512 var unknownPropString = unknownProps.map(function (prop) {
7513 return '`' + prop + '`';
7514 }).join(', ');
7515
7516 if (unknownProps.length === 1) {
7517 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);
7518 } else if (unknownProps.length > 1) {
7519 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);
7520 }
7521};
7522
7523function validateProperties$2(type, props, canUseEventSystem) {
7524 if (isCustomComponent(type, props)) {
7525 return;
7526 }
7527
7528 warnUnknownProperties(type, props, canUseEventSystem);
7529}
7530
7531// TODO: direct imports like some-package/src/* are bad. Fix me.
7532var didWarnInvalidHydration = false;
7533var didWarnShadyDOM = false;
7534var didWarnScriptTags = false;
7535var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7536var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7537var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7538var AUTOFOCUS = 'autoFocus';
7539var CHILDREN = 'children';
7540var STYLE$1 = 'style';
7541var HTML = '__html';
7542var LISTENERS = 'listeners';
7543var HTML_NAMESPACE = Namespaces.html;
7544var warnedUnknownTags;
7545var suppressHydrationWarning;
7546var validatePropertiesInDevelopment;
7547var warnForTextDifference;
7548var warnForPropDifference;
7549var warnForExtraAttributes;
7550var warnForInvalidEventListener;
7551var canDiffStyleForHydrationWarning;
7552var normalizeMarkupForTextOrAttribute;
7553var normalizeHTML;
7554
7555{
7556 warnedUnknownTags = {
7557 // Chrome is the only major browser not shipping <time>. But as of July
7558 // 2017 it intends to ship it due to widespread usage. We intentionally
7559 // *don't* warn for <time> even if it's unrecognized by Chrome because
7560 // it soon will be, and many apps have been using it anyway.
7561 time: true,
7562 // There are working polyfills for <dialog>. Let people use it.
7563 dialog: true,
7564 // Electron ships a custom <webview> tag to display external web content in
7565 // an isolated frame and process.
7566 // This tag is not present in non Electron environments such as JSDom which
7567 // is often used for testing purposes.
7568 // @see https://electronjs.org/docs/api/webview-tag
7569 webview: true
7570 };
7571
7572 validatePropertiesInDevelopment = function (type, props) {
7573 validateProperties(type, props);
7574 validateProperties$1(type, props);
7575 validateProperties$2(type, props,
7576 /* canUseEventSystem */
7577 true);
7578 }; // IE 11 parses & normalizes the style attribute as opposed to other
7579 // browsers. It adds spaces and sorts the properties in some
7580 // non-alphabetical order. Handling that would require sorting CSS
7581 // properties in the client & server versions or applying
7582 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7583 // normalized. Since it only affects IE, we're skipping style warnings
7584 // in that browser completely in favor of doing all that work.
7585 // See https://github.com/facebook/react/issues/11807
7586
7587
7588 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
7589 // It also can turn \u0000 into \uFFFD inside attributes.
7590 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7591 // If we have a mismatch, it might be caused by that.
7592 // We will still patch up in this case but not fire the warning.
7593
7594 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7595 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7596
7597 normalizeMarkupForTextOrAttribute = function (markup) {
7598 var markupString = typeof markup === 'string' ? markup : '' + markup;
7599 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7600 };
7601
7602 warnForTextDifference = function (serverText, clientText) {
7603 if (didWarnInvalidHydration) {
7604 return;
7605 }
7606
7607 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7608 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7609
7610 if (normalizedServerText === normalizedClientText) {
7611 return;
7612 }
7613
7614 didWarnInvalidHydration = true;
7615 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7616 };
7617
7618 warnForPropDifference = function (propName, serverValue, clientValue) {
7619 if (didWarnInvalidHydration) {
7620 return;
7621 }
7622
7623 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7624 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7625
7626 if (normalizedServerValue === normalizedClientValue) {
7627 return;
7628 }
7629
7630 didWarnInvalidHydration = true;
7631 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7632 };
7633
7634 warnForExtraAttributes = function (attributeNames) {
7635 if (didWarnInvalidHydration) {
7636 return;
7637 }
7638
7639 didWarnInvalidHydration = true;
7640 var names = [];
7641 attributeNames.forEach(function (name) {
7642 names.push(name);
7643 });
7644 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7645 };
7646
7647 warnForInvalidEventListener = function (registrationName, listener) {
7648 if (listener === false) {
7649 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);
7650 } else {
7651 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7652 }
7653 }; // Parse the HTML and read it back to normalize the HTML string so that it
7654 // can be used for comparison.
7655
7656
7657 normalizeHTML = function (parent, html) {
7658 // We could have created a separate document here to avoid
7659 // re-initializing custom elements if they exist. But this breaks
7660 // how <noscript> is being handled. So we use the same document.
7661 // See the discussion in https://github.com/facebook/react/pull/11157.
7662 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7663 testElement.innerHTML = html;
7664 return testElement.innerHTML;
7665 };
7666}
7667
7668function ensureListeningTo(rootContainerElement, registrationName) {
7669 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7670 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7671 listenTo(registrationName, doc);
7672}
7673
7674function getOwnerDocumentFromRootContainer(rootContainerElement) {
7675 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7676}
7677
7678function noop() {}
7679
7680function trapClickOnNonInteractiveElement(node) {
7681 // Mobile Safari does not fire properly bubble click events on
7682 // non-interactive elements, which means delegated click listeners do not
7683 // fire. The workaround for this bug involves attaching an empty click
7684 // listener on the target node.
7685 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7686 // Just set it using the onclick property so that we don't have to manage any
7687 // bookkeeping for it. Not sure if we need to clear it when the listener is
7688 // removed.
7689 // TODO: Only do this for the relevant Safaris maybe?
7690 node.onclick = noop;
7691}
7692
7693function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7694 for (var propKey in nextProps) {
7695 if (!nextProps.hasOwnProperty(propKey)) {
7696 continue;
7697 }
7698
7699 var nextProp = nextProps[propKey];
7700
7701 if (propKey === STYLE$1) {
7702 {
7703 if (nextProp) {
7704 // Freeze the next style object so that we can assume it won't be
7705 // mutated. We have already warned for this in the past.
7706 Object.freeze(nextProp);
7707 }
7708 } // Relies on `updateStylesByID` not mutating `styleUpdates`.
7709
7710
7711 setValueForStyles(domElement, nextProp);
7712 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7713 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7714
7715 if (nextHtml != null) {
7716 setInnerHTML(domElement, nextHtml);
7717 }
7718 } else if (propKey === CHILDREN) {
7719 if (typeof nextProp === 'string') {
7720 // Avoid setting initial textContent when the text is empty. In IE11 setting
7721 // textContent on a <textarea> will cause the placeholder to not
7722 // show within the <textarea> until it has been focused and blurred again.
7723 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7724 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7725
7726 if (canSetTextContent) {
7727 setTextContent(domElement, nextProp);
7728 }
7729 } else if (typeof nextProp === 'number') {
7730 setTextContent(domElement, '' + nextProp);
7731 }
7732 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
7733 } else if (propKey === AUTOFOCUS) {// We polyfill it separately on the client during commit.
7734 // We could have excluded it in the property list instead of
7735 // adding a special case here, but then it wouldn't be emitted
7736 // on server rendering (but we *do* want to emit it in SSR).
7737 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7738 if (nextProp != null) {
7739 if (true && typeof nextProp !== 'function') {
7740 warnForInvalidEventListener(propKey, nextProp);
7741 }
7742
7743 ensureListeningTo(rootContainerElement, propKey);
7744 }
7745 } else if (nextProp != null) {
7746 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7747 }
7748 }
7749}
7750
7751function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7752 // TODO: Handle wasCustomComponentTag
7753 for (var i = 0; i < updatePayload.length; i += 2) {
7754 var propKey = updatePayload[i];
7755 var propValue = updatePayload[i + 1];
7756
7757 if (propKey === STYLE$1) {
7758 setValueForStyles(domElement, propValue);
7759 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7760 setInnerHTML(domElement, propValue);
7761 } else if (propKey === CHILDREN) {
7762 setTextContent(domElement, propValue);
7763 } else {
7764 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7765 }
7766 }
7767}
7768
7769function createElement(type, props, rootContainerElement, parentNamespace) {
7770 var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
7771 // tags get no namespace.
7772
7773 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7774 var domElement;
7775 var namespaceURI = parentNamespace;
7776
7777 if (namespaceURI === HTML_NAMESPACE) {
7778 namespaceURI = getIntrinsicNamespace(type);
7779 }
7780
7781 if (namespaceURI === HTML_NAMESPACE) {
7782 {
7783 isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
7784 // allow <SVG> or <mATH>.
7785
7786 !(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;
7787 }
7788
7789 if (type === 'script') {
7790 // Create the script via .innerHTML so its "parser-inserted" flag is
7791 // set to true and it does not execute
7792 var div = ownerDocument.createElement('div');
7793
7794 {
7795 if (enableTrustedTypesIntegration && !didWarnScriptTags) {
7796 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).');
7797 didWarnScriptTags = true;
7798 }
7799 }
7800
7801 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7802 // This is guaranteed to yield a script element.
7803
7804 var firstChild = div.firstChild;
7805 domElement = div.removeChild(firstChild);
7806 } else if (typeof props.is === 'string') {
7807 // $FlowIssue `createElement` should be updated for Web Components
7808 domElement = ownerDocument.createElement(type, {
7809 is: props.is
7810 });
7811 } else {
7812 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7813 // See discussion in https://github.com/facebook/react/pull/6896
7814 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7815 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
7816 // attributes on `select`s needs to be added before `option`s are inserted.
7817 // This prevents:
7818 // - a bug where the `select` does not scroll to the correct option because singular
7819 // `select` elements automatically pick the first item #13222
7820 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
7821 // See https://github.com/facebook/react/issues/13222
7822 // and https://github.com/facebook/react/issues/14239
7823
7824 if (type === 'select') {
7825 var node = domElement;
7826
7827 if (props.multiple) {
7828 node.multiple = true;
7829 } else if (props.size) {
7830 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
7831 // it is possible that no option is selected.
7832 //
7833 // This is only necessary when a select in "single selection mode".
7834 node.size = props.size;
7835 }
7836 }
7837 }
7838 } else {
7839 domElement = ownerDocument.createElementNS(namespaceURI, type);
7840 }
7841
7842 {
7843 if (namespaceURI === HTML_NAMESPACE) {
7844 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7845 warnedUnknownTags[type] = true;
7846 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);
7847 }
7848 }
7849 }
7850
7851 return domElement;
7852}
7853function createTextNode(text, rootContainerElement) {
7854 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7855}
7856function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7857 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7858
7859 {
7860 validatePropertiesInDevelopment(tag, rawProps);
7861
7862 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
7863 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
7864 didWarnShadyDOM = true;
7865 }
7866 } // TODO: Make sure that we check isMounted before firing any of these events.
7867
7868
7869 var props;
7870
7871 switch (tag) {
7872 case 'iframe':
7873 case 'object':
7874 case 'embed':
7875 trapBubbledEvent(TOP_LOAD, domElement);
7876 props = rawProps;
7877 break;
7878
7879 case 'video':
7880 case 'audio':
7881 // Create listener for each media event
7882 for (var i = 0; i < mediaEventTypes.length; i++) {
7883 trapBubbledEvent(mediaEventTypes[i], domElement);
7884 }
7885
7886 props = rawProps;
7887 break;
7888
7889 case 'source':
7890 trapBubbledEvent(TOP_ERROR, domElement);
7891 props = rawProps;
7892 break;
7893
7894 case 'img':
7895 case 'image':
7896 case 'link':
7897 trapBubbledEvent(TOP_ERROR, domElement);
7898 trapBubbledEvent(TOP_LOAD, domElement);
7899 props = rawProps;
7900 break;
7901
7902 case 'form':
7903 trapBubbledEvent(TOP_RESET, domElement);
7904 trapBubbledEvent(TOP_SUBMIT, domElement);
7905 props = rawProps;
7906 break;
7907
7908 case 'details':
7909 trapBubbledEvent(TOP_TOGGLE, domElement);
7910 props = rawProps;
7911 break;
7912
7913 case 'input':
7914 initWrapperState(domElement, rawProps);
7915 props = getHostProps(domElement, rawProps);
7916 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7917 // to onChange. Even if there is no listener.
7918
7919 ensureListeningTo(rootContainerElement, 'onChange');
7920 break;
7921
7922 case 'option':
7923 validateProps(domElement, rawProps);
7924 props = getHostProps$1(domElement, rawProps);
7925 break;
7926
7927 case 'select':
7928 initWrapperState$1(domElement, rawProps);
7929 props = getHostProps$2(domElement, rawProps);
7930 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7931 // to onChange. Even if there is no listener.
7932
7933 ensureListeningTo(rootContainerElement, 'onChange');
7934 break;
7935
7936 case 'textarea':
7937 initWrapperState$2(domElement, rawProps);
7938 props = getHostProps$3(domElement, rawProps);
7939 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
7940 // to onChange. Even if there is no listener.
7941
7942 ensureListeningTo(rootContainerElement, 'onChange');
7943 break;
7944
7945 default:
7946 props = rawProps;
7947 }
7948
7949 assertValidProps(tag, props);
7950 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
7951
7952 switch (tag) {
7953 case 'input':
7954 // TODO: Make sure we check if this is still unmounted or do any clean
7955 // up necessary since we never stop tracking anymore.
7956 track(domElement);
7957 postMountWrapper(domElement, rawProps, false);
7958 break;
7959
7960 case 'textarea':
7961 // TODO: Make sure we check if this is still unmounted or do any clean
7962 // up necessary since we never stop tracking anymore.
7963 track(domElement);
7964 postMountWrapper$3(domElement, rawProps);
7965 break;
7966
7967 case 'option':
7968 postMountWrapper$1(domElement, rawProps);
7969 break;
7970
7971 case 'select':
7972 postMountWrapper$2(domElement, rawProps);
7973 break;
7974
7975 default:
7976 if (typeof props.onClick === 'function') {
7977 // TODO: This cast may not be sound for SVG, MathML or custom elements.
7978 trapClickOnNonInteractiveElement(domElement);
7979 }
7980
7981 break;
7982 }
7983} // Calculate the diff between the two objects.
7984
7985function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
7986 {
7987 validatePropertiesInDevelopment(tag, nextRawProps);
7988 }
7989
7990 var updatePayload = null;
7991 var lastProps;
7992 var nextProps;
7993
7994 switch (tag) {
7995 case 'input':
7996 lastProps = getHostProps(domElement, lastRawProps);
7997 nextProps = getHostProps(domElement, nextRawProps);
7998 updatePayload = [];
7999 break;
8000
8001 case 'option':
8002 lastProps = getHostProps$1(domElement, lastRawProps);
8003 nextProps = getHostProps$1(domElement, nextRawProps);
8004 updatePayload = [];
8005 break;
8006
8007 case 'select':
8008 lastProps = getHostProps$2(domElement, lastRawProps);
8009 nextProps = getHostProps$2(domElement, nextRawProps);
8010 updatePayload = [];
8011 break;
8012
8013 case 'textarea':
8014 lastProps = getHostProps$3(domElement, lastRawProps);
8015 nextProps = getHostProps$3(domElement, nextRawProps);
8016 updatePayload = [];
8017 break;
8018
8019 default:
8020 lastProps = lastRawProps;
8021 nextProps = nextRawProps;
8022
8023 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
8024 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8025 trapClickOnNonInteractiveElement(domElement);
8026 }
8027
8028 break;
8029 }
8030
8031 assertValidProps(tag, nextProps);
8032 var propKey;
8033 var styleName;
8034 var styleUpdates = null;
8035
8036 for (propKey in lastProps) {
8037 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
8038 continue;
8039 }
8040
8041 if (propKey === STYLE$1) {
8042 var lastStyle = lastProps[propKey];
8043
8044 for (styleName in lastStyle) {
8045 if (lastStyle.hasOwnProperty(styleName)) {
8046 if (!styleUpdates) {
8047 styleUpdates = {};
8048 }
8049
8050 styleUpdates[styleName] = '';
8051 }
8052 }
8053 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {// Noop. This is handled by the clear text mechanism.
8054 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8055 } else if (propKey === AUTOFOCUS) {// Noop. It doesn't work on updates anyway.
8056 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8057 // This is a special case. If any listener updates we need to ensure
8058 // that the "current" fiber pointer gets updated so we need a commit
8059 // to update this element.
8060 if (!updatePayload) {
8061 updatePayload = [];
8062 }
8063 } else {
8064 // For all other deleted properties we add it to the queue. We use
8065 // the whitelist in the commit phase instead.
8066 (updatePayload = updatePayload || []).push(propKey, null);
8067 }
8068 }
8069
8070 for (propKey in nextProps) {
8071 var nextProp = nextProps[propKey];
8072 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
8073
8074 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
8075 continue;
8076 }
8077
8078 if (propKey === STYLE$1) {
8079 {
8080 if (nextProp) {
8081 // Freeze the next style object so that we can assume it won't be
8082 // mutated. We have already warned for this in the past.
8083 Object.freeze(nextProp);
8084 }
8085 }
8086
8087 if (lastProp) {
8088 // Unset styles on `lastProp` but not on `nextProp`.
8089 for (styleName in lastProp) {
8090 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
8091 if (!styleUpdates) {
8092 styleUpdates = {};
8093 }
8094
8095 styleUpdates[styleName] = '';
8096 }
8097 } // Update styles that changed since `lastProp`.
8098
8099
8100 for (styleName in nextProp) {
8101 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8102 if (!styleUpdates) {
8103 styleUpdates = {};
8104 }
8105
8106 styleUpdates[styleName] = nextProp[styleName];
8107 }
8108 }
8109 } else {
8110 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8111 if (!styleUpdates) {
8112 if (!updatePayload) {
8113 updatePayload = [];
8114 }
8115
8116 updatePayload.push(propKey, styleUpdates);
8117 }
8118
8119 styleUpdates = nextProp;
8120 }
8121 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8122 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8123 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8124
8125 if (nextHtml != null) {
8126 if (lastHtml !== nextHtml) {
8127 (updatePayload = updatePayload || []).push(propKey, toStringOrTrustedType(nextHtml));
8128 }
8129 } else {// TODO: It might be too late to clear this if we have children
8130 // inserted already.
8131 }
8132 } else if (propKey === CHILDREN) {
8133 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8134 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8135 }
8136 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8137 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8138 if (nextProp != null) {
8139 // We eagerly listen to this even though we haven't committed yet.
8140 if (true && typeof nextProp !== 'function') {
8141 warnForInvalidEventListener(propKey, nextProp);
8142 }
8143
8144 ensureListeningTo(rootContainerElement, propKey);
8145 }
8146
8147 if (!updatePayload && lastProp !== nextProp) {
8148 // This is a special case. If any listener updates we need to ensure
8149 // that the "current" props pointer gets updated so we need a commit
8150 // to update this element.
8151 updatePayload = [];
8152 }
8153 } else {
8154 // For any other property we always add it to the queue and then we
8155 // filter it out using the whitelist during the commit.
8156 (updatePayload = updatePayload || []).push(propKey, nextProp);
8157 }
8158 }
8159
8160 if (styleUpdates) {
8161 {
8162 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8163 }
8164
8165 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8166 }
8167
8168 return updatePayload;
8169} // Apply the diff.
8170
8171function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8172 // Update checked *before* name.
8173 // In the middle of an update, it is possible to have multiple checked.
8174 // When a checked radio tries to change name, browser makes another radio's checked false.
8175 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8176 updateChecked(domElement, nextRawProps);
8177 }
8178
8179 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8180 var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
8181
8182 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
8183 // changed.
8184
8185 switch (tag) {
8186 case 'input':
8187 // Update the wrapper around inputs *after* updating props. This has to
8188 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8189 // raise warnings and prevent the new value from being assigned.
8190 updateWrapper(domElement, nextRawProps);
8191 break;
8192
8193 case 'textarea':
8194 updateWrapper$1(domElement, nextRawProps);
8195 break;
8196
8197 case 'select':
8198 // <select> value update needs to occur after <option> children
8199 // reconciliation
8200 postUpdateWrapper(domElement, nextRawProps);
8201 break;
8202 }
8203}
8204
8205function getPossibleStandardName(propName) {
8206 {
8207 var lowerCasedName = propName.toLowerCase();
8208
8209 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8210 return null;
8211 }
8212
8213 return possibleStandardNames[lowerCasedName] || null;
8214 }
8215
8216 return null;
8217}
8218
8219function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8220 var isCustomComponentTag;
8221 var extraAttributeNames;
8222
8223 {
8224 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8225 isCustomComponentTag = isCustomComponent(tag, rawProps);
8226 validatePropertiesInDevelopment(tag, rawProps);
8227
8228 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8229 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8230 didWarnShadyDOM = true;
8231 }
8232 } // TODO: Make sure that we check isMounted before firing any of these events.
8233
8234
8235 switch (tag) {
8236 case 'iframe':
8237 case 'object':
8238 case 'embed':
8239 trapBubbledEvent(TOP_LOAD, domElement);
8240 break;
8241
8242 case 'video':
8243 case 'audio':
8244 // Create listener for each media event
8245 for (var i = 0; i < mediaEventTypes.length; i++) {
8246 trapBubbledEvent(mediaEventTypes[i], domElement);
8247 }
8248
8249 break;
8250
8251 case 'source':
8252 trapBubbledEvent(TOP_ERROR, domElement);
8253 break;
8254
8255 case 'img':
8256 case 'image':
8257 case 'link':
8258 trapBubbledEvent(TOP_ERROR, domElement);
8259 trapBubbledEvent(TOP_LOAD, domElement);
8260 break;
8261
8262 case 'form':
8263 trapBubbledEvent(TOP_RESET, domElement);
8264 trapBubbledEvent(TOP_SUBMIT, domElement);
8265 break;
8266
8267 case 'details':
8268 trapBubbledEvent(TOP_TOGGLE, domElement);
8269 break;
8270
8271 case 'input':
8272 initWrapperState(domElement, rawProps);
8273 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8274 // to onChange. Even if there is no listener.
8275
8276 ensureListeningTo(rootContainerElement, 'onChange');
8277 break;
8278
8279 case 'option':
8280 validateProps(domElement, rawProps);
8281 break;
8282
8283 case 'select':
8284 initWrapperState$1(domElement, rawProps);
8285 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8286 // to onChange. Even if there is no listener.
8287
8288 ensureListeningTo(rootContainerElement, 'onChange');
8289 break;
8290
8291 case 'textarea':
8292 initWrapperState$2(domElement, rawProps);
8293 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8294 // to onChange. Even if there is no listener.
8295
8296 ensureListeningTo(rootContainerElement, 'onChange');
8297 break;
8298 }
8299
8300 assertValidProps(tag, rawProps);
8301
8302 {
8303 extraAttributeNames = new Set();
8304 var attributes = domElement.attributes;
8305
8306 for (var _i = 0; _i < attributes.length; _i++) {
8307 var name = attributes[_i].name.toLowerCase();
8308
8309 switch (name) {
8310 // Built-in SSR attribute is whitelisted
8311 case 'data-reactroot':
8312 break;
8313 // Controlled attributes are not validated
8314 // TODO: Only ignore them on controlled tags.
8315
8316 case 'value':
8317 break;
8318
8319 case 'checked':
8320 break;
8321
8322 case 'selected':
8323 break;
8324
8325 default:
8326 // Intentionally use the original name.
8327 // See discussion in https://github.com/facebook/react/pull/10676.
8328 extraAttributeNames.add(attributes[_i].name);
8329 }
8330 }
8331 }
8332
8333 var updatePayload = null;
8334
8335 for (var propKey in rawProps) {
8336 if (!rawProps.hasOwnProperty(propKey)) {
8337 continue;
8338 }
8339
8340 var nextProp = rawProps[propKey];
8341
8342 if (propKey === CHILDREN) {
8343 // For text content children we compare against textContent. This
8344 // might match additional HTML that is hidden when we read it using
8345 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8346 // satisfies our requirement. Our requirement is not to produce perfect
8347 // HTML and attributes. Ideally we should preserve structure but it's
8348 // ok not to if the visible content is still enough to indicate what
8349 // even listeners these nodes might be wired up to.
8350 // TODO: Warn if there is more than a single textNode as a child.
8351 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8352 if (typeof nextProp === 'string') {
8353 if (domElement.textContent !== nextProp) {
8354 if (true && !suppressHydrationWarning) {
8355 warnForTextDifference(domElement.textContent, nextProp);
8356 }
8357
8358 updatePayload = [CHILDREN, nextProp];
8359 }
8360 } else if (typeof nextProp === 'number') {
8361 if (domElement.textContent !== '' + nextProp) {
8362 if (true && !suppressHydrationWarning) {
8363 warnForTextDifference(domElement.textContent, nextProp);
8364 }
8365
8366 updatePayload = [CHILDREN, '' + nextProp];
8367 }
8368 }
8369 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8370 if (nextProp != null) {
8371 if (true && typeof nextProp !== 'function') {
8372 warnForInvalidEventListener(propKey, nextProp);
8373 }
8374
8375 ensureListeningTo(rootContainerElement, propKey);
8376 }
8377 } else if (true && // Convince Flow we've calculated it (it's DEV-only in this method.)
8378 typeof isCustomComponentTag === 'boolean') {
8379 // Validate that the properties correspond to their expected values.
8380 var serverValue = void 0;
8381 var propertyInfo = getPropertyInfo(propKey);
8382
8383 if (suppressHydrationWarning) {// Don't bother comparing. We're ignoring all these warnings.
8384 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 || // Controlled attributes are not validated
8385 // TODO: Only ignore them on controlled tags.
8386 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {// Noop
8387 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8388 var serverHTML = domElement.innerHTML;
8389 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8390 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8391
8392 if (expectedHTML !== serverHTML) {
8393 warnForPropDifference(propKey, serverHTML, expectedHTML);
8394 }
8395 } else if (propKey === STYLE$1) {
8396 // $FlowFixMe - Should be inferred as not undefined.
8397 extraAttributeNames.delete(propKey);
8398
8399 if (canDiffStyleForHydrationWarning) {
8400 var expectedStyle = createDangerousStringForStyles(nextProp);
8401 serverValue = domElement.getAttribute('style');
8402
8403 if (expectedStyle !== serverValue) {
8404 warnForPropDifference(propKey, serverValue, expectedStyle);
8405 }
8406 }
8407 } else if (isCustomComponentTag) {
8408 // $FlowFixMe - Should be inferred as not undefined.
8409 extraAttributeNames.delete(propKey.toLowerCase());
8410 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8411
8412 if (nextProp !== serverValue) {
8413 warnForPropDifference(propKey, serverValue, nextProp);
8414 }
8415 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8416 var isMismatchDueToBadCasing = false;
8417
8418 if (propertyInfo !== null) {
8419 // $FlowFixMe - Should be inferred as not undefined.
8420 extraAttributeNames.delete(propertyInfo.attributeName);
8421 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8422 } else {
8423 var ownNamespace = parentNamespace;
8424
8425 if (ownNamespace === HTML_NAMESPACE) {
8426 ownNamespace = getIntrinsicNamespace(tag);
8427 }
8428
8429 if (ownNamespace === HTML_NAMESPACE) {
8430 // $FlowFixMe - Should be inferred as not undefined.
8431 extraAttributeNames.delete(propKey.toLowerCase());
8432 } else {
8433 var standardName = getPossibleStandardName(propKey);
8434
8435 if (standardName !== null && standardName !== propKey) {
8436 // If an SVG prop is supplied with bad casing, it will
8437 // be successfully parsed from HTML, but will produce a mismatch
8438 // (and would be incorrectly rendered on the client).
8439 // However, we already warn about bad casing elsewhere.
8440 // So we'll skip the misleading extra mismatch warning in this case.
8441 isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
8442
8443 extraAttributeNames.delete(standardName);
8444 } // $FlowFixMe - Should be inferred as not undefined.
8445
8446
8447 extraAttributeNames.delete(propKey);
8448 }
8449
8450 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8451 }
8452
8453 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8454 warnForPropDifference(propKey, serverValue, nextProp);
8455 }
8456 }
8457 }
8458 }
8459
8460 {
8461 // $FlowFixMe - Should be inferred as not undefined.
8462 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8463 // $FlowFixMe - Should be inferred as not undefined.
8464 warnForExtraAttributes(extraAttributeNames);
8465 }
8466 }
8467
8468 switch (tag) {
8469 case 'input':
8470 // TODO: Make sure we check if this is still unmounted or do any clean
8471 // up necessary since we never stop tracking anymore.
8472 track(domElement);
8473 postMountWrapper(domElement, rawProps, true);
8474 break;
8475
8476 case 'textarea':
8477 // TODO: Make sure we check if this is still unmounted or do any clean
8478 // up necessary since we never stop tracking anymore.
8479 track(domElement);
8480 postMountWrapper$3(domElement, rawProps);
8481 break;
8482
8483 case 'select':
8484 case 'option':
8485 // For input and textarea we current always set the value property at
8486 // post mount to force it to diverge from attributes. However, for
8487 // option and select we don't quite do the same thing and select
8488 // is not resilient to the DOM state changing so we don't do that here.
8489 // TODO: Consider not doing this for input and textarea.
8490 break;
8491
8492 default:
8493 if (typeof rawProps.onClick === 'function') {
8494 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8495 trapClickOnNonInteractiveElement(domElement);
8496 }
8497
8498 break;
8499 }
8500
8501 return updatePayload;
8502}
8503function diffHydratedText(textNode, text) {
8504 var isDifferent = textNode.nodeValue !== text;
8505 return isDifferent;
8506}
8507function warnForUnmatchedText(textNode, text) {
8508 {
8509 warnForTextDifference(textNode.nodeValue, text);
8510 }
8511}
8512function warnForDeletedHydratableElement(parentNode, child) {
8513 {
8514 if (didWarnInvalidHydration) {
8515 return;
8516 }
8517
8518 didWarnInvalidHydration = true;
8519 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8520 }
8521}
8522function warnForDeletedHydratableText(parentNode, child) {
8523 {
8524 if (didWarnInvalidHydration) {
8525 return;
8526 }
8527
8528 didWarnInvalidHydration = true;
8529 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8530 }
8531}
8532function warnForInsertedHydratedElement(parentNode, tag, props) {
8533 {
8534 if (didWarnInvalidHydration) {
8535 return;
8536 }
8537
8538 didWarnInvalidHydration = true;
8539 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8540 }
8541}
8542function warnForInsertedHydratedText(parentNode, text) {
8543 {
8544 if (text === '') {
8545 // We expect to insert empty text nodes since they're not represented in
8546 // the HTML.
8547 // TODO: Remove this special case if we can just avoid inserting empty
8548 // text nodes.
8549 return;
8550 }
8551
8552 if (didWarnInvalidHydration) {
8553 return;
8554 }
8555
8556 didWarnInvalidHydration = true;
8557 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8558 }
8559}
8560function restoreControlledState$$1(domElement, tag, props) {
8561 switch (tag) {
8562 case 'input':
8563 restoreControlledState$1(domElement, props);
8564 return;
8565
8566 case 'textarea':
8567 restoreControlledState$3(domElement, props);
8568 return;
8569
8570 case 'select':
8571 restoreControlledState$2(domElement, props);
8572 return;
8573 }
8574}
8575function listenToEventResponderEventTypes(eventTypes, element) {
8576 if (enableFlareAPI) {
8577 // Get the listening Set for this element. We use this to track
8578 // what events we're listening to.
8579 var listeningSet = getListeningSetForElement(element); // Go through each target event type of the event responder
8580
8581 for (var i = 0, length = eventTypes.length; i < length; ++i) {
8582 var eventType = eventTypes[i];
8583 var isPassive = !endsWith(eventType, '_active');
8584 var eventKey = isPassive ? eventType + '_passive' : eventType;
8585 var targetEventType = isPassive ? eventType : eventType.substring(0, eventType.length - 7);
8586
8587 if (!listeningSet.has(eventKey)) {
8588 trapEventForResponderEventSystem(element, targetEventType, isPassive);
8589 listeningSet.add(eventKey);
8590 }
8591 }
8592 }
8593} // We can remove this once the event API is stable and out of a flag
8594
8595if (enableFlareAPI) {
8596 setListenToResponderEventTypes(listenToEventResponderEventTypes);
8597}
8598
8599function getActiveElement(doc) {
8600 doc = doc || (typeof document !== 'undefined' ? document : undefined);
8601
8602 if (typeof doc === 'undefined') {
8603 return null;
8604 }
8605
8606 try {
8607 return doc.activeElement || doc.body;
8608 } catch (e) {
8609 return doc.body;
8610 }
8611}
8612
8613/**
8614 * Given any node return the first leaf node without children.
8615 *
8616 * @param {DOMElement|DOMTextNode} node
8617 * @return {DOMElement|DOMTextNode}
8618 */
8619
8620function getLeafNode(node) {
8621 while (node && node.firstChild) {
8622 node = node.firstChild;
8623 }
8624
8625 return node;
8626}
8627/**
8628 * Get the next sibling within a container. This will walk up the
8629 * DOM if a node's siblings have been exhausted.
8630 *
8631 * @param {DOMElement|DOMTextNode} node
8632 * @return {?DOMElement|DOMTextNode}
8633 */
8634
8635
8636function getSiblingNode(node) {
8637 while (node) {
8638 if (node.nextSibling) {
8639 return node.nextSibling;
8640 }
8641
8642 node = node.parentNode;
8643 }
8644}
8645/**
8646 * Get object describing the nodes which contain characters at offset.
8647 *
8648 * @param {DOMElement|DOMTextNode} root
8649 * @param {number} offset
8650 * @return {?object}
8651 */
8652
8653
8654function getNodeForCharacterOffset(root, offset) {
8655 var node = getLeafNode(root);
8656 var nodeStart = 0;
8657 var nodeEnd = 0;
8658
8659 while (node) {
8660 if (node.nodeType === TEXT_NODE) {
8661 nodeEnd = nodeStart + node.textContent.length;
8662
8663 if (nodeStart <= offset && nodeEnd >= offset) {
8664 return {
8665 node: node,
8666 offset: offset - nodeStart
8667 };
8668 }
8669
8670 nodeStart = nodeEnd;
8671 }
8672
8673 node = getLeafNode(getSiblingNode(node));
8674 }
8675}
8676
8677/**
8678 * @param {DOMElement} outerNode
8679 * @return {?object}
8680 */
8681
8682function getOffsets(outerNode) {
8683 var ownerDocument = outerNode.ownerDocument;
8684 var win = ownerDocument && ownerDocument.defaultView || window;
8685 var selection = win.getSelection && win.getSelection();
8686
8687 if (!selection || selection.rangeCount === 0) {
8688 return null;
8689 }
8690
8691 var anchorNode = selection.anchorNode,
8692 anchorOffset = selection.anchorOffset,
8693 focusNode = selection.focusNode,
8694 focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
8695 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
8696 // expose properties, triggering a "Permission denied error" if any of its
8697 // properties are accessed. The only seemingly possible way to avoid erroring
8698 // is to access a property that typically works for non-anonymous divs and
8699 // catch any error that may otherwise arise. See
8700 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
8701
8702 try {
8703 /* eslint-disable no-unused-expressions */
8704 anchorNode.nodeType;
8705 focusNode.nodeType;
8706 /* eslint-enable no-unused-expressions */
8707 } catch (e) {
8708 return null;
8709 }
8710
8711 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
8712}
8713/**
8714 * Returns {start, end} where `start` is the character/codepoint index of
8715 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
8716 * `end` is the index of (focusNode, focusOffset).
8717 *
8718 * Returns null if you pass in garbage input but we should probably just crash.
8719 *
8720 * Exported only for testing.
8721 */
8722
8723function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
8724 var length = 0;
8725 var start = -1;
8726 var end = -1;
8727 var indexWithinAnchor = 0;
8728 var indexWithinFocus = 0;
8729 var node = outerNode;
8730 var parentNode = null;
8731
8732 outer: while (true) {
8733 var next = null;
8734
8735 while (true) {
8736 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
8737 start = length + anchorOffset;
8738 }
8739
8740 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
8741 end = length + focusOffset;
8742 }
8743
8744 if (node.nodeType === TEXT_NODE) {
8745 length += node.nodeValue.length;
8746 }
8747
8748 if ((next = node.firstChild) === null) {
8749 break;
8750 } // Moving from `node` to its first child `next`.
8751
8752
8753 parentNode = node;
8754 node = next;
8755 }
8756
8757 while (true) {
8758 if (node === outerNode) {
8759 // If `outerNode` has children, this is always the second time visiting
8760 // it. If it has no children, this is still the first loop, and the only
8761 // valid selection is anchorNode and focusNode both equal to this node
8762 // and both offsets 0, in which case we will have handled above.
8763 break outer;
8764 }
8765
8766 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
8767 start = length;
8768 }
8769
8770 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
8771 end = length;
8772 }
8773
8774 if ((next = node.nextSibling) !== null) {
8775 break;
8776 }
8777
8778 node = parentNode;
8779 parentNode = node.parentNode;
8780 } // Moving from `node` to its next sibling `next`.
8781
8782
8783 node = next;
8784 }
8785
8786 if (start === -1 || end === -1) {
8787 // This should never happen. (Would happen if the anchor/focus nodes aren't
8788 // actually inside the passed-in node.)
8789 return null;
8790 }
8791
8792 return {
8793 start: start,
8794 end: end
8795 };
8796}
8797/**
8798 * In modern non-IE browsers, we can support both forward and backward
8799 * selections.
8800 *
8801 * Note: IE10+ supports the Selection object, but it does not support
8802 * the `extend` method, which means that even in modern IE, it's not possible
8803 * to programmatically create a backward selection. Thus, for all IE
8804 * versions, we use the old IE API to create our selections.
8805 *
8806 * @param {DOMElement|DOMTextNode} node
8807 * @param {object} offsets
8808 */
8809
8810function setOffsets(node, offsets) {
8811 var doc = node.ownerDocument || document;
8812 var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
8813 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
8814 // fails when pasting 100+ items)
8815
8816 if (!win.getSelection) {
8817 return;
8818 }
8819
8820 var selection = win.getSelection();
8821 var length = node.textContent.length;
8822 var start = Math.min(offsets.start, length);
8823 var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
8824 // Flip backward selections, so we can set with a single range.
8825
8826 if (!selection.extend && start > end) {
8827 var temp = end;
8828 end = start;
8829 start = temp;
8830 }
8831
8832 var startMarker = getNodeForCharacterOffset(node, start);
8833 var endMarker = getNodeForCharacterOffset(node, end);
8834
8835 if (startMarker && endMarker) {
8836 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
8837 return;
8838 }
8839
8840 var range = doc.createRange();
8841 range.setStart(startMarker.node, startMarker.offset);
8842 selection.removeAllRanges();
8843
8844 if (start > end) {
8845 selection.addRange(range);
8846 selection.extend(endMarker.node, endMarker.offset);
8847 } else {
8848 range.setEnd(endMarker.node, endMarker.offset);
8849 selection.addRange(range);
8850 }
8851 }
8852}
8853
8854function isTextNode(node) {
8855 return node && node.nodeType === TEXT_NODE;
8856}
8857
8858function containsNode(outerNode, innerNode) {
8859 if (!outerNode || !innerNode) {
8860 return false;
8861 } else if (outerNode === innerNode) {
8862 return true;
8863 } else if (isTextNode(outerNode)) {
8864 return false;
8865 } else if (isTextNode(innerNode)) {
8866 return containsNode(outerNode, innerNode.parentNode);
8867 } else if ('contains' in outerNode) {
8868 return outerNode.contains(innerNode);
8869 } else if (outerNode.compareDocumentPosition) {
8870 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
8871 } else {
8872 return false;
8873 }
8874}
8875
8876function isInDocument(node) {
8877 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
8878}
8879
8880function isSameOriginFrame(iframe) {
8881 try {
8882 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
8883 // to throw, e.g. if it has a cross-origin src attribute.
8884 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
8885 // iframe.contentDocument.defaultView;
8886 // A safety way is to access one of the cross origin properties: Window or Location
8887 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
8888 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
8889 return typeof iframe.contentWindow.location.href === 'string';
8890 } catch (err) {
8891 return false;
8892 }
8893}
8894
8895function getActiveElementDeep() {
8896 var win = window;
8897 var element = getActiveElement();
8898
8899 while (element instanceof win.HTMLIFrameElement) {
8900 if (isSameOriginFrame(element)) {
8901 win = element.contentWindow;
8902 } else {
8903 return element;
8904 }
8905
8906 element = getActiveElement(win.document);
8907 }
8908
8909 return element;
8910}
8911/**
8912 * @ReactInputSelection: React input selection module. Based on Selection.js,
8913 * but modified to be suitable for react and has a couple of bug fixes (doesn't
8914 * assume buttons have range selections allowed).
8915 * Input selection module for React.
8916 */
8917
8918/**
8919 * @hasSelectionCapabilities: we get the element types that support selection
8920 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
8921 * and `selectionEnd` rows.
8922 */
8923
8924
8925function hasSelectionCapabilities(elem) {
8926 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
8927 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
8928}
8929function getSelectionInformation() {
8930 var focusedElem = getActiveElementDeep();
8931 return {
8932 focusedElem: focusedElem,
8933 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
8934 };
8935}
8936/**
8937 * @restoreSelection: If any selection information was potentially lost,
8938 * restore it. This is useful when performing operations that could remove dom
8939 * nodes and place them back in, resulting in focus being lost.
8940 */
8941
8942function restoreSelection(priorSelectionInformation) {
8943 var curFocusedElem = getActiveElementDeep();
8944 var priorFocusedElem = priorSelectionInformation.focusedElem;
8945 var priorSelectionRange = priorSelectionInformation.selectionRange;
8946
8947 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
8948 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
8949 setSelection(priorFocusedElem, priorSelectionRange);
8950 } // Focusing a node can change the scroll position, which is undesirable
8951
8952
8953 var ancestors = [];
8954 var ancestor = priorFocusedElem;
8955
8956 while (ancestor = ancestor.parentNode) {
8957 if (ancestor.nodeType === ELEMENT_NODE) {
8958 ancestors.push({
8959 element: ancestor,
8960 left: ancestor.scrollLeft,
8961 top: ancestor.scrollTop
8962 });
8963 }
8964 }
8965
8966 if (typeof priorFocusedElem.focus === 'function') {
8967 priorFocusedElem.focus();
8968 }
8969
8970 for (var i = 0; i < ancestors.length; i++) {
8971 var info = ancestors[i];
8972 info.element.scrollLeft = info.left;
8973 info.element.scrollTop = info.top;
8974 }
8975 }
8976}
8977/**
8978 * @getSelection: Gets the selection bounds of a focused textarea, input or
8979 * contentEditable node.
8980 * -@input: Look up selection bounds of this input
8981 * -@return {start: selectionStart, end: selectionEnd}
8982 */
8983
8984function getSelection(input) {
8985 var selection;
8986
8987 if ('selectionStart' in input) {
8988 // Modern browser with input or textarea.
8989 selection = {
8990 start: input.selectionStart,
8991 end: input.selectionEnd
8992 };
8993 } else {
8994 // Content editable or old IE textarea.
8995 selection = getOffsets(input);
8996 }
8997
8998 return selection || {
8999 start: 0,
9000 end: 0
9001 };
9002}
9003/**
9004 * @setSelection: Sets the selection bounds of a textarea or input and focuses
9005 * the input.
9006 * -@input Set selection bounds of this input or textarea
9007 * -@offsets Object of same form that is returned from get*
9008 */
9009
9010function setSelection(input, offsets) {
9011 var start = offsets.start,
9012 end = offsets.end;
9013
9014 if (end === undefined) {
9015 end = start;
9016 }
9017
9018 if ('selectionStart' in input) {
9019 input.selectionStart = start;
9020 input.selectionEnd = Math.min(end, input.value.length);
9021 } else {
9022 setOffsets(input, offsets);
9023 }
9024}
9025
9026var validateDOMNesting = function () {};
9027
9028var updatedAncestorInfo = function () {};
9029
9030{
9031 // This validation code was written based on the HTML5 parsing spec:
9032 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9033 //
9034 // Note: this does not catch all invalid nesting, nor does it try to (as it's
9035 // not clear what practical benefit doing so provides); instead, we warn only
9036 // for cases where the parser will give a parse tree differing from what React
9037 // intended. For example, <b><div></div></b> is invalid but we don't warn
9038 // because it still parses correctly; we do warn for other cases like nested
9039 // <p> tags where the beginning of the second element implicitly closes the
9040 // first, causing a confusing mess.
9041 // https://html.spec.whatwg.org/multipage/syntax.html#special
9042 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
9043
9044 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
9045 // TODO: Distinguish by namespace here -- for <title>, including it here
9046 // errs on the side of fewer warnings
9047 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
9048
9049 var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
9050
9051 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
9052 var emptyAncestorInfo = {
9053 current: null,
9054 formTag: null,
9055 aTagInScope: null,
9056 buttonTagInScope: null,
9057 nobrTagInScope: null,
9058 pTagInButtonScope: null,
9059 listItemTagAutoclosing: null,
9060 dlItemTagAutoclosing: null
9061 };
9062
9063 updatedAncestorInfo = function (oldInfo, tag) {
9064 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
9065
9066 var info = {
9067 tag: tag
9068 };
9069
9070 if (inScopeTags.indexOf(tag) !== -1) {
9071 ancestorInfo.aTagInScope = null;
9072 ancestorInfo.buttonTagInScope = null;
9073 ancestorInfo.nobrTagInScope = null;
9074 }
9075
9076 if (buttonScopeTags.indexOf(tag) !== -1) {
9077 ancestorInfo.pTagInButtonScope = null;
9078 } // See rules for 'li', 'dd', 'dt' start tags in
9079 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9080
9081
9082 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
9083 ancestorInfo.listItemTagAutoclosing = null;
9084 ancestorInfo.dlItemTagAutoclosing = null;
9085 }
9086
9087 ancestorInfo.current = info;
9088
9089 if (tag === 'form') {
9090 ancestorInfo.formTag = info;
9091 }
9092
9093 if (tag === 'a') {
9094 ancestorInfo.aTagInScope = info;
9095 }
9096
9097 if (tag === 'button') {
9098 ancestorInfo.buttonTagInScope = info;
9099 }
9100
9101 if (tag === 'nobr') {
9102 ancestorInfo.nobrTagInScope = info;
9103 }
9104
9105 if (tag === 'p') {
9106 ancestorInfo.pTagInButtonScope = info;
9107 }
9108
9109 if (tag === 'li') {
9110 ancestorInfo.listItemTagAutoclosing = info;
9111 }
9112
9113 if (tag === 'dd' || tag === 'dt') {
9114 ancestorInfo.dlItemTagAutoclosing = info;
9115 }
9116
9117 return ancestorInfo;
9118 };
9119 /**
9120 * Returns whether
9121 */
9122
9123
9124 var isTagValidWithParent = function (tag, parentTag) {
9125 // First, let's check if we're in an unusual parsing mode...
9126 switch (parentTag) {
9127 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
9128 case 'select':
9129 return tag === 'option' || tag === 'optgroup' || tag === '#text';
9130
9131 case 'optgroup':
9132 return tag === 'option' || tag === '#text';
9133 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
9134 // but
9135
9136 case 'option':
9137 return tag === '#text';
9138 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
9139 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
9140 // No special behavior since these rules fall back to "in body" mode for
9141 // all except special table nodes which cause bad parsing behavior anyway.
9142 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
9143
9144 case 'tr':
9145 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
9146 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
9147
9148 case 'tbody':
9149 case 'thead':
9150 case 'tfoot':
9151 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
9152 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
9153
9154 case 'colgroup':
9155 return tag === 'col' || tag === 'template';
9156 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
9157
9158 case 'table':
9159 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
9160 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
9161
9162 case 'head':
9163 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
9164 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
9165
9166 case 'html':
9167 return tag === 'head' || tag === 'body' || tag === 'frameset';
9168
9169 case 'frameset':
9170 return tag === 'frame';
9171
9172 case '#document':
9173 return tag === 'html';
9174 } // Probably in the "in body" parsing mode, so we outlaw only tag combos
9175 // where the parsing rules cause implicit opens or closes to be added.
9176 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9177
9178
9179 switch (tag) {
9180 case 'h1':
9181 case 'h2':
9182 case 'h3':
9183 case 'h4':
9184 case 'h5':
9185 case 'h6':
9186 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
9187
9188 case 'rp':
9189 case 'rt':
9190 return impliedEndTags.indexOf(parentTag) === -1;
9191
9192 case 'body':
9193 case 'caption':
9194 case 'col':
9195 case 'colgroup':
9196 case 'frameset':
9197 case 'frame':
9198 case 'head':
9199 case 'html':
9200 case 'tbody':
9201 case 'td':
9202 case 'tfoot':
9203 case 'th':
9204 case 'thead':
9205 case 'tr':
9206 // These tags are only valid with a few parents that have special child
9207 // parsing rules -- if we're down here, then none of those matched and
9208 // so we allow it only if we don't know what the parent is, as all other
9209 // cases are invalid.
9210 return parentTag == null;
9211 }
9212
9213 return true;
9214 };
9215 /**
9216 * Returns whether
9217 */
9218
9219
9220 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
9221 switch (tag) {
9222 case 'address':
9223 case 'article':
9224 case 'aside':
9225 case 'blockquote':
9226 case 'center':
9227 case 'details':
9228 case 'dialog':
9229 case 'dir':
9230 case 'div':
9231 case 'dl':
9232 case 'fieldset':
9233 case 'figcaption':
9234 case 'figure':
9235 case 'footer':
9236 case 'header':
9237 case 'hgroup':
9238 case 'main':
9239 case 'menu':
9240 case 'nav':
9241 case 'ol':
9242 case 'p':
9243 case 'section':
9244 case 'summary':
9245 case 'ul':
9246 case 'pre':
9247 case 'listing':
9248 case 'table':
9249 case 'hr':
9250 case 'xmp':
9251 case 'h1':
9252 case 'h2':
9253 case 'h3':
9254 case 'h4':
9255 case 'h5':
9256 case 'h6':
9257 return ancestorInfo.pTagInButtonScope;
9258
9259 case 'form':
9260 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
9261
9262 case 'li':
9263 return ancestorInfo.listItemTagAutoclosing;
9264
9265 case 'dd':
9266 case 'dt':
9267 return ancestorInfo.dlItemTagAutoclosing;
9268
9269 case 'button':
9270 return ancestorInfo.buttonTagInScope;
9271
9272 case 'a':
9273 // Spec says something about storing a list of markers, but it sounds
9274 // equivalent to this check.
9275 return ancestorInfo.aTagInScope;
9276
9277 case 'nobr':
9278 return ancestorInfo.nobrTagInScope;
9279 }
9280
9281 return null;
9282 };
9283
9284 var didWarn$1 = {};
9285
9286 validateDOMNesting = function (childTag, childText, ancestorInfo) {
9287 ancestorInfo = ancestorInfo || emptyAncestorInfo;
9288 var parentInfo = ancestorInfo.current;
9289 var parentTag = parentInfo && parentInfo.tag;
9290
9291 if (childText != null) {
9292 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
9293 childTag = '#text';
9294 }
9295
9296 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
9297 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
9298 var invalidParentOrAncestor = invalidParent || invalidAncestor;
9299
9300 if (!invalidParentOrAncestor) {
9301 return;
9302 }
9303
9304 var ancestorTag = invalidParentOrAncestor.tag;
9305 var addendum = getCurrentFiberStackInDev();
9306 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
9307
9308 if (didWarn$1[warnKey]) {
9309 return;
9310 }
9311
9312 didWarn$1[warnKey] = true;
9313 var tagDisplayName = childTag;
9314 var whitespaceInfo = '';
9315
9316 if (childTag === '#text') {
9317 if (/\S/.test(childText)) {
9318 tagDisplayName = 'Text nodes';
9319 } else {
9320 tagDisplayName = 'Whitespace text nodes';
9321 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
9322 }
9323 } else {
9324 tagDisplayName = '<' + childTag + '>';
9325 }
9326
9327 if (invalidParent) {
9328 var info = '';
9329
9330 if (ancestorTag === 'table' && childTag === 'tr') {
9331 info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
9332 }
9333
9334 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
9335 } else {
9336 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
9337 }
9338 };
9339}
9340
9341// can re-export everything from this module.
9342
9343function shim() {
9344 {
9345 {
9346 throw Error("The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.");
9347 }
9348 }
9349} // Persistence (when unsupported)
9350
9351
9352var supportsPersistence = false;
9353var cloneInstance = shim;
9354var cloneFundamentalInstance = shim;
9355var createContainerChildSet = shim;
9356var appendChildToContainerChildSet = shim;
9357var finalizeContainerChildren = shim;
9358var replaceContainerChildren = shim;
9359var cloneHiddenInstance = shim;
9360var cloneHiddenTextInstance = shim;
9361
9362var SUPPRESS_HYDRATION_WARNING;
9363
9364{
9365 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9366}
9367
9368var SUSPENSE_START_DATA = '$';
9369var SUSPENSE_END_DATA = '/$';
9370var SUSPENSE_PENDING_START_DATA = '$?';
9371var SUSPENSE_FALLBACK_START_DATA = '$!';
9372var STYLE = 'style';
9373var eventsEnabled = null;
9374var selectionInformation = null;
9375
9376function shouldAutoFocusHostComponent(type, props) {
9377 switch (type) {
9378 case 'button':
9379 case 'input':
9380 case 'select':
9381 case 'textarea':
9382 return !!props.autoFocus;
9383 }
9384
9385 return false;
9386}
9387
9388function getRootHostContext(rootContainerInstance) {
9389 var type;
9390 var namespace;
9391 var nodeType = rootContainerInstance.nodeType;
9392
9393 switch (nodeType) {
9394 case DOCUMENT_NODE:
9395 case DOCUMENT_FRAGMENT_NODE:
9396 {
9397 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
9398 var root = rootContainerInstance.documentElement;
9399 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
9400 break;
9401 }
9402
9403 default:
9404 {
9405 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
9406 var ownNamespace = container.namespaceURI || null;
9407 type = container.tagName;
9408 namespace = getChildNamespace(ownNamespace, type);
9409 break;
9410 }
9411 }
9412
9413 {
9414 var validatedTag = type.toLowerCase();
9415 var ancestorInfo = updatedAncestorInfo(null, validatedTag);
9416 return {
9417 namespace: namespace,
9418 ancestorInfo: ancestorInfo
9419 };
9420 }
9421
9422 return namespace;
9423}
9424function getChildHostContext(parentHostContext, type, rootContainerInstance) {
9425 {
9426 var parentHostContextDev = parentHostContext;
9427 var namespace = getChildNamespace(parentHostContextDev.namespace, type);
9428 var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
9429 return {
9430 namespace: namespace,
9431 ancestorInfo: ancestorInfo
9432 };
9433 }
9434
9435 var parentNamespace = parentHostContext;
9436 return getChildNamespace(parentNamespace, type);
9437}
9438function getPublicInstance(instance) {
9439 return instance;
9440}
9441function prepareForCommit(containerInfo) {
9442 eventsEnabled = isEnabled();
9443 selectionInformation = getSelectionInformation();
9444 setEnabled(false);
9445}
9446function resetAfterCommit(containerInfo) {
9447 restoreSelection(selectionInformation);
9448 selectionInformation = null;
9449 setEnabled(eventsEnabled);
9450 eventsEnabled = null;
9451}
9452function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9453 var parentNamespace;
9454
9455 {
9456 // TODO: take namespace into account when validating.
9457 var hostContextDev = hostContext;
9458 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
9459
9460 if (typeof props.children === 'string' || typeof props.children === 'number') {
9461 var string = '' + props.children;
9462 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9463 validateDOMNesting(null, string, ownAncestorInfo);
9464 }
9465
9466 parentNamespace = hostContextDev.namespace;
9467 }
9468
9469 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
9470 precacheFiberNode(internalInstanceHandle, domElement);
9471 updateFiberProps(domElement, props);
9472 return domElement;
9473}
9474function appendInitialChild(parentInstance, child) {
9475 parentInstance.appendChild(child);
9476}
9477function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
9478 setInitialProperties(domElement, type, props, rootContainerInstance);
9479 return shouldAutoFocusHostComponent(type, props);
9480}
9481function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
9482 {
9483 var hostContextDev = hostContext;
9484
9485 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
9486 var string = '' + newProps.children;
9487 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9488 validateDOMNesting(null, string, ownAncestorInfo);
9489 }
9490 }
9491
9492 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
9493}
9494function shouldSetTextContent(type, props) {
9495 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;
9496}
9497function shouldDeprioritizeSubtree(type, props) {
9498 return !!props.hidden;
9499}
9500function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
9501 {
9502 var hostContextDev = hostContext;
9503 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
9504 }
9505
9506 var textNode = createTextNode(text, rootContainerInstance);
9507 precacheFiberNode(internalInstanceHandle, textNode);
9508 return textNode;
9509}
9510var isPrimaryRenderer = true;
9511var warnsIfNotActing = true; // This initialization code may run even on server environments
9512// if a component just imports ReactDOM (e.g. for findDOMNode).
9513// Some environments might not have setTimeout or clearTimeout.
9514
9515var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
9516var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
9517var noTimeout = -1; // -------------------
9518// Mutation
9519// -------------------
9520
9521var supportsMutation = true;
9522function commitMount(domElement, type, newProps, internalInstanceHandle) {
9523 // Despite the naming that might imply otherwise, this method only
9524 // fires if there is an `Update` effect scheduled during mounting.
9525 // This happens if `finalizeInitialChildren` returns `true` (which it
9526 // does to implement the `autoFocus` attribute on the client). But
9527 // there are also other cases when this might happen (such as patching
9528 // up text content during hydration mismatch). So we'll check this again.
9529 if (shouldAutoFocusHostComponent(type, newProps)) {
9530 domElement.focus();
9531 }
9532}
9533function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
9534 // Update the props handle so that we know which props are the ones with
9535 // with current event handlers.
9536 updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.
9537
9538 updateProperties(domElement, updatePayload, type, oldProps, newProps);
9539}
9540function resetTextContent(domElement) {
9541 setTextContent(domElement, '');
9542}
9543function commitTextUpdate(textInstance, oldText, newText) {
9544 textInstance.nodeValue = newText;
9545}
9546function appendChild(parentInstance, child) {
9547 parentInstance.appendChild(child);
9548}
9549function appendChildToContainer(container, child) {
9550 var parentNode;
9551
9552 if (container.nodeType === COMMENT_NODE) {
9553 parentNode = container.parentNode;
9554 parentNode.insertBefore(child, container);
9555 } else {
9556 parentNode = container;
9557 parentNode.appendChild(child);
9558 } // This container might be used for a portal.
9559 // If something inside a portal is clicked, that click should bubble
9560 // through the React tree. However, on Mobile Safari the click would
9561 // never bubble through the *DOM* tree unless an ancestor with onclick
9562 // event exists. So we wouldn't see it and dispatch it.
9563 // This is why we ensure that non React root containers have inline onclick
9564 // defined.
9565 // https://github.com/facebook/react/issues/11918
9566
9567
9568 var reactRootContainer = container._reactRootContainer;
9569
9570 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
9571 // TODO: This cast may not be sound for SVG, MathML or custom elements.
9572 trapClickOnNonInteractiveElement(parentNode);
9573 }
9574}
9575function insertBefore(parentInstance, child, beforeChild) {
9576 parentInstance.insertBefore(child, beforeChild);
9577}
9578function insertInContainerBefore(container, child, beforeChild) {
9579 if (container.nodeType === COMMENT_NODE) {
9580 container.parentNode.insertBefore(child, beforeChild);
9581 } else {
9582 container.insertBefore(child, beforeChild);
9583 }
9584} // This is a specific event for the React Flare
9585// event system, so event responders can act
9586// accordingly to a DOM node being unmounted that
9587// previously had active document focus.
9588
9589function dispatchDetachedVisibleNodeEvent(child) {
9590 if (enableFlareAPI && selectionInformation && child === selectionInformation.focusedElem) {
9591 var targetFiber = getClosestInstanceFromNode(child); // Simlulate a blur event to the React Flare responder system.
9592
9593 dispatchEventForResponderEventSystem('detachedvisiblenode', targetFiber, {
9594 target: child,
9595 timeStamp: Date.now()
9596 }, child, RESPONDER_EVENT_SYSTEM | IS_PASSIVE);
9597 }
9598}
9599
9600function removeChild(parentInstance, child) {
9601 dispatchDetachedVisibleNodeEvent(child);
9602 parentInstance.removeChild(child);
9603}
9604function removeChildFromContainer(container, child) {
9605 if (container.nodeType === COMMENT_NODE) {
9606 container.parentNode.removeChild(child);
9607 } else {
9608 dispatchDetachedVisibleNodeEvent(child);
9609 container.removeChild(child);
9610 }
9611}
9612function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9613 var node = suspenseInstance; // Delete all nodes within this suspense boundary.
9614 // There might be nested nodes so we need to keep track of how
9615 // deep we are and only break out when we're back on top.
9616
9617 var depth = 0;
9618
9619 do {
9620 var nextNode = node.nextSibling;
9621 parentInstance.removeChild(node);
9622
9623 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9624 var data = nextNode.data;
9625
9626 if (data === SUSPENSE_END_DATA) {
9627 if (depth === 0) {
9628 parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
9629
9630 retryIfBlockedOn(suspenseInstance);
9631 return;
9632 } else {
9633 depth--;
9634 }
9635 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
9636 depth++;
9637 }
9638 }
9639
9640 node = nextNode;
9641 } while (node); // TODO: Warn, we didn't find the end comment boundary.
9642 // Retry if any event replaying was blocked on this.
9643
9644
9645 retryIfBlockedOn(suspenseInstance);
9646}
9647function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9648 if (container.nodeType === COMMENT_NODE) {
9649 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9650 } else if (container.nodeType === ELEMENT_NODE) {
9651 clearSuspenseBoundary(container, suspenseInstance);
9652 } else {} // Document nodes should never contain suspense boundaries.
9653 // Retry if any event replaying was blocked on this.
9654
9655
9656 retryIfBlockedOn(container);
9657}
9658function hideInstance(instance) {
9659 // TODO: Does this work for all element types? What about MathML? Should we
9660 // pass host context to this method?
9661 instance = instance;
9662 var style = instance.style;
9663
9664 if (typeof style.setProperty === 'function') {
9665 style.setProperty('display', 'none', 'important');
9666 } else {
9667 style.display = 'none';
9668 }
9669}
9670function hideTextInstance(textInstance) {
9671 textInstance.nodeValue = '';
9672}
9673function unhideInstance(instance, props) {
9674 instance = instance;
9675 var styleProp = props[STYLE];
9676 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9677 instance.style.display = dangerousStyleValue('display', display);
9678}
9679function unhideTextInstance(textInstance, text) {
9680 textInstance.nodeValue = text;
9681} // -------------------
9682// Hydration
9683// -------------------
9684
9685var supportsHydration = true;
9686function canHydrateInstance(instance, type, props) {
9687 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9688 return null;
9689 } // This has now been refined to an element node.
9690
9691
9692 return instance;
9693}
9694function canHydrateTextInstance(instance, text) {
9695 if (text === '' || instance.nodeType !== TEXT_NODE) {
9696 // Empty strings are not parsed by HTML so there won't be a correct match here.
9697 return null;
9698 } // This has now been refined to a text node.
9699
9700
9701 return instance;
9702}
9703function canHydrateSuspenseInstance(instance) {
9704 if (instance.nodeType !== COMMENT_NODE) {
9705 // Empty strings are not parsed by HTML so there won't be a correct match here.
9706 return null;
9707 } // This has now been refined to a suspense node.
9708
9709
9710 return instance;
9711}
9712function isSuspenseInstancePending(instance) {
9713 return instance.data === SUSPENSE_PENDING_START_DATA;
9714}
9715function isSuspenseInstanceFallback(instance) {
9716 return instance.data === SUSPENSE_FALLBACK_START_DATA;
9717}
9718function registerSuspenseInstanceRetry(instance, callback) {
9719 instance._reactRetry = callback;
9720}
9721
9722function getNextHydratable(node) {
9723 // Skip non-hydratable nodes.
9724 for (; node != null; node = node.nextSibling) {
9725 var nodeType = node.nodeType;
9726
9727 if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
9728 break;
9729 }
9730
9731 if (enableSuspenseServerRenderer) {
9732 if (nodeType === COMMENT_NODE) {
9733 var nodeData = node.data;
9734
9735 if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
9736 break;
9737 }
9738 }
9739 }
9740 }
9741
9742 return node;
9743}
9744
9745function getNextHydratableSibling(instance) {
9746 return getNextHydratable(instance.nextSibling);
9747}
9748function getFirstHydratableChild(parentInstance) {
9749 return getNextHydratable(parentInstance.firstChild);
9750}
9751function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9752 precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
9753 // get attached.
9754
9755 updateFiberProps(instance, props);
9756 var parentNamespace;
9757
9758 {
9759 var hostContextDev = hostContext;
9760 parentNamespace = hostContextDev.namespace;
9761 }
9762
9763 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9764}
9765function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9766 precacheFiberNode(internalInstanceHandle, textInstance);
9767 return diffHydratedText(textInstance, text);
9768}
9769function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
9770 precacheFiberNode(internalInstanceHandle, suspenseInstance);
9771}
9772function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9773 var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
9774 // There might be nested nodes so we need to keep track of how
9775 // deep we are and only break out when we're back on top.
9776
9777 var depth = 0;
9778
9779 while (node) {
9780 if (node.nodeType === COMMENT_NODE) {
9781 var data = node.data;
9782
9783 if (data === SUSPENSE_END_DATA) {
9784 if (depth === 0) {
9785 return getNextHydratableSibling(node);
9786 } else {
9787 depth--;
9788 }
9789 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9790 depth++;
9791 }
9792 }
9793
9794 node = node.nextSibling;
9795 } // TODO: Warn, we didn't find the end comment boundary.
9796
9797
9798 return null;
9799} // Returns the SuspenseInstance if this node is a direct child of a
9800// SuspenseInstance. I.e. if its previous sibling is a Comment with
9801// SUSPENSE_x_START_DATA. Otherwise, null.
9802
9803function getParentSuspenseInstance(targetInstance) {
9804 var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
9805 // There might be nested nodes so we need to keep track of how
9806 // deep we are and only break out when we're back on top.
9807
9808 var depth = 0;
9809
9810 while (node) {
9811 if (node.nodeType === COMMENT_NODE) {
9812 var data = node.data;
9813
9814 if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9815 if (depth === 0) {
9816 return node;
9817 } else {
9818 depth--;
9819 }
9820 } else if (data === SUSPENSE_END_DATA) {
9821 depth++;
9822 }
9823 }
9824
9825 node = node.previousSibling;
9826 }
9827
9828 return null;
9829}
9830function commitHydratedContainer(container) {
9831 // Retry if any event replaying was blocked on this.
9832 retryIfBlockedOn(container);
9833}
9834function commitHydratedSuspenseInstance(suspenseInstance) {
9835 // Retry if any event replaying was blocked on this.
9836 retryIfBlockedOn(suspenseInstance);
9837}
9838function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9839 {
9840 warnForUnmatchedText(textInstance, text);
9841 }
9842}
9843function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9844 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9845 warnForUnmatchedText(textInstance, text);
9846 }
9847}
9848function didNotHydrateContainerInstance(parentContainer, instance) {
9849 {
9850 if (instance.nodeType === ELEMENT_NODE) {
9851 warnForDeletedHydratableElement(parentContainer, instance);
9852 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9853 } else {
9854 warnForDeletedHydratableText(parentContainer, instance);
9855 }
9856 }
9857}
9858function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9859 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9860 if (instance.nodeType === ELEMENT_NODE) {
9861 warnForDeletedHydratableElement(parentInstance, instance);
9862 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9863 } else {
9864 warnForDeletedHydratableText(parentInstance, instance);
9865 }
9866 }
9867}
9868function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9869 {
9870 warnForInsertedHydratedElement(parentContainer, type, props);
9871 }
9872}
9873function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9874 {
9875 warnForInsertedHydratedText(parentContainer, text);
9876 }
9877}
9878
9879function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
9880 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9881 warnForInsertedHydratedElement(parentInstance, type, props);
9882 }
9883}
9884function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
9885 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9886 warnForInsertedHydratedText(parentInstance, text);
9887 }
9888}
9889function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
9890 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {// TODO: warnForInsertedHydratedSuspense(parentInstance);
9891 }
9892}
9893function mountResponderInstance(responder, responderInstance, responderProps, responderState, instance) {
9894 // Listen to events
9895 var doc = instance.ownerDocument;
9896 var _ref = responder,
9897 rootEventTypes = _ref.rootEventTypes,
9898 targetEventTypes = _ref.targetEventTypes;
9899
9900 if (targetEventTypes !== null) {
9901 listenToEventResponderEventTypes(targetEventTypes, doc);
9902 }
9903
9904 if (rootEventTypes !== null) {
9905 addRootEventTypesForResponderInstance(responderInstance, rootEventTypes);
9906 listenToEventResponderEventTypes(rootEventTypes, doc);
9907 }
9908
9909 mountEventResponder(responder, responderInstance, responderProps, responderState);
9910 return responderInstance;
9911}
9912function unmountResponderInstance(responderInstance) {
9913 if (enableFlareAPI) {
9914 // TODO stop listening to targetEventTypes
9915 unmountEventResponder(responderInstance);
9916 }
9917}
9918function getFundamentalComponentInstance(fundamentalInstance) {
9919 if (enableFundamentalAPI) {
9920 var currentFiber = fundamentalInstance.currentFiber,
9921 impl = fundamentalInstance.impl,
9922 props = fundamentalInstance.props,
9923 state = fundamentalInstance.state;
9924 var instance = impl.getInstance(null, props, state);
9925 precacheFiberNode(currentFiber, instance);
9926 return instance;
9927 } // Because of the flag above, this gets around the Flow error;
9928
9929
9930 return null;
9931}
9932function mountFundamentalComponent(fundamentalInstance) {
9933 if (enableFundamentalAPI) {
9934 var impl = fundamentalInstance.impl,
9935 instance = fundamentalInstance.instance,
9936 props = fundamentalInstance.props,
9937 state = fundamentalInstance.state;
9938 var onMount = impl.onMount;
9939
9940 if (onMount !== undefined) {
9941 onMount(null, instance, props, state);
9942 }
9943 }
9944}
9945function shouldUpdateFundamentalComponent(fundamentalInstance) {
9946 if (enableFundamentalAPI) {
9947 var impl = fundamentalInstance.impl,
9948 prevProps = fundamentalInstance.prevProps,
9949 props = fundamentalInstance.props,
9950 state = fundamentalInstance.state;
9951 var shouldUpdate = impl.shouldUpdate;
9952
9953 if (shouldUpdate !== undefined) {
9954 return shouldUpdate(null, prevProps, props, state);
9955 }
9956 }
9957
9958 return true;
9959}
9960function updateFundamentalComponent(fundamentalInstance) {
9961 if (enableFundamentalAPI) {
9962 var impl = fundamentalInstance.impl,
9963 instance = fundamentalInstance.instance,
9964 prevProps = fundamentalInstance.prevProps,
9965 props = fundamentalInstance.props,
9966 state = fundamentalInstance.state;
9967 var onUpdate = impl.onUpdate;
9968
9969 if (onUpdate !== undefined) {
9970 onUpdate(null, instance, prevProps, props, state);
9971 }
9972 }
9973}
9974function unmountFundamentalComponent(fundamentalInstance) {
9975 if (enableFundamentalAPI) {
9976 var impl = fundamentalInstance.impl,
9977 instance = fundamentalInstance.instance,
9978 props = fundamentalInstance.props,
9979 state = fundamentalInstance.state;
9980 var onUnmount = impl.onUnmount;
9981
9982 if (onUnmount !== undefined) {
9983 onUnmount(null, instance, props, state);
9984 }
9985 }
9986}
9987function getInstanceFromNode$2(node) {
9988 return getClosestInstanceFromNode(node) || null;
9989}
9990
9991var randomKey = Math.random().toString(36).slice(2);
9992var internalInstanceKey = '__reactInternalInstance$' + randomKey;
9993var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
9994var internalContainerInstanceKey = '__reactContainere$' + randomKey;
9995function precacheFiberNode(hostInst, node) {
9996 node[internalInstanceKey] = hostInst;
9997}
9998function markContainerAsRoot(hostRoot, node) {
9999 node[internalContainerInstanceKey] = hostRoot;
10000}
10001function unmarkContainerAsRoot(node) {
10002 node[internalContainerInstanceKey] = null;
10003}
10004function isContainerMarkedAsRoot(node) {
10005 return !!node[internalContainerInstanceKey];
10006} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
10007// If the target node is part of a hydrated or not yet rendered subtree, then
10008// this may also return a SuspenseComponent or HostRoot to indicate that.
10009// Conceptually the HostRoot fiber is a child of the Container node. So if you
10010// pass the Container node as the targetNode, you will not actually get the
10011// HostRoot back. To get to the HostRoot, you need to pass a child of it.
10012// The same thing applies to Suspense boundaries.
10013
10014function getClosestInstanceFromNode(targetNode) {
10015 var targetInst = targetNode[internalInstanceKey];
10016
10017 if (targetInst) {
10018 // Don't return HostRoot or SuspenseComponent here.
10019 return targetInst;
10020 } // If the direct event target isn't a React owned DOM node, we need to look
10021 // to see if one of its parents is a React owned DOM node.
10022
10023
10024 var parentNode = targetNode.parentNode;
10025
10026 while (parentNode) {
10027 // We'll check if this is a container root that could include
10028 // React nodes in the future. We need to check this first because
10029 // if we're a child of a dehydrated container, we need to first
10030 // find that inner container before moving on to finding the parent
10031 // instance. Note that we don't check this field on the targetNode
10032 // itself because the fibers are conceptually between the container
10033 // node and the first child. It isn't surrounding the container node.
10034 // If it's not a container, we check if it's an instance.
10035 targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
10036
10037 if (targetInst) {
10038 // Since this wasn't the direct target of the event, we might have
10039 // stepped past dehydrated DOM nodes to get here. However they could
10040 // also have been non-React nodes. We need to answer which one.
10041 // If we the instance doesn't have any children, then there can't be
10042 // a nested suspense boundary within it. So we can use this as a fast
10043 // bailout. Most of the time, when people add non-React children to
10044 // the tree, it is using a ref to a child-less DOM node.
10045 // Normally we'd only need to check one of the fibers because if it
10046 // has ever gone from having children to deleting them or vice versa
10047 // it would have deleted the dehydrated boundary nested inside already.
10048 // However, since the HostRoot starts out with an alternate it might
10049 // have one on the alternate so we need to check in case this was a
10050 // root.
10051 var alternate = targetInst.alternate;
10052
10053 if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
10054 // Next we need to figure out if the node that skipped past is
10055 // nested within a dehydrated boundary and if so, which one.
10056 var suspenseInstance = getParentSuspenseInstance(targetNode);
10057
10058 while (suspenseInstance !== null) {
10059 // We found a suspense instance. That means that we haven't
10060 // hydrated it yet. Even though we leave the comments in the
10061 // DOM after hydrating, and there are boundaries in the DOM
10062 // that could already be hydrated, we wouldn't have found them
10063 // through this pass since if the target is hydrated it would
10064 // have had an internalInstanceKey on it.
10065 // Let's get the fiber associated with the SuspenseComponent
10066 // as the deepest instance.
10067 var targetSuspenseInst = suspenseInstance[internalInstanceKey];
10068
10069 if (targetSuspenseInst) {
10070 return targetSuspenseInst;
10071 } // If we don't find a Fiber on the comment, it might be because
10072 // we haven't gotten to hydrate it yet. There might still be a
10073 // parent boundary that hasn't above this one so we need to find
10074 // the outer most that is known.
10075
10076
10077 suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
10078 // host component also hasn't hydrated yet. We can return it
10079 // below since it will bail out on the isMounted check later.
10080 }
10081 }
10082
10083 return targetInst;
10084 }
10085
10086 targetNode = parentNode;
10087 parentNode = targetNode.parentNode;
10088 }
10089
10090 return null;
10091}
10092/**
10093 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
10094 * instance, or null if the node was not rendered by this React.
10095 */
10096
10097function getInstanceFromNode$1(node) {
10098 var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
10099
10100 if (inst) {
10101 if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
10102 return inst;
10103 } else {
10104 return null;
10105 }
10106 }
10107
10108 return null;
10109}
10110/**
10111 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
10112 * DOM node.
10113 */
10114
10115function getNodeFromInstance$1(inst) {
10116 if (inst.tag === HostComponent || inst.tag === HostText) {
10117 // In Fiber this, is just the state node right now. We assume it will be
10118 // a host component or host text.
10119 return inst.stateNode;
10120 } // Without this first invariant, passing a non-DOM-component triggers the next
10121 // invariant for a missing parent, which is super confusing.
10122
10123
10124 {
10125 {
10126 throw Error("getNodeFromInstance: Invalid argument.");
10127 }
10128 }
10129}
10130function getFiberCurrentPropsFromNode$1(node) {
10131 return node[internalEventHandlersKey] || null;
10132}
10133function updateFiberProps(node, props) {
10134 node[internalEventHandlersKey] = props;
10135}
10136
10137/**
10138 * These variables store information about text content of a target node,
10139 * allowing comparison of content before and after a given event.
10140 *
10141 * Identify the node where selection currently begins, then observe
10142 * both its text content and its current position in the DOM. Since the
10143 * browser may natively replace the target node during composition, we can
10144 * use its position to find its replacement.
10145 *
10146 *
10147 */
10148var root = null;
10149var startText = null;
10150var fallbackText = null;
10151function initialize(nativeEventTarget) {
10152 root = nativeEventTarget;
10153 startText = getText();
10154 return true;
10155}
10156function reset() {
10157 root = null;
10158 startText = null;
10159 fallbackText = null;
10160}
10161function getData() {
10162 if (fallbackText) {
10163 return fallbackText;
10164 }
10165
10166 var start;
10167 var startValue = startText;
10168 var startLength = startValue.length;
10169 var end;
10170 var endValue = getText();
10171 var endLength = endValue.length;
10172
10173 for (start = 0; start < startLength; start++) {
10174 if (startValue[start] !== endValue[start]) {
10175 break;
10176 }
10177 }
10178
10179 var minEnd = startLength - start;
10180
10181 for (end = 1; end <= minEnd; end++) {
10182 if (startValue[startLength - end] !== endValue[endLength - end]) {
10183 break;
10184 }
10185 }
10186
10187 var sliceTail = end > 1 ? 1 - end : undefined;
10188 fallbackText = endValue.slice(start, sliceTail);
10189 return fallbackText;
10190}
10191function getText() {
10192 if ('value' in root) {
10193 return root.value;
10194 }
10195
10196 return root.textContent;
10197}
10198
10199/**
10200 * @interface Event
10201 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
10202 */
10203
10204var SyntheticCompositionEvent = SyntheticEvent.extend({
10205 data: null
10206});
10207
10208/**
10209 * @interface Event
10210 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
10211 * /#events-inputevents
10212 */
10213
10214var SyntheticInputEvent = SyntheticEvent.extend({
10215 data: null
10216});
10217
10218var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
10219
10220var START_KEYCODE = 229;
10221var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
10222var documentMode = null;
10223
10224if (canUseDOM && 'documentMode' in document) {
10225 documentMode = document.documentMode;
10226} // Webkit offers a very useful `textInput` event that can be used to
10227// directly represent `beforeInput`. The IE `textinput` event is not as
10228// useful, so we don't use it.
10229
10230
10231var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
10232// by the native compositionend event may be incorrect. Japanese ideographic
10233// spaces, for instance (\u3000) are not recorded correctly.
10234
10235var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
10236var SPACEBAR_CODE = 32;
10237var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.
10238
10239var eventTypes$1 = {
10240 beforeInput: {
10241 phasedRegistrationNames: {
10242 bubbled: 'onBeforeInput',
10243 captured: 'onBeforeInputCapture'
10244 },
10245 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
10246 },
10247 compositionEnd: {
10248 phasedRegistrationNames: {
10249 bubbled: 'onCompositionEnd',
10250 captured: 'onCompositionEndCapture'
10251 },
10252 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10253 },
10254 compositionStart: {
10255 phasedRegistrationNames: {
10256 bubbled: 'onCompositionStart',
10257 captured: 'onCompositionStartCapture'
10258 },
10259 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10260 },
10261 compositionUpdate: {
10262 phasedRegistrationNames: {
10263 bubbled: 'onCompositionUpdate',
10264 captured: 'onCompositionUpdateCapture'
10265 },
10266 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10267 }
10268}; // Track whether we've ever handled a keypress on the space key.
10269
10270var hasSpaceKeypress = false;
10271/**
10272 * Return whether a native keypress event is assumed to be a command.
10273 * This is required because Firefox fires `keypress` events for key commands
10274 * (cut, copy, select-all, etc.) even though no character is inserted.
10275 */
10276
10277function isKeypressCommand(nativeEvent) {
10278 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
10279 !(nativeEvent.ctrlKey && nativeEvent.altKey);
10280}
10281/**
10282 * Translate native top level events into event types.
10283 *
10284 * @param {string} topLevelType
10285 * @return {object}
10286 */
10287
10288
10289function getCompositionEventType(topLevelType) {
10290 switch (topLevelType) {
10291 case TOP_COMPOSITION_START:
10292 return eventTypes$1.compositionStart;
10293
10294 case TOP_COMPOSITION_END:
10295 return eventTypes$1.compositionEnd;
10296
10297 case TOP_COMPOSITION_UPDATE:
10298 return eventTypes$1.compositionUpdate;
10299 }
10300}
10301/**
10302 * Does our fallback best-guess model think this event signifies that
10303 * composition has begun?
10304 *
10305 * @param {string} topLevelType
10306 * @param {object} nativeEvent
10307 * @return {boolean}
10308 */
10309
10310
10311function isFallbackCompositionStart(topLevelType, nativeEvent) {
10312 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
10313}
10314/**
10315 * Does our fallback mode think that this event is the end of composition?
10316 *
10317 * @param {string} topLevelType
10318 * @param {object} nativeEvent
10319 * @return {boolean}
10320 */
10321
10322
10323function isFallbackCompositionEnd(topLevelType, nativeEvent) {
10324 switch (topLevelType) {
10325 case TOP_KEY_UP:
10326 // Command keys insert or clear IME input.
10327 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
10328
10329 case TOP_KEY_DOWN:
10330 // Expect IME keyCode on each keydown. If we get any other
10331 // code we must have exited earlier.
10332 return nativeEvent.keyCode !== START_KEYCODE;
10333
10334 case TOP_KEY_PRESS:
10335 case TOP_MOUSE_DOWN:
10336 case TOP_BLUR:
10337 // Events are not possible without cancelling IME.
10338 return true;
10339
10340 default:
10341 return false;
10342 }
10343}
10344/**
10345 * Google Input Tools provides composition data via a CustomEvent,
10346 * with the `data` property populated in the `detail` object. If this
10347 * is available on the event object, use it. If not, this is a plain
10348 * composition event and we have nothing special to extract.
10349 *
10350 * @param {object} nativeEvent
10351 * @return {?string}
10352 */
10353
10354
10355function getDataFromCustomEvent(nativeEvent) {
10356 var detail = nativeEvent.detail;
10357
10358 if (typeof detail === 'object' && 'data' in detail) {
10359 return detail.data;
10360 }
10361
10362 return null;
10363}
10364/**
10365 * Check if a composition event was triggered by Korean IME.
10366 * Our fallback mode does not work well with IE's Korean IME,
10367 * so just use native composition events when Korean IME is used.
10368 * Although CompositionEvent.locale property is deprecated,
10369 * it is available in IE, where our fallback mode is enabled.
10370 *
10371 * @param {object} nativeEvent
10372 * @return {boolean}
10373 */
10374
10375
10376function isUsingKoreanIME(nativeEvent) {
10377 return nativeEvent.locale === 'ko';
10378} // Track the current IME composition status, if any.
10379
10380
10381var isComposing = false;
10382/**
10383 * @return {?object} A SyntheticCompositionEvent.
10384 */
10385
10386function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10387 var eventType;
10388 var fallbackData;
10389
10390 if (canUseCompositionEvent) {
10391 eventType = getCompositionEventType(topLevelType);
10392 } else if (!isComposing) {
10393 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
10394 eventType = eventTypes$1.compositionStart;
10395 }
10396 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10397 eventType = eventTypes$1.compositionEnd;
10398 }
10399
10400 if (!eventType) {
10401 return null;
10402 }
10403
10404 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
10405 // The current composition is stored statically and must not be
10406 // overwritten while composition continues.
10407 if (!isComposing && eventType === eventTypes$1.compositionStart) {
10408 isComposing = initialize(nativeEventTarget);
10409 } else if (eventType === eventTypes$1.compositionEnd) {
10410 if (isComposing) {
10411 fallbackData = getData();
10412 }
10413 }
10414 }
10415
10416 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
10417
10418 if (fallbackData) {
10419 // Inject data generated from fallback path into the synthetic event.
10420 // This matches the property of native CompositionEventInterface.
10421 event.data = fallbackData;
10422 } else {
10423 var customData = getDataFromCustomEvent(nativeEvent);
10424
10425 if (customData !== null) {
10426 event.data = customData;
10427 }
10428 }
10429
10430 accumulateTwoPhaseDispatches(event);
10431 return event;
10432}
10433/**
10434 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
10435 * @param {object} nativeEvent Native browser event.
10436 * @return {?string} The string corresponding to this `beforeInput` event.
10437 */
10438
10439
10440function getNativeBeforeInputChars(topLevelType, nativeEvent) {
10441 switch (topLevelType) {
10442 case TOP_COMPOSITION_END:
10443 return getDataFromCustomEvent(nativeEvent);
10444
10445 case TOP_KEY_PRESS:
10446 /**
10447 * If native `textInput` events are available, our goal is to make
10448 * use of them. However, there is a special case: the spacebar key.
10449 * In Webkit, preventing default on a spacebar `textInput` event
10450 * cancels character insertion, but it *also* causes the browser
10451 * to fall back to its default spacebar behavior of scrolling the
10452 * page.
10453 *
10454 * Tracking at:
10455 * https://code.google.com/p/chromium/issues/detail?id=355103
10456 *
10457 * To avoid this issue, use the keypress event as if no `textInput`
10458 * event is available.
10459 */
10460 var which = nativeEvent.which;
10461
10462 if (which !== SPACEBAR_CODE) {
10463 return null;
10464 }
10465
10466 hasSpaceKeypress = true;
10467 return SPACEBAR_CHAR;
10468
10469 case TOP_TEXT_INPUT:
10470 // Record the characters to be added to the DOM.
10471 var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
10472 // it at the keypress level and bail immediately. Android Chrome
10473 // doesn't give us keycodes, so we need to ignore it.
10474
10475 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
10476 return null;
10477 }
10478
10479 return chars;
10480
10481 default:
10482 // For other native event types, do nothing.
10483 return null;
10484 }
10485}
10486/**
10487 * For browsers that do not provide the `textInput` event, extract the
10488 * appropriate string to use for SyntheticInputEvent.
10489 *
10490 * @param {number} topLevelType Number from `TopLevelEventTypes`.
10491 * @param {object} nativeEvent Native browser event.
10492 * @return {?string} The fallback string for this `beforeInput` event.
10493 */
10494
10495
10496function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
10497 // If we are currently composing (IME) and using a fallback to do so,
10498 // try to extract the composed characters from the fallback object.
10499 // If composition event is available, we extract a string only at
10500 // compositionevent, otherwise extract it at fallback events.
10501 if (isComposing) {
10502 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10503 var chars = getData();
10504 reset();
10505 isComposing = false;
10506 return chars;
10507 }
10508
10509 return null;
10510 }
10511
10512 switch (topLevelType) {
10513 case TOP_PASTE:
10514 // If a paste event occurs after a keypress, throw out the input
10515 // chars. Paste events should not lead to BeforeInput events.
10516 return null;
10517
10518 case TOP_KEY_PRESS:
10519 /**
10520 * As of v27, Firefox may fire keypress events even when no character
10521 * will be inserted. A few possibilities:
10522 *
10523 * - `which` is `0`. Arrow keys, Esc key, etc.
10524 *
10525 * - `which` is the pressed key code, but no char is available.
10526 * Ex: 'AltGr + d` in Polish. There is no modified character for
10527 * this key combination and no character is inserted into the
10528 * document, but FF fires the keypress for char code `100` anyway.
10529 * No `input` event will occur.
10530 *
10531 * - `which` is the pressed key code, but a command combination is
10532 * being used. Ex: `Cmd+C`. No character is inserted, and no
10533 * `input` event will occur.
10534 */
10535 if (!isKeypressCommand(nativeEvent)) {
10536 // IE fires the `keypress` event when a user types an emoji via
10537 // Touch keyboard of Windows. In such a case, the `char` property
10538 // holds an emoji character like `\uD83D\uDE0A`. Because its length
10539 // is 2, the property `which` does not represent an emoji correctly.
10540 // In such a case, we directly return the `char` property instead of
10541 // using `which`.
10542 if (nativeEvent.char && nativeEvent.char.length > 1) {
10543 return nativeEvent.char;
10544 } else if (nativeEvent.which) {
10545 return String.fromCharCode(nativeEvent.which);
10546 }
10547 }
10548
10549 return null;
10550
10551 case TOP_COMPOSITION_END:
10552 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
10553
10554 default:
10555 return null;
10556 }
10557}
10558/**
10559 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
10560 * `textInput` or fallback behavior.
10561 *
10562 * @return {?object} A SyntheticInputEvent.
10563 */
10564
10565
10566function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10567 var chars;
10568
10569 if (canUseTextInputEvent) {
10570 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
10571 } else {
10572 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
10573 } // If no characters are being inserted, no BeforeInput event should
10574 // be fired.
10575
10576
10577 if (!chars) {
10578 return null;
10579 }
10580
10581 var event = SyntheticInputEvent.getPooled(eventTypes$1.beforeInput, targetInst, nativeEvent, nativeEventTarget);
10582 event.data = chars;
10583 accumulateTwoPhaseDispatches(event);
10584 return event;
10585}
10586/**
10587 * Create an `onBeforeInput` event to match
10588 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
10589 *
10590 * This event plugin is based on the native `textInput` event
10591 * available in Chrome, Safari, Opera, and IE. This event fires after
10592 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
10593 *
10594 * `beforeInput` is spec'd but not implemented in any browsers, and
10595 * the `input` event does not provide any useful information about what has
10596 * actually been added, contrary to the spec. Thus, `textInput` is the best
10597 * available event to identify the characters that have actually been inserted
10598 * into the target node.
10599 *
10600 * This plugin is also responsible for emitting `composition` events, thus
10601 * allowing us to share composition fallback code for both `beforeInput` and
10602 * `composition` event types.
10603 */
10604
10605
10606var BeforeInputEventPlugin = {
10607 eventTypes: eventTypes$1,
10608 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10609 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10610 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10611
10612 if (composition === null) {
10613 return beforeInput;
10614 }
10615
10616 if (beforeInput === null) {
10617 return composition;
10618 }
10619
10620 return [composition, beforeInput];
10621 }
10622};
10623
10624/**
10625 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
10626 */
10627var supportedInputTypes = {
10628 color: true,
10629 date: true,
10630 datetime: true,
10631 'datetime-local': true,
10632 email: true,
10633 month: true,
10634 number: true,
10635 password: true,
10636 range: true,
10637 search: true,
10638 tel: true,
10639 text: true,
10640 time: true,
10641 url: true,
10642 week: true
10643};
10644
10645function isTextInputElement(elem) {
10646 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
10647
10648 if (nodeName === 'input') {
10649 return !!supportedInputTypes[elem.type];
10650 }
10651
10652 if (nodeName === 'textarea') {
10653 return true;
10654 }
10655
10656 return false;
10657}
10658
10659var eventTypes$2 = {
10660 change: {
10661 phasedRegistrationNames: {
10662 bubbled: 'onChange',
10663 captured: 'onChangeCapture'
10664 },
10665 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
10666 }
10667};
10668
10669function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
10670 var event = SyntheticEvent.getPooled(eventTypes$2.change, inst, nativeEvent, target);
10671 event.type = 'change'; // Flag this event loop as needing state restore.
10672
10673 enqueueStateRestore(target);
10674 accumulateTwoPhaseDispatches(event);
10675 return event;
10676}
10677/**
10678 * For IE shims
10679 */
10680
10681
10682var activeElement = null;
10683var activeElementInst = null;
10684/**
10685 * SECTION: handle `change` event
10686 */
10687
10688function shouldUseChangeEvent(elem) {
10689 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
10690 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
10691}
10692
10693function manualDispatchChangeEvent(nativeEvent) {
10694 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
10695 // other events and have it go through ReactBrowserEventEmitter. Since it
10696 // doesn't, we manually listen for the events and so we have to enqueue and
10697 // process the abstract event manually.
10698 //
10699 // Batching is necessary here in order to ensure that all event handlers run
10700 // before the next rerender (including event handlers attached to ancestor
10701 // elements instead of directly on the input). Without this, controlled
10702 // components don't work properly in conjunction with event bubbling because
10703 // the component is rerendered and the value reverted before all the event
10704 // handlers can run. See https://github.com/facebook/react/issues/708.
10705
10706 batchedUpdates(runEventInBatch, event);
10707}
10708
10709function runEventInBatch(event) {
10710 runEventsInBatch(event);
10711}
10712
10713function getInstIfValueChanged(targetInst) {
10714 var targetNode = getNodeFromInstance$1(targetInst);
10715
10716 if (updateValueIfChanged(targetNode)) {
10717 return targetInst;
10718 }
10719}
10720
10721function getTargetInstForChangeEvent(topLevelType, targetInst) {
10722 if (topLevelType === TOP_CHANGE) {
10723 return targetInst;
10724 }
10725}
10726/**
10727 * SECTION: handle `input` event
10728 */
10729
10730
10731var isInputEventSupported = false;
10732
10733if (canUseDOM) {
10734 // IE9 claims to support the input event but fails to trigger it when
10735 // deleting text, so we ignore its input events.
10736 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
10737}
10738/**
10739 * (For IE <=9) Starts tracking propertychange events on the passed-in element
10740 * and override the value property so that we can distinguish user events from
10741 * value changes in JS.
10742 */
10743
10744
10745function startWatchingForValueChange(target, targetInst) {
10746 activeElement = target;
10747 activeElementInst = targetInst;
10748 activeElement.attachEvent('onpropertychange', handlePropertyChange);
10749}
10750/**
10751 * (For IE <=9) Removes the event listeners from the currently-tracked element,
10752 * if any exists.
10753 */
10754
10755
10756function stopWatchingForValueChange() {
10757 if (!activeElement) {
10758 return;
10759 }
10760
10761 activeElement.detachEvent('onpropertychange', handlePropertyChange);
10762 activeElement = null;
10763 activeElementInst = null;
10764}
10765/**
10766 * (For IE <=9) Handles a propertychange event, sending a `change` event if
10767 * the value of the active element has changed.
10768 */
10769
10770
10771function handlePropertyChange(nativeEvent) {
10772 if (nativeEvent.propertyName !== 'value') {
10773 return;
10774 }
10775
10776 if (getInstIfValueChanged(activeElementInst)) {
10777 manualDispatchChangeEvent(nativeEvent);
10778 }
10779}
10780
10781function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
10782 if (topLevelType === TOP_FOCUS) {
10783 // In IE9, propertychange fires for most input events but is buggy and
10784 // doesn't fire when text is deleted, but conveniently, selectionchange
10785 // appears to fire in all of the remaining cases so we catch those and
10786 // forward the event if the value has changed
10787 // In either case, we don't want to call the event handler if the value
10788 // is changed from JS so we redefine a setter for `.value` that updates
10789 // our activeElementValue variable, allowing us to ignore those changes
10790 //
10791 // stopWatching() should be a noop here but we call it just in case we
10792 // missed a blur event somehow.
10793 stopWatchingForValueChange();
10794 startWatchingForValueChange(target, targetInst);
10795 } else if (topLevelType === TOP_BLUR) {
10796 stopWatchingForValueChange();
10797 }
10798} // For IE8 and IE9.
10799
10800
10801function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
10802 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
10803 // On the selectionchange event, the target is just document which isn't
10804 // helpful for us so just check activeElement instead.
10805 //
10806 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
10807 // propertychange on the first input event after setting `value` from a
10808 // script and fires only keydown, keypress, keyup. Catching keyup usually
10809 // gets it and catching keydown lets us fire an event for the first
10810 // keystroke if user does a key repeat (it'll be a little delayed: right
10811 // before the second keystroke). Other input methods (e.g., paste) seem to
10812 // fire selectionchange normally.
10813 return getInstIfValueChanged(activeElementInst);
10814 }
10815}
10816/**
10817 * SECTION: handle `click` event
10818 */
10819
10820
10821function shouldUseClickEvent(elem) {
10822 // Use the `click` event to detect changes to checkbox and radio inputs.
10823 // This approach works across all browsers, whereas `change` does not fire
10824 // until `blur` in IE8.
10825 var nodeName = elem.nodeName;
10826 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
10827}
10828
10829function getTargetInstForClickEvent(topLevelType, targetInst) {
10830 if (topLevelType === TOP_CLICK) {
10831 return getInstIfValueChanged(targetInst);
10832 }
10833}
10834
10835function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
10836 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
10837 return getInstIfValueChanged(targetInst);
10838 }
10839}
10840
10841function handleControlledInputBlur(node) {
10842 var state = node._wrapperState;
10843
10844 if (!state || !state.controlled || node.type !== 'number') {
10845 return;
10846 }
10847
10848 if (!disableInputAttributeSyncing) {
10849 // If controlled, assign the value attribute to the current value on blur
10850 setDefaultValue(node, 'number', node.value);
10851 }
10852}
10853/**
10854 * This plugin creates an `onChange` event that normalizes change events
10855 * across form elements. This event fires at a time when it's possible to
10856 * change the element's value without seeing a flicker.
10857 *
10858 * Supported elements are:
10859 * - input (see `isTextInputElement`)
10860 * - textarea
10861 * - select
10862 */
10863
10864
10865var ChangeEventPlugin = {
10866 eventTypes: eventTypes$2,
10867 _isInputEventSupported: isInputEventSupported,
10868 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10869 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
10870 var getTargetInstFunc, handleEventFunc;
10871
10872 if (shouldUseChangeEvent(targetNode)) {
10873 getTargetInstFunc = getTargetInstForChangeEvent;
10874 } else if (isTextInputElement(targetNode)) {
10875 if (isInputEventSupported) {
10876 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
10877 } else {
10878 getTargetInstFunc = getTargetInstForInputEventPolyfill;
10879 handleEventFunc = handleEventsForInputEventPolyfill;
10880 }
10881 } else if (shouldUseClickEvent(targetNode)) {
10882 getTargetInstFunc = getTargetInstForClickEvent;
10883 }
10884
10885 if (getTargetInstFunc) {
10886 var inst = getTargetInstFunc(topLevelType, targetInst);
10887
10888 if (inst) {
10889 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
10890 return event;
10891 }
10892 }
10893
10894 if (handleEventFunc) {
10895 handleEventFunc(topLevelType, targetNode, targetInst);
10896 } // When blurring, set the value attribute for number inputs
10897
10898
10899 if (topLevelType === TOP_BLUR) {
10900 handleControlledInputBlur(targetNode);
10901 }
10902 }
10903};
10904
10905/**
10906 * Module that is injectable into `EventPluginHub`, that specifies a
10907 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
10908 * plugins, without having to package every one of them. This is better than
10909 * having plugins be ordered in the same order that they are injected because
10910 * that ordering would be influenced by the packaging order.
10911 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
10912 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
10913 */
10914var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
10915
10916var eventTypes$3 = {
10917 mouseEnter: {
10918 registrationName: 'onMouseEnter',
10919 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
10920 },
10921 mouseLeave: {
10922 registrationName: 'onMouseLeave',
10923 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
10924 },
10925 pointerEnter: {
10926 registrationName: 'onPointerEnter',
10927 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
10928 },
10929 pointerLeave: {
10930 registrationName: 'onPointerLeave',
10931 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
10932 }
10933}; // We track the lastNativeEvent to ensure that when we encounter
10934// cases where we process the same nativeEvent multiple times,
10935// which can happen when have multiple ancestors, that we don't
10936// duplicate enter
10937
10938var lastNativeEvent;
10939var EnterLeaveEventPlugin = {
10940 eventTypes: eventTypes$3,
10941
10942 /**
10943 * For almost every interaction we care about, there will be both a top-level
10944 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
10945 * we do not extract duplicate events. However, moving the mouse into the
10946 * browser from outside will not fire a `mouseout` event. In this case, we use
10947 * the `mouseover` top-level event.
10948 */
10949 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10950 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
10951 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
10952
10953 if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
10954 // If this is an over event with a target, then we've already dispatched
10955 // the event in the out event of the other target. If this is replayed,
10956 // then it's because we couldn't dispatch against this target previously
10957 // so we have to do it now instead.
10958 return null;
10959 }
10960
10961 if (!isOutEvent && !isOverEvent) {
10962 // Must not be a mouse or pointer in or out - ignoring.
10963 return null;
10964 }
10965
10966 var win;
10967
10968 if (nativeEventTarget.window === nativeEventTarget) {
10969 // `nativeEventTarget` is probably a window object.
10970 win = nativeEventTarget;
10971 } else {
10972 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
10973 var doc = nativeEventTarget.ownerDocument;
10974
10975 if (doc) {
10976 win = doc.defaultView || doc.parentWindow;
10977 } else {
10978 win = window;
10979 }
10980 }
10981
10982 var from;
10983 var to;
10984
10985 if (isOutEvent) {
10986 from = targetInst;
10987 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
10988 to = related ? getClosestInstanceFromNode(related) : null;
10989
10990 if (to !== null) {
10991 var nearestMounted = getNearestMountedFiber(to);
10992
10993 if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
10994 to = null;
10995 }
10996 }
10997 } else {
10998 // Moving to a node from outside the window.
10999 from = null;
11000 to = targetInst;
11001 }
11002
11003 if (from === to) {
11004 // Nothing pertains to our managed components.
11005 return null;
11006 }
11007
11008 var eventInterface, leaveEventType, enterEventType, eventTypePrefix;
11009
11010 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
11011 eventInterface = SyntheticMouseEvent;
11012 leaveEventType = eventTypes$3.mouseLeave;
11013 enterEventType = eventTypes$3.mouseEnter;
11014 eventTypePrefix = 'mouse';
11015 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
11016 eventInterface = SyntheticPointerEvent;
11017 leaveEventType = eventTypes$3.pointerLeave;
11018 enterEventType = eventTypes$3.pointerEnter;
11019 eventTypePrefix = 'pointer';
11020 }
11021
11022 var fromNode = from == null ? win : getNodeFromInstance$1(from);
11023 var toNode = to == null ? win : getNodeFromInstance$1(to);
11024 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
11025 leave.type = eventTypePrefix + 'leave';
11026 leave.target = fromNode;
11027 leave.relatedTarget = toNode;
11028 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
11029 enter.type = eventTypePrefix + 'enter';
11030 enter.target = toNode;
11031 enter.relatedTarget = fromNode;
11032 accumulateEnterLeaveDispatches(leave, enter, from, to);
11033
11034 if (nativeEvent === lastNativeEvent) {
11035 lastNativeEvent = null;
11036 return [leave];
11037 }
11038
11039 lastNativeEvent = nativeEvent;
11040 return [leave, enter];
11041 }
11042};
11043
11044/**
11045 * inlined Object.is polyfill to avoid requiring consumers ship their own
11046 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
11047 */
11048function is(x, y) {
11049 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
11050 ;
11051}
11052
11053var is$1 = typeof Object.is === 'function' ? Object.is : is;
11054
11055var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
11056/**
11057 * Performs equality by iterating through keys on an object and returning false
11058 * when any key has values which are not strictly equal between the arguments.
11059 * Returns true when the values of all keys are strictly equal.
11060 */
11061
11062function shallowEqual(objA, objB) {
11063 if (is$1(objA, objB)) {
11064 return true;
11065 }
11066
11067 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
11068 return false;
11069 }
11070
11071 var keysA = Object.keys(objA);
11072 var keysB = Object.keys(objB);
11073
11074 if (keysA.length !== keysB.length) {
11075 return false;
11076 } // Test for A's keys different from B.
11077
11078
11079 for (var i = 0; i < keysA.length; i++) {
11080 if (!hasOwnProperty$2.call(objB, keysA[i]) || !is$1(objA[keysA[i]], objB[keysA[i]])) {
11081 return false;
11082 }
11083 }
11084
11085 return true;
11086}
11087
11088var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
11089var eventTypes$4 = {
11090 select: {
11091 phasedRegistrationNames: {
11092 bubbled: 'onSelect',
11093 captured: 'onSelectCapture'
11094 },
11095 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]
11096 }
11097};
11098var activeElement$1 = null;
11099var activeElementInst$1 = null;
11100var lastSelection = null;
11101var mouseDown = false;
11102/**
11103 * Get an object which is a unique representation of the current selection.
11104 *
11105 * The return value will not be consistent across nodes or browsers, but
11106 * two identical selections on the same node will return identical objects.
11107 *
11108 * @param {DOMElement} node
11109 * @return {object}
11110 */
11111
11112function getSelection$1(node) {
11113 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
11114 return {
11115 start: node.selectionStart,
11116 end: node.selectionEnd
11117 };
11118 } else {
11119 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
11120 var selection = win.getSelection();
11121 return {
11122 anchorNode: selection.anchorNode,
11123 anchorOffset: selection.anchorOffset,
11124 focusNode: selection.focusNode,
11125 focusOffset: selection.focusOffset
11126 };
11127 }
11128}
11129/**
11130 * Get document associated with the event target.
11131 *
11132 * @param {object} nativeEventTarget
11133 * @return {Document}
11134 */
11135
11136
11137function getEventTargetDocument(eventTarget) {
11138 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
11139}
11140/**
11141 * Poll selection to see whether it's changed.
11142 *
11143 * @param {object} nativeEvent
11144 * @param {object} nativeEventTarget
11145 * @return {?SyntheticEvent}
11146 */
11147
11148
11149function constructSelectEvent(nativeEvent, nativeEventTarget) {
11150 // Ensure we have the right element, and that the user is not dragging a
11151 // selection (this matches native `select` event behavior). In HTML5, select
11152 // fires only on input and textarea thus if there's no focused element we
11153 // won't dispatch.
11154 var doc = getEventTargetDocument(nativeEventTarget);
11155
11156 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
11157 return null;
11158 } // Only fire when selection has actually changed.
11159
11160
11161 var currentSelection = getSelection$1(activeElement$1);
11162
11163 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
11164 lastSelection = currentSelection;
11165 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$4.select, activeElementInst$1, nativeEvent, nativeEventTarget);
11166 syntheticEvent.type = 'select';
11167 syntheticEvent.target = activeElement$1;
11168 accumulateTwoPhaseDispatches(syntheticEvent);
11169 return syntheticEvent;
11170 }
11171
11172 return null;
11173}
11174/**
11175 * This plugin creates an `onSelect` event that normalizes select events
11176 * across form elements.
11177 *
11178 * Supported elements are:
11179 * - input (see `isTextInputElement`)
11180 * - textarea
11181 * - contentEditable
11182 *
11183 * This differs from native browser implementations in the following ways:
11184 * - Fires on contentEditable fields as well as inputs.
11185 * - Fires for collapsed selection.
11186 * - Fires after user input.
11187 */
11188
11189
11190var SelectEventPlugin = {
11191 eventTypes: eventTypes$4,
11192 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11193 var doc = getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
11194 // not extract events. See #3639.
11195
11196 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
11197 return null;
11198 }
11199
11200 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
11201
11202 switch (topLevelType) {
11203 // Track the input node that has focus.
11204 case TOP_FOCUS:
11205 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
11206 activeElement$1 = targetNode;
11207 activeElementInst$1 = targetInst;
11208 lastSelection = null;
11209 }
11210
11211 break;
11212
11213 case TOP_BLUR:
11214 activeElement$1 = null;
11215 activeElementInst$1 = null;
11216 lastSelection = null;
11217 break;
11218 // Don't fire the event while the user is dragging. This matches the
11219 // semantics of the native select event.
11220
11221 case TOP_MOUSE_DOWN:
11222 mouseDown = true;
11223 break;
11224
11225 case TOP_CONTEXT_MENU:
11226 case TOP_MOUSE_UP:
11227 case TOP_DRAG_END:
11228 mouseDown = false;
11229 return constructSelectEvent(nativeEvent, nativeEventTarget);
11230 // Chrome and IE fire non-standard event when selection is changed (and
11231 // sometimes when it hasn't). IE's event fires out of order with respect
11232 // to key and input events on deletion, so we discard it.
11233 //
11234 // Firefox doesn't support selectionchange, so check selection status
11235 // after each key entry. The selection changes after keydown and before
11236 // keyup, but we check on keydown as well in the case of holding down a
11237 // key, when multiple keydown events are fired but only one keyup is.
11238 // This is also our approach for IE handling, for the reason above.
11239
11240 case TOP_SELECTION_CHANGE:
11241 if (skipSelectionChangeEvent) {
11242 break;
11243 }
11244
11245 // falls through
11246
11247 case TOP_KEY_DOWN:
11248 case TOP_KEY_UP:
11249 return constructSelectEvent(nativeEvent, nativeEventTarget);
11250 }
11251
11252 return null;
11253 }
11254};
11255
11256/**
11257 * Inject modules for resolving DOM hierarchy and plugin ordering.
11258 */
11259
11260injection.injectEventPluginOrder(DOMEventPluginOrder);
11261setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
11262/**
11263 * Some important event plugins included by default (without having to require
11264 * them).
11265 */
11266
11267injection.injectEventPluginsByName({
11268 SimpleEventPlugin: SimpleEventPlugin,
11269 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
11270 ChangeEventPlugin: ChangeEventPlugin,
11271 SelectEventPlugin: SelectEventPlugin,
11272 BeforeInputEventPlugin: BeforeInputEventPlugin
11273});
11274
11275// Prefix measurements so that it's possible to filter them.
11276// Longer prefixes are hard to read in DevTools.
11277var reactEmoji = "\u269B";
11278var warningEmoji = "\u26D4";
11279var 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.
11280// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
11281
11282var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
11283// Reusing `currentFiber` would be confusing for this because user code fiber
11284// can change during commit phase too, but we don't need to unwind it (since
11285// lifecycles in the commit phase don't resemble a tree).
11286
11287var currentPhase = null;
11288var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
11289// so we will keep track of it, and include it in the report.
11290// Track commits caused by cascading updates.
11291
11292var isCommitting = false;
11293var hasScheduledUpdateInCurrentCommit = false;
11294var hasScheduledUpdateInCurrentPhase = false;
11295var commitCountInCurrentWorkLoop = 0;
11296var effectCountInCurrentCommit = 0;
11297// to avoid stretch the commit phase with measurement overhead.
11298
11299var labelsInCurrentCommit = new Set();
11300
11301var formatMarkName = function (markName) {
11302 return reactEmoji + " " + markName;
11303};
11304
11305var formatLabel = function (label, warning) {
11306 var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
11307 var suffix = warning ? " Warning: " + warning : '';
11308 return "" + prefix + label + suffix;
11309};
11310
11311var beginMark = function (markName) {
11312 performance.mark(formatMarkName(markName));
11313};
11314
11315var clearMark = function (markName) {
11316 performance.clearMarks(formatMarkName(markName));
11317};
11318
11319var endMark = function (label, markName, warning) {
11320 var formattedMarkName = formatMarkName(markName);
11321 var formattedLabel = formatLabel(label, warning);
11322
11323 try {
11324 performance.measure(formattedLabel, formattedMarkName);
11325 } catch (err) {} // If previous mark was missing for some reason, this will throw.
11326 // This could only happen if React crashed in an unexpected place earlier.
11327 // Don't pile on with more errors.
11328 // Clear marks immediately to avoid growing buffer.
11329
11330
11331 performance.clearMarks(formattedMarkName);
11332 performance.clearMeasures(formattedLabel);
11333};
11334
11335var getFiberMarkName = function (label, debugID) {
11336 return label + " (#" + debugID + ")";
11337};
11338
11339var getFiberLabel = function (componentName, isMounted, phase) {
11340 if (phase === null) {
11341 // These are composite component total time measurements.
11342 return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
11343 } else {
11344 // Composite component methods.
11345 return componentName + "." + phase;
11346 }
11347};
11348
11349var beginFiberMark = function (fiber, phase) {
11350 var componentName = getComponentName(fiber.type) || 'Unknown';
11351 var debugID = fiber._debugID;
11352 var isMounted = fiber.alternate !== null;
11353 var label = getFiberLabel(componentName, isMounted, phase);
11354
11355 if (isCommitting && labelsInCurrentCommit.has(label)) {
11356 // During the commit phase, we don't show duplicate labels because
11357 // there is a fixed overhead for every measurement, and we don't
11358 // want to stretch the commit phase beyond necessary.
11359 return false;
11360 }
11361
11362 labelsInCurrentCommit.add(label);
11363 var markName = getFiberMarkName(label, debugID);
11364 beginMark(markName);
11365 return true;
11366};
11367
11368var clearFiberMark = function (fiber, phase) {
11369 var componentName = getComponentName(fiber.type) || 'Unknown';
11370 var debugID = fiber._debugID;
11371 var isMounted = fiber.alternate !== null;
11372 var label = getFiberLabel(componentName, isMounted, phase);
11373 var markName = getFiberMarkName(label, debugID);
11374 clearMark(markName);
11375};
11376
11377var endFiberMark = function (fiber, phase, warning) {
11378 var componentName = getComponentName(fiber.type) || 'Unknown';
11379 var debugID = fiber._debugID;
11380 var isMounted = fiber.alternate !== null;
11381 var label = getFiberLabel(componentName, isMounted, phase);
11382 var markName = getFiberMarkName(label, debugID);
11383 endMark(label, markName, warning);
11384};
11385
11386var shouldIgnoreFiber = function (fiber) {
11387 // Host components should be skipped in the timeline.
11388 // We could check typeof fiber.type, but does this work with RN?
11389 switch (fiber.tag) {
11390 case HostRoot:
11391 case HostComponent:
11392 case HostText:
11393 case HostPortal:
11394 case Fragment:
11395 case ContextProvider:
11396 case ContextConsumer:
11397 case Mode:
11398 return true;
11399
11400 default:
11401 return false;
11402 }
11403};
11404
11405var clearPendingPhaseMeasurement = function () {
11406 if (currentPhase !== null && currentPhaseFiber !== null) {
11407 clearFiberMark(currentPhaseFiber, currentPhase);
11408 }
11409
11410 currentPhaseFiber = null;
11411 currentPhase = null;
11412 hasScheduledUpdateInCurrentPhase = false;
11413};
11414
11415var pauseTimers = function () {
11416 // Stops all currently active measurements so that they can be resumed
11417 // if we continue in a later deferred loop from the same unit of work.
11418 var fiber = currentFiber;
11419
11420 while (fiber) {
11421 if (fiber._debugIsCurrentlyTiming) {
11422 endFiberMark(fiber, null, null);
11423 }
11424
11425 fiber = fiber.return;
11426 }
11427};
11428
11429var resumeTimersRecursively = function (fiber) {
11430 if (fiber.return !== null) {
11431 resumeTimersRecursively(fiber.return);
11432 }
11433
11434 if (fiber._debugIsCurrentlyTiming) {
11435 beginFiberMark(fiber, null);
11436 }
11437};
11438
11439var resumeTimers = function () {
11440 // Resumes all measurements that were active during the last deferred loop.
11441 if (currentFiber !== null) {
11442 resumeTimersRecursively(currentFiber);
11443 }
11444};
11445
11446function recordEffect() {
11447 if (enableUserTimingAPI) {
11448 effectCountInCurrentCommit++;
11449 }
11450}
11451function recordScheduleUpdate() {
11452 if (enableUserTimingAPI) {
11453 if (isCommitting) {
11454 hasScheduledUpdateInCurrentCommit = true;
11455 }
11456
11457 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
11458 hasScheduledUpdateInCurrentPhase = true;
11459 }
11460 }
11461}
11462
11463
11464function startWorkTimer(fiber) {
11465 if (enableUserTimingAPI) {
11466 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11467 return;
11468 } // If we pause, this is the fiber to unwind from.
11469
11470
11471 currentFiber = fiber;
11472
11473 if (!beginFiberMark(fiber, null)) {
11474 return;
11475 }
11476
11477 fiber._debugIsCurrentlyTiming = true;
11478 }
11479}
11480function cancelWorkTimer(fiber) {
11481 if (enableUserTimingAPI) {
11482 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11483 return;
11484 } // Remember we shouldn't complete measurement for this fiber.
11485 // Otherwise flamechart will be deep even for small updates.
11486
11487
11488 fiber._debugIsCurrentlyTiming = false;
11489 clearFiberMark(fiber, null);
11490 }
11491}
11492function stopWorkTimer(fiber) {
11493 if (enableUserTimingAPI) {
11494 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11495 return;
11496 } // If we pause, its parent is the fiber to unwind from.
11497
11498
11499 currentFiber = fiber.return;
11500
11501 if (!fiber._debugIsCurrentlyTiming) {
11502 return;
11503 }
11504
11505 fiber._debugIsCurrentlyTiming = false;
11506 endFiberMark(fiber, null, null);
11507 }
11508}
11509function stopFailedWorkTimer(fiber) {
11510 if (enableUserTimingAPI) {
11511 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11512 return;
11513 } // If we pause, its parent is the fiber to unwind from.
11514
11515
11516 currentFiber = fiber.return;
11517
11518 if (!fiber._debugIsCurrentlyTiming) {
11519 return;
11520 }
11521
11522 fiber._debugIsCurrentlyTiming = false;
11523 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
11524 endFiberMark(fiber, null, warning);
11525 }
11526}
11527function startPhaseTimer(fiber, phase) {
11528 if (enableUserTimingAPI) {
11529 if (!supportsUserTiming) {
11530 return;
11531 }
11532
11533 clearPendingPhaseMeasurement();
11534
11535 if (!beginFiberMark(fiber, phase)) {
11536 return;
11537 }
11538
11539 currentPhaseFiber = fiber;
11540 currentPhase = phase;
11541 }
11542}
11543function stopPhaseTimer() {
11544 if (enableUserTimingAPI) {
11545 if (!supportsUserTiming) {
11546 return;
11547 }
11548
11549 if (currentPhase !== null && currentPhaseFiber !== null) {
11550 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
11551 endFiberMark(currentPhaseFiber, currentPhase, warning);
11552 }
11553
11554 currentPhase = null;
11555 currentPhaseFiber = null;
11556 }
11557}
11558function startWorkLoopTimer(nextUnitOfWork) {
11559 if (enableUserTimingAPI) {
11560 currentFiber = nextUnitOfWork;
11561
11562 if (!supportsUserTiming) {
11563 return;
11564 }
11565
11566 commitCountInCurrentWorkLoop = 0; // This is top level call.
11567 // Any other measurements are performed within.
11568
11569 beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.
11570
11571 resumeTimers();
11572 }
11573}
11574function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
11575 if (enableUserTimingAPI) {
11576 if (!supportsUserTiming) {
11577 return;
11578 }
11579
11580 var warning = null;
11581
11582 if (interruptedBy !== null) {
11583 if (interruptedBy.tag === HostRoot) {
11584 warning = 'A top-level update interrupted the previous render';
11585 } else {
11586 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
11587 warning = "An update to " + componentName + " interrupted the previous render";
11588 }
11589 } else if (commitCountInCurrentWorkLoop > 1) {
11590 warning = 'There were cascading updates';
11591 }
11592
11593 commitCountInCurrentWorkLoop = 0;
11594 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.
11595
11596 pauseTimers();
11597 endMark(label, '(React Tree Reconciliation)', warning);
11598 }
11599}
11600function startCommitTimer() {
11601 if (enableUserTimingAPI) {
11602 if (!supportsUserTiming) {
11603 return;
11604 }
11605
11606 isCommitting = true;
11607 hasScheduledUpdateInCurrentCommit = false;
11608 labelsInCurrentCommit.clear();
11609 beginMark('(Committing Changes)');
11610 }
11611}
11612function stopCommitTimer() {
11613 if (enableUserTimingAPI) {
11614 if (!supportsUserTiming) {
11615 return;
11616 }
11617
11618 var warning = null;
11619
11620 if (hasScheduledUpdateInCurrentCommit) {
11621 warning = 'Lifecycle hook scheduled a cascading update';
11622 } else if (commitCountInCurrentWorkLoop > 0) {
11623 warning = 'Caused by a cascading update in earlier commit';
11624 }
11625
11626 hasScheduledUpdateInCurrentCommit = false;
11627 commitCountInCurrentWorkLoop++;
11628 isCommitting = false;
11629 labelsInCurrentCommit.clear();
11630 endMark('(Committing Changes)', '(Committing Changes)', warning);
11631 }
11632}
11633function startCommitSnapshotEffectsTimer() {
11634 if (enableUserTimingAPI) {
11635 if (!supportsUserTiming) {
11636 return;
11637 }
11638
11639 effectCountInCurrentCommit = 0;
11640 beginMark('(Committing Snapshot Effects)');
11641 }
11642}
11643function stopCommitSnapshotEffectsTimer() {
11644 if (enableUserTimingAPI) {
11645 if (!supportsUserTiming) {
11646 return;
11647 }
11648
11649 var count = effectCountInCurrentCommit;
11650 effectCountInCurrentCommit = 0;
11651 endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
11652 }
11653}
11654function startCommitHostEffectsTimer() {
11655 if (enableUserTimingAPI) {
11656 if (!supportsUserTiming) {
11657 return;
11658 }
11659
11660 effectCountInCurrentCommit = 0;
11661 beginMark('(Committing Host Effects)');
11662 }
11663}
11664function stopCommitHostEffectsTimer() {
11665 if (enableUserTimingAPI) {
11666 if (!supportsUserTiming) {
11667 return;
11668 }
11669
11670 var count = effectCountInCurrentCommit;
11671 effectCountInCurrentCommit = 0;
11672 endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
11673 }
11674}
11675function startCommitLifeCyclesTimer() {
11676 if (enableUserTimingAPI) {
11677 if (!supportsUserTiming) {
11678 return;
11679 }
11680
11681 effectCountInCurrentCommit = 0;
11682 beginMark('(Calling Lifecycle Methods)');
11683 }
11684}
11685function stopCommitLifeCyclesTimer() {
11686 if (enableUserTimingAPI) {
11687 if (!supportsUserTiming) {
11688 return;
11689 }
11690
11691 var count = effectCountInCurrentCommit;
11692 effectCountInCurrentCommit = 0;
11693 endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
11694 }
11695}
11696
11697var valueStack = [];
11698var fiberStack;
11699
11700{
11701 fiberStack = [];
11702}
11703
11704var index = -1;
11705
11706function createCursor(defaultValue) {
11707 return {
11708 current: defaultValue
11709 };
11710}
11711
11712function pop(cursor, fiber) {
11713 if (index < 0) {
11714 {
11715 warningWithoutStack$1(false, 'Unexpected pop.');
11716 }
11717
11718 return;
11719 }
11720
11721 {
11722 if (fiber !== fiberStack[index]) {
11723 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
11724 }
11725 }
11726
11727 cursor.current = valueStack[index];
11728 valueStack[index] = null;
11729
11730 {
11731 fiberStack[index] = null;
11732 }
11733
11734 index--;
11735}
11736
11737function push(cursor, value, fiber) {
11738 index++;
11739 valueStack[index] = cursor.current;
11740
11741 {
11742 fiberStack[index] = fiber;
11743 }
11744
11745 cursor.current = value;
11746}
11747
11748var warnedAboutMissingGetChildContext;
11749
11750{
11751 warnedAboutMissingGetChildContext = {};
11752}
11753
11754var emptyContextObject = {};
11755
11756{
11757 Object.freeze(emptyContextObject);
11758} // A cursor to the current merged context object on the stack.
11759
11760
11761var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
11762
11763var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
11764// We use this to get access to the parent context after we have already
11765// pushed the next context provider, and now need to merge their contexts.
11766
11767var previousContext = emptyContextObject;
11768
11769function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
11770 if (disableLegacyContext) {
11771 return emptyContextObject;
11772 } else {
11773 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
11774 // If the fiber is a context provider itself, when we read its context
11775 // we may have already pushed its own child context on the stack. A context
11776 // provider should not "see" its own child context. Therefore we read the
11777 // previous (parent) context instead for a context provider.
11778 return previousContext;
11779 }
11780
11781 return contextStackCursor.current;
11782 }
11783}
11784
11785function cacheContext(workInProgress, unmaskedContext, maskedContext) {
11786 if (disableLegacyContext) {
11787 return;
11788 } else {
11789 var instance = workInProgress.stateNode;
11790 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
11791 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
11792 }
11793}
11794
11795function getMaskedContext(workInProgress, unmaskedContext) {
11796 if (disableLegacyContext) {
11797 return emptyContextObject;
11798 } else {
11799 var type = workInProgress.type;
11800 var contextTypes = type.contextTypes;
11801
11802 if (!contextTypes) {
11803 return emptyContextObject;
11804 } // Avoid recreating masked context unless unmasked context has changed.
11805 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
11806 // This may trigger infinite loops if componentWillReceiveProps calls setState.
11807
11808
11809 var instance = workInProgress.stateNode;
11810
11811 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
11812 return instance.__reactInternalMemoizedMaskedChildContext;
11813 }
11814
11815 var context = {};
11816
11817 for (var key in contextTypes) {
11818 context[key] = unmaskedContext[key];
11819 }
11820
11821 {
11822 var name = getComponentName(type) || 'Unknown';
11823 checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
11824 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
11825 // Context is created before the class component is instantiated so check for instance.
11826
11827
11828 if (instance) {
11829 cacheContext(workInProgress, unmaskedContext, context);
11830 }
11831
11832 return context;
11833 }
11834}
11835
11836function hasContextChanged() {
11837 if (disableLegacyContext) {
11838 return false;
11839 } else {
11840 return didPerformWorkStackCursor.current;
11841 }
11842}
11843
11844function isContextProvider(type) {
11845 if (disableLegacyContext) {
11846 return false;
11847 } else {
11848 var childContextTypes = type.childContextTypes;
11849 return childContextTypes !== null && childContextTypes !== undefined;
11850 }
11851}
11852
11853function popContext(fiber) {
11854 if (disableLegacyContext) {
11855 return;
11856 } else {
11857 pop(didPerformWorkStackCursor, fiber);
11858 pop(contextStackCursor, fiber);
11859 }
11860}
11861
11862function popTopLevelContextObject(fiber) {
11863 if (disableLegacyContext) {
11864 return;
11865 } else {
11866 pop(didPerformWorkStackCursor, fiber);
11867 pop(contextStackCursor, fiber);
11868 }
11869}
11870
11871function pushTopLevelContextObject(fiber, context, didChange) {
11872 if (disableLegacyContext) {
11873 return;
11874 } else {
11875 if (!(contextStackCursor.current === emptyContextObject)) {
11876 {
11877 throw Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
11878 }
11879 }
11880
11881 push(contextStackCursor, context, fiber);
11882 push(didPerformWorkStackCursor, didChange, fiber);
11883 }
11884}
11885
11886function processChildContext(fiber, type, parentContext) {
11887 if (disableLegacyContext) {
11888 return parentContext;
11889 } else {
11890 var instance = fiber.stateNode;
11891 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
11892 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
11893
11894 if (typeof instance.getChildContext !== 'function') {
11895 {
11896 var componentName = getComponentName(type) || 'Unknown';
11897
11898 if (!warnedAboutMissingGetChildContext[componentName]) {
11899 warnedAboutMissingGetChildContext[componentName] = true;
11900 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);
11901 }
11902 }
11903
11904 return parentContext;
11905 }
11906
11907 var childContext;
11908
11909 {
11910 setCurrentPhase('getChildContext');
11911 }
11912
11913 startPhaseTimer(fiber, 'getChildContext');
11914 childContext = instance.getChildContext();
11915 stopPhaseTimer();
11916
11917 {
11918 setCurrentPhase(null);
11919 }
11920
11921 for (var contextKey in childContext) {
11922 if (!(contextKey in childContextTypes)) {
11923 {
11924 throw Error((getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
11925 }
11926 }
11927 }
11928
11929 {
11930 var name = getComponentName(type) || 'Unknown';
11931 checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
11932 // somebody calls unstable_renderSubtreeIntoContainer() and we process
11933 // context from the parent component instance. The stack will be missing
11934 // because it's outside of the reconciliation, and so the pointer has not
11935 // been set. This is rare and doesn't matter. We'll also remove that API.
11936 getCurrentFiberStackInDev);
11937 }
11938
11939 return _assign({}, parentContext, {}, childContext);
11940 }
11941}
11942
11943function pushContextProvider(workInProgress) {
11944 if (disableLegacyContext) {
11945 return false;
11946 } else {
11947 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
11948 // If the instance does not exist yet, we will push null at first,
11949 // and replace it on the stack later when invalidating the context.
11950
11951 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
11952 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
11953
11954 previousContext = contextStackCursor.current;
11955 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
11956 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
11957 return true;
11958 }
11959}
11960
11961function invalidateContextProvider(workInProgress, type, didChange) {
11962 if (disableLegacyContext) {
11963 return;
11964 } else {
11965 var instance = workInProgress.stateNode;
11966
11967 if (!instance) {
11968 {
11969 throw Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
11970 }
11971 }
11972
11973 if (didChange) {
11974 // Merge parent and own context.
11975 // Skip this if we're not updating due to sCU.
11976 // This avoids unnecessarily recomputing memoized values.
11977 var mergedContext = processChildContext(workInProgress, type, previousContext);
11978 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
11979 // It is important to unwind the context in the reverse order.
11980
11981 pop(didPerformWorkStackCursor, workInProgress);
11982 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
11983
11984 push(contextStackCursor, mergedContext, workInProgress);
11985 push(didPerformWorkStackCursor, didChange, workInProgress);
11986 } else {
11987 pop(didPerformWorkStackCursor, workInProgress);
11988 push(didPerformWorkStackCursor, didChange, workInProgress);
11989 }
11990 }
11991}
11992
11993function findCurrentUnmaskedContext(fiber) {
11994 if (disableLegacyContext) {
11995 return emptyContextObject;
11996 } else {
11997 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
11998 // makes sense elsewhere
11999 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
12000 {
12001 throw Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");
12002 }
12003 }
12004
12005 var node = fiber;
12006
12007 do {
12008 switch (node.tag) {
12009 case HostRoot:
12010 return node.stateNode.context;
12011
12012 case ClassComponent:
12013 {
12014 var Component = node.type;
12015
12016 if (isContextProvider(Component)) {
12017 return node.stateNode.__reactInternalMemoizedMergedChildContext;
12018 }
12019
12020 break;
12021 }
12022 }
12023
12024 node = node.return;
12025 } while (node !== null);
12026
12027 {
12028 {
12029 throw Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
12030 }
12031 }
12032 }
12033}
12034
12035var LegacyRoot = 0;
12036var BlockingRoot = 1;
12037var ConcurrentRoot = 2;
12038
12039// Intentionally not named imports because Rollup would use dynamic dispatch for
12040// CommonJS interop named imports.
12041var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority;
12042var Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback;
12043var Scheduler_cancelCallback = Scheduler.unstable_cancelCallback;
12044var Scheduler_shouldYield = Scheduler.unstable_shouldYield;
12045var Scheduler_requestPaint = Scheduler.unstable_requestPaint;
12046var Scheduler_now = Scheduler.unstable_now;
12047var Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel;
12048var Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority;
12049var Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
12050var Scheduler_NormalPriority = Scheduler.unstable_NormalPriority;
12051var Scheduler_LowPriority = Scheduler.unstable_LowPriority;
12052var Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;
12053
12054if (enableSchedulerTracing) {
12055 // Provide explicit error message when production+profiling bundle of e.g.
12056 // react-dom is used with production (non-profiling) bundle of
12057 // scheduler/tracing
12058 if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {
12059 {
12060 throw 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");
12061 }
12062 }
12063}
12064
12065var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
12066// ascending numbers so we can compare them like numbers. They start at 90 to
12067// avoid clashing with Scheduler's priorities.
12068
12069var ImmediatePriority = 99;
12070var UserBlockingPriority$2 = 98;
12071var NormalPriority = 97;
12072var LowPriority = 96;
12073var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
12074
12075var NoPriority = 90;
12076var shouldYield = Scheduler_shouldYield;
12077var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
12078Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
12079var syncQueue = null;
12080var immediateQueueCallbackNode = null;
12081var isFlushingSyncQueue = false;
12082var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
12083// This will be the case for modern browsers that support `performance.now`. In
12084// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
12085// timestamp. In that case, subtract the module initialization time to simulate
12086// the behavior of performance.now and keep our times small enough to fit
12087// within 32 bits.
12088// TODO: Consider lifting this into Scheduler.
12089
12090var now = initialTimeMs < 10000 ? Scheduler_now : function () {
12091 return Scheduler_now() - initialTimeMs;
12092};
12093function getCurrentPriorityLevel() {
12094 switch (Scheduler_getCurrentPriorityLevel()) {
12095 case Scheduler_ImmediatePriority:
12096 return ImmediatePriority;
12097
12098 case Scheduler_UserBlockingPriority:
12099 return UserBlockingPriority$2;
12100
12101 case Scheduler_NormalPriority:
12102 return NormalPriority;
12103
12104 case Scheduler_LowPriority:
12105 return LowPriority;
12106
12107 case Scheduler_IdlePriority:
12108 return IdlePriority;
12109
12110 default:
12111 {
12112 {
12113 throw Error("Unknown priority level.");
12114 }
12115 }
12116
12117 }
12118}
12119
12120function reactPriorityToSchedulerPriority(reactPriorityLevel) {
12121 switch (reactPriorityLevel) {
12122 case ImmediatePriority:
12123 return Scheduler_ImmediatePriority;
12124
12125 case UserBlockingPriority$2:
12126 return Scheduler_UserBlockingPriority;
12127
12128 case NormalPriority:
12129 return Scheduler_NormalPriority;
12130
12131 case LowPriority:
12132 return Scheduler_LowPriority;
12133
12134 case IdlePriority:
12135 return Scheduler_IdlePriority;
12136
12137 default:
12138 {
12139 {
12140 throw Error("Unknown priority level.");
12141 }
12142 }
12143
12144 }
12145}
12146
12147function runWithPriority$2(reactPriorityLevel, fn) {
12148 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12149 return Scheduler_runWithPriority(priorityLevel, fn);
12150}
12151function scheduleCallback(reactPriorityLevel, callback, options) {
12152 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12153 return Scheduler_scheduleCallback(priorityLevel, callback, options);
12154}
12155function scheduleSyncCallback(callback) {
12156 // Push this callback into an internal queue. We'll flush these either in
12157 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
12158 if (syncQueue === null) {
12159 syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
12160
12161 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
12162 } else {
12163 // Push onto existing queue. Don't need to schedule a callback because
12164 // we already scheduled one when we created the queue.
12165 syncQueue.push(callback);
12166 }
12167
12168 return fakeCallbackNode;
12169}
12170function cancelCallback(callbackNode) {
12171 if (callbackNode !== fakeCallbackNode) {
12172 Scheduler_cancelCallback(callbackNode);
12173 }
12174}
12175function flushSyncCallbackQueue() {
12176 if (immediateQueueCallbackNode !== null) {
12177 var node = immediateQueueCallbackNode;
12178 immediateQueueCallbackNode = null;
12179 Scheduler_cancelCallback(node);
12180 }
12181
12182 flushSyncCallbackQueueImpl();
12183}
12184
12185function flushSyncCallbackQueueImpl() {
12186 if (!isFlushingSyncQueue && syncQueue !== null) {
12187 // Prevent re-entrancy.
12188 isFlushingSyncQueue = true;
12189 var i = 0;
12190
12191 try {
12192 var _isSync = true;
12193 var queue = syncQueue;
12194 runWithPriority$2(ImmediatePriority, function () {
12195 for (; i < queue.length; i++) {
12196 var callback = queue[i];
12197
12198 do {
12199 callback = callback(_isSync);
12200 } while (callback !== null);
12201 }
12202 });
12203 syncQueue = null;
12204 } catch (error) {
12205 // If something throws, leave the remaining callbacks on the queue.
12206 if (syncQueue !== null) {
12207 syncQueue = syncQueue.slice(i + 1);
12208 } // Resume flushing in the next tick
12209
12210
12211 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
12212 throw error;
12213 } finally {
12214 isFlushingSyncQueue = false;
12215 }
12216 }
12217}
12218
12219var NoMode = 0;
12220var StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root
12221// tag instead
12222
12223var BlockingMode = 2;
12224var ConcurrentMode = 4;
12225var ProfileMode = 8;
12226
12227// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
12228// Math.pow(2, 30) - 1
12229// 0b111111111111111111111111111111
12230var MAX_SIGNED_31_BIT_INT = 1073741823;
12231
12232var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
12233// Never work can be committed in an inconsistent state without tearing the UI.
12234// The main example is offscreen content, like a hidden subtree. So one possible
12235// name is Offscreen. However, it also includes dehydrated Suspense boundaries,
12236// which are inconsistent in the sense that they haven't finished yet, but
12237// aren't visibly inconsistent because the server rendered HTML matches what the
12238// hydrated tree would look like.
12239
12240var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
12241// order to be consistent.
12242
12243var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle
12244// and is used to increase priority of hover targets. It is increasing with
12245// each usage so that last always wins.
12246
12247var ContinuousHydration = 3;
12248var Sync = MAX_SIGNED_31_BIT_INT;
12249var Batched = Sync - 1;
12250var UNIT_SIZE = 10;
12251var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.
12252
12253function msToExpirationTime(ms) {
12254 // Always add an offset so that we don't clash with the magic number for NoWork.
12255 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
12256}
12257function expirationTimeToMs(expirationTime) {
12258 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
12259}
12260
12261function ceiling(num, precision) {
12262 return ((num / precision | 0) + 1) * precision;
12263}
12264
12265function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
12266 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
12267} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
12268// the names to reflect.
12269
12270
12271var LOW_PRIORITY_EXPIRATION = 5000;
12272var LOW_PRIORITY_BATCH_SIZE = 250;
12273function computeAsyncExpiration(currentTime) {
12274 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
12275}
12276function computeSuspenseExpiration(currentTime, timeoutMs) {
12277 // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
12278 return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
12279} // We intentionally set a higher expiration time for interactive updates in
12280// dev than in production.
12281//
12282// If the main thread is being blocked so long that you hit the expiration,
12283// it's a problem that could be solved with better scheduling.
12284//
12285// People will be more likely to notice this and fix it with the long
12286// expiration time in development.
12287//
12288// In production we opt for better UX at the risk of masking scheduling
12289// problems, by expiring fast.
12290
12291var HIGH_PRIORITY_EXPIRATION = 500;
12292var HIGH_PRIORITY_BATCH_SIZE = 100;
12293function computeInteractiveExpiration(currentTime) {
12294 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
12295}
12296function computeContinuousHydrationExpiration(currentTime) {
12297 // Each time we ask for a new one of these we increase the priority.
12298 // This ensures that the last one always wins since we can't deprioritize
12299 // once we've scheduled work already.
12300 return ContinuousHydration++;
12301}
12302function inferPriorityFromExpirationTime(currentTime, expirationTime) {
12303 if (expirationTime === Sync) {
12304 return ImmediatePriority;
12305 }
12306
12307 if (expirationTime === Never || expirationTime === Idle) {
12308 return IdlePriority;
12309 }
12310
12311 var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);
12312
12313 if (msUntil <= 0) {
12314 return ImmediatePriority;
12315 }
12316
12317 if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
12318 return UserBlockingPriority$2;
12319 }
12320
12321 if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
12322 return NormalPriority;
12323 } // TODO: Handle LowPriority
12324 // Assume anything lower has idle priority
12325
12326
12327 return IdlePriority;
12328}
12329
12330/**
12331 * Forked from fbjs/warning:
12332 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
12333 *
12334 * Only change is we use console.warn instead of console.error,
12335 * and do nothing when 'console' is not supported.
12336 * This really simplifies the code.
12337 * ---
12338 * Similar to invariant but only logs a warning if the condition is not met.
12339 * This can be used to log issues in development environments in critical
12340 * paths. Removing the logging code for production environments will keep the
12341 * same logic and follow the same code paths.
12342 */
12343var lowPriorityWarningWithoutStack = function () {};
12344
12345{
12346 var printWarning = function (format) {
12347 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
12348 args[_key - 1] = arguments[_key];
12349 }
12350
12351 var argIndex = 0;
12352 var message = 'Warning: ' + format.replace(/%s/g, function () {
12353 return args[argIndex++];
12354 });
12355
12356 if (typeof console !== 'undefined') {
12357 console.warn(message);
12358 }
12359
12360 try {
12361 // --- Welcome to debugging React ---
12362 // This error was thrown as a convenience so that you can use this stack
12363 // to find the callsite that caused this warning to fire.
12364 throw new Error(message);
12365 } catch (x) {}
12366 };
12367
12368 lowPriorityWarningWithoutStack = function (condition, format) {
12369 if (format === undefined) {
12370 throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
12371 }
12372
12373 if (!condition) {
12374 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
12375 args[_key2 - 2] = arguments[_key2];
12376 }
12377
12378 printWarning.apply(void 0, [format].concat(args));
12379 }
12380 };
12381}
12382
12383var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
12384
12385var ReactStrictModeWarnings = {
12386 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
12387 flushPendingUnsafeLifecycleWarnings: function () {},
12388 recordLegacyContextWarning: function (fiber, instance) {},
12389 flushLegacyContextWarning: function () {},
12390 discardPendingWarnings: function () {}
12391};
12392
12393{
12394 var findStrictRoot = function (fiber) {
12395 var maybeStrictRoot = null;
12396 var node = fiber;
12397
12398 while (node !== null) {
12399 if (node.mode & StrictMode) {
12400 maybeStrictRoot = node;
12401 }
12402
12403 node = node.return;
12404 }
12405
12406 return maybeStrictRoot;
12407 };
12408
12409 var setToSortedString = function (set) {
12410 var array = [];
12411 set.forEach(function (value) {
12412 array.push(value);
12413 });
12414 return array.sort().join(', ');
12415 };
12416
12417 var pendingComponentWillMountWarnings = [];
12418 var pendingUNSAFE_ComponentWillMountWarnings = [];
12419 var pendingComponentWillReceivePropsWarnings = [];
12420 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12421 var pendingComponentWillUpdateWarnings = [];
12422 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
12423
12424 var didWarnAboutUnsafeLifecycles = new Set();
12425
12426 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
12427 // Dedup strategy: Warn once per component.
12428 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
12429 return;
12430 }
12431
12432 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
12433 instance.componentWillMount.__suppressDeprecationWarning !== true) {
12434 pendingComponentWillMountWarnings.push(fiber);
12435 }
12436
12437 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
12438 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
12439 }
12440
12441 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12442 pendingComponentWillReceivePropsWarnings.push(fiber);
12443 }
12444
12445 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12446 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
12447 }
12448
12449 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12450 pendingComponentWillUpdateWarnings.push(fiber);
12451 }
12452
12453 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
12454 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
12455 }
12456 };
12457
12458 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
12459 // We do an initial pass to gather component names
12460 var componentWillMountUniqueNames = new Set();
12461
12462 if (pendingComponentWillMountWarnings.length > 0) {
12463 pendingComponentWillMountWarnings.forEach(function (fiber) {
12464 componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12465 didWarnAboutUnsafeLifecycles.add(fiber.type);
12466 });
12467 pendingComponentWillMountWarnings = [];
12468 }
12469
12470 var UNSAFE_componentWillMountUniqueNames = new Set();
12471
12472 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
12473 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
12474 UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12475 didWarnAboutUnsafeLifecycles.add(fiber.type);
12476 });
12477 pendingUNSAFE_ComponentWillMountWarnings = [];
12478 }
12479
12480 var componentWillReceivePropsUniqueNames = new Set();
12481
12482 if (pendingComponentWillReceivePropsWarnings.length > 0) {
12483 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
12484 componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12485 didWarnAboutUnsafeLifecycles.add(fiber.type);
12486 });
12487 pendingComponentWillReceivePropsWarnings = [];
12488 }
12489
12490 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
12491
12492 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
12493 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
12494 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12495 didWarnAboutUnsafeLifecycles.add(fiber.type);
12496 });
12497 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12498 }
12499
12500 var componentWillUpdateUniqueNames = new Set();
12501
12502 if (pendingComponentWillUpdateWarnings.length > 0) {
12503 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
12504 componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12505 didWarnAboutUnsafeLifecycles.add(fiber.type);
12506 });
12507 pendingComponentWillUpdateWarnings = [];
12508 }
12509
12510 var UNSAFE_componentWillUpdateUniqueNames = new Set();
12511
12512 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
12513 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
12514 UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12515 didWarnAboutUnsafeLifecycles.add(fiber.type);
12516 });
12517 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12518 } // Finally, we flush all the warnings
12519 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
12520
12521
12522 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
12523 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
12524 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);
12525 }
12526
12527 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
12528 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
12529
12530 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);
12531 }
12532
12533 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
12534 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
12535
12536 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);
12537 }
12538
12539 if (componentWillMountUniqueNames.size > 0) {
12540 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
12541
12542 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);
12543 }
12544
12545 if (componentWillReceivePropsUniqueNames.size > 0) {
12546 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
12547
12548 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);
12549 }
12550
12551 if (componentWillUpdateUniqueNames.size > 0) {
12552 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
12553
12554 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);
12555 }
12556 };
12557
12558 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
12559
12560 var didWarnAboutLegacyContext = new Set();
12561
12562 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
12563 var strictRoot = findStrictRoot(fiber);
12564
12565 if (strictRoot === null) {
12566 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.');
12567 return;
12568 } // Dedup strategy: Warn once per component.
12569
12570
12571 if (didWarnAboutLegacyContext.has(fiber.type)) {
12572 return;
12573 }
12574
12575 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
12576
12577 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
12578 if (warningsForRoot === undefined) {
12579 warningsForRoot = [];
12580 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
12581 }
12582
12583 warningsForRoot.push(fiber);
12584 }
12585 };
12586
12587 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
12588 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
12589 var uniqueNames = new Set();
12590 fiberArray.forEach(function (fiber) {
12591 uniqueNames.add(getComponentName(fiber.type) || 'Component');
12592 didWarnAboutLegacyContext.add(fiber.type);
12593 });
12594 var sortedNames = setToSortedString(uniqueNames);
12595 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
12596 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);
12597 });
12598 };
12599
12600 ReactStrictModeWarnings.discardPendingWarnings = function () {
12601 pendingComponentWillMountWarnings = [];
12602 pendingUNSAFE_ComponentWillMountWarnings = [];
12603 pendingComponentWillReceivePropsWarnings = [];
12604 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12605 pendingComponentWillUpdateWarnings = [];
12606 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12607 pendingLegacyContextWarning = new Map();
12608 };
12609}
12610
12611var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
12612
12613var failedBoundaries = null;
12614var setRefreshHandler = function (handler) {
12615 {
12616 resolveFamily = handler;
12617 }
12618};
12619function resolveFunctionForHotReloading(type) {
12620 {
12621 if (resolveFamily === null) {
12622 // Hot reloading is disabled.
12623 return type;
12624 }
12625
12626 var family = resolveFamily(type);
12627
12628 if (family === undefined) {
12629 return type;
12630 } // Use the latest known implementation.
12631
12632
12633 return family.current;
12634 }
12635}
12636function resolveClassForHotReloading(type) {
12637 // No implementation differences.
12638 return resolveFunctionForHotReloading(type);
12639}
12640function resolveForwardRefForHotReloading(type) {
12641 {
12642 if (resolveFamily === null) {
12643 // Hot reloading is disabled.
12644 return type;
12645 }
12646
12647 var family = resolveFamily(type);
12648
12649 if (family === undefined) {
12650 // Check if we're dealing with a real forwardRef. Don't want to crash early.
12651 if (type !== null && type !== undefined && typeof type.render === 'function') {
12652 // ForwardRef is special because its resolved .type is an object,
12653 // but it's possible that we only have its inner render function in the map.
12654 // If that inner render function is different, we'll build a new forwardRef type.
12655 var currentRender = resolveFunctionForHotReloading(type.render);
12656
12657 if (type.render !== currentRender) {
12658 var syntheticType = {
12659 $$typeof: REACT_FORWARD_REF_TYPE,
12660 render: currentRender
12661 };
12662
12663 if (type.displayName !== undefined) {
12664 syntheticType.displayName = type.displayName;
12665 }
12666
12667 return syntheticType;
12668 }
12669 }
12670
12671 return type;
12672 } // Use the latest known implementation.
12673
12674
12675 return family.current;
12676 }
12677}
12678function isCompatibleFamilyForHotReloading(fiber, element) {
12679 {
12680 if (resolveFamily === null) {
12681 // Hot reloading is disabled.
12682 return false;
12683 }
12684
12685 var prevType = fiber.elementType;
12686 var nextType = element.type; // If we got here, we know types aren't === equal.
12687
12688 var needsCompareFamilies = false;
12689 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
12690
12691 switch (fiber.tag) {
12692 case ClassComponent:
12693 {
12694 if (typeof nextType === 'function') {
12695 needsCompareFamilies = true;
12696 }
12697
12698 break;
12699 }
12700
12701 case FunctionComponent:
12702 {
12703 if (typeof nextType === 'function') {
12704 needsCompareFamilies = true;
12705 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12706 // We don't know the inner type yet.
12707 // We're going to assume that the lazy inner type is stable,
12708 // and so it is sufficient to avoid reconciling it away.
12709 // We're not going to unwrap or actually use the new lazy type.
12710 needsCompareFamilies = true;
12711 }
12712
12713 break;
12714 }
12715
12716 case ForwardRef:
12717 {
12718 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
12719 needsCompareFamilies = true;
12720 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12721 needsCompareFamilies = true;
12722 }
12723
12724 break;
12725 }
12726
12727 case MemoComponent:
12728 case SimpleMemoComponent:
12729 {
12730 if ($$typeofNextType === REACT_MEMO_TYPE) {
12731 // TODO: if it was but can no longer be simple,
12732 // we shouldn't set this.
12733 needsCompareFamilies = true;
12734 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12735 needsCompareFamilies = true;
12736 }
12737
12738 break;
12739 }
12740
12741 default:
12742 return false;
12743 } // Check if both types have a family and it's the same one.
12744
12745
12746 if (needsCompareFamilies) {
12747 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
12748 // This means both of them need to be registered to preserve state.
12749 // If we unwrapped and compared the inner types for wrappers instead,
12750 // then we would risk falsely saying two separate memo(Foo)
12751 // calls are equivalent because they wrap the same Foo function.
12752 var prevFamily = resolveFamily(prevType);
12753
12754 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
12755 return true;
12756 }
12757 }
12758
12759 return false;
12760 }
12761}
12762function markFailedErrorBoundaryForHotReloading(fiber) {
12763 {
12764 if (resolveFamily === null) {
12765 // Hot reloading is disabled.
12766 return;
12767 }
12768
12769 if (typeof WeakSet !== 'function') {
12770 return;
12771 }
12772
12773 if (failedBoundaries === null) {
12774 failedBoundaries = new WeakSet();
12775 }
12776
12777 failedBoundaries.add(fiber);
12778 }
12779}
12780var scheduleRefresh = function (root, update) {
12781 {
12782 if (resolveFamily === null) {
12783 // Hot reloading is disabled.
12784 return;
12785 }
12786
12787 var staleFamilies = update.staleFamilies,
12788 updatedFamilies = update.updatedFamilies;
12789 flushPassiveEffects();
12790 flushSync(function () {
12791 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
12792 });
12793 }
12794};
12795var scheduleRoot = function (root, element) {
12796 {
12797 if (root.context !== emptyContextObject) {
12798 // Super edge case: root has a legacy _renderSubtree context
12799 // but we don't know the parentComponent so we can't pass it.
12800 // Just ignore. We'll delete this with _renderSubtree code path later.
12801 return;
12802 }
12803
12804 flushPassiveEffects();
12805 syncUpdates(function () {
12806 updateContainer(element, root, null, null);
12807 });
12808 }
12809};
12810
12811function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
12812 {
12813 var alternate = fiber.alternate,
12814 child = fiber.child,
12815 sibling = fiber.sibling,
12816 tag = fiber.tag,
12817 type = fiber.type;
12818 var candidateType = null;
12819
12820 switch (tag) {
12821 case FunctionComponent:
12822 case SimpleMemoComponent:
12823 case ClassComponent:
12824 candidateType = type;
12825 break;
12826
12827 case ForwardRef:
12828 candidateType = type.render;
12829 break;
12830
12831 default:
12832 break;
12833 }
12834
12835 if (resolveFamily === null) {
12836 throw new Error('Expected resolveFamily to be set during hot reload.');
12837 }
12838
12839 var needsRender = false;
12840 var needsRemount = false;
12841
12842 if (candidateType !== null) {
12843 var family = resolveFamily(candidateType);
12844
12845 if (family !== undefined) {
12846 if (staleFamilies.has(family)) {
12847 needsRemount = true;
12848 } else if (updatedFamilies.has(family)) {
12849 if (tag === ClassComponent) {
12850 needsRemount = true;
12851 } else {
12852 needsRender = true;
12853 }
12854 }
12855 }
12856 }
12857
12858 if (failedBoundaries !== null) {
12859 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
12860 needsRemount = true;
12861 }
12862 }
12863
12864 if (needsRemount) {
12865 fiber._debugNeedsRemount = true;
12866 }
12867
12868 if (needsRemount || needsRender) {
12869 scheduleWork(fiber, Sync);
12870 }
12871
12872 if (child !== null && !needsRemount) {
12873 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
12874 }
12875
12876 if (sibling !== null) {
12877 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
12878 }
12879 }
12880}
12881
12882var findHostInstancesForRefresh = function (root, families) {
12883 {
12884 var hostInstances = new Set();
12885 var types = new Set(families.map(function (family) {
12886 return family.current;
12887 }));
12888 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
12889 return hostInstances;
12890 }
12891};
12892
12893function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
12894 {
12895 var child = fiber.child,
12896 sibling = fiber.sibling,
12897 tag = fiber.tag,
12898 type = fiber.type;
12899 var candidateType = null;
12900
12901 switch (tag) {
12902 case FunctionComponent:
12903 case SimpleMemoComponent:
12904 case ClassComponent:
12905 candidateType = type;
12906 break;
12907
12908 case ForwardRef:
12909 candidateType = type.render;
12910 break;
12911
12912 default:
12913 break;
12914 }
12915
12916 var didMatch = false;
12917
12918 if (candidateType !== null) {
12919 if (types.has(candidateType)) {
12920 didMatch = true;
12921 }
12922 }
12923
12924 if (didMatch) {
12925 // We have a match. This only drills down to the closest host components.
12926 // There's no need to search deeper because for the purpose of giving
12927 // visual feedback, "flashing" outermost parent rectangles is sufficient.
12928 findHostInstancesForFiberShallowly(fiber, hostInstances);
12929 } else {
12930 // If there's no match, maybe there will be one further down in the child tree.
12931 if (child !== null) {
12932 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
12933 }
12934 }
12935
12936 if (sibling !== null) {
12937 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
12938 }
12939 }
12940}
12941
12942function findHostInstancesForFiberShallowly(fiber, hostInstances) {
12943 {
12944 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
12945
12946 if (foundHostInstances) {
12947 return;
12948 } // If we didn't find any host children, fallback to closest host parent.
12949
12950
12951 var node = fiber;
12952
12953 while (true) {
12954 switch (node.tag) {
12955 case HostComponent:
12956 hostInstances.add(node.stateNode);
12957 return;
12958
12959 case HostPortal:
12960 hostInstances.add(node.stateNode.containerInfo);
12961 return;
12962
12963 case HostRoot:
12964 hostInstances.add(node.stateNode.containerInfo);
12965 return;
12966 }
12967
12968 if (node.return === null) {
12969 throw new Error('Expected to reach root first.');
12970 }
12971
12972 node = node.return;
12973 }
12974 }
12975}
12976
12977function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
12978 {
12979 var node = fiber;
12980 var foundHostInstances = false;
12981
12982 while (true) {
12983 if (node.tag === HostComponent) {
12984 // We got a match.
12985 foundHostInstances = true;
12986 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
12987 } else if (node.child !== null) {
12988 node.child.return = node;
12989 node = node.child;
12990 continue;
12991 }
12992
12993 if (node === fiber) {
12994 return foundHostInstances;
12995 }
12996
12997 while (node.sibling === null) {
12998 if (node.return === null || node.return === fiber) {
12999 return foundHostInstances;
13000 }
13001
13002 node = node.return;
13003 }
13004
13005 node.sibling.return = node.return;
13006 node = node.sibling;
13007 }
13008 }
13009
13010 return false;
13011}
13012
13013function resolveDefaultProps(Component, baseProps) {
13014 if (Component && Component.defaultProps) {
13015 // Resolve default props. Taken from ReactElement
13016 var props = _assign({}, baseProps);
13017
13018 var defaultProps = Component.defaultProps;
13019
13020 for (var propName in defaultProps) {
13021 if (props[propName] === undefined) {
13022 props[propName] = defaultProps[propName];
13023 }
13024 }
13025
13026 return props;
13027 }
13028
13029 return baseProps;
13030}
13031function readLazyComponentType(lazyComponent) {
13032 initializeLazyComponentType(lazyComponent);
13033
13034 if (lazyComponent._status !== Resolved) {
13035 throw lazyComponent._result;
13036 }
13037
13038 return lazyComponent._result;
13039}
13040
13041var valueCursor = createCursor(null);
13042var rendererSigil;
13043
13044{
13045 // Use this to detect multiple renderers using the same context
13046 rendererSigil = {};
13047}
13048
13049var currentlyRenderingFiber = null;
13050var lastContextDependency = null;
13051var lastContextWithAllBitsObserved = null;
13052var isDisallowedContextReadInDEV = false;
13053function resetContextDependencies() {
13054 // This is called right before React yields execution, to ensure `readContext`
13055 // cannot be called outside the render phase.
13056 currentlyRenderingFiber = null;
13057 lastContextDependency = null;
13058 lastContextWithAllBitsObserved = null;
13059
13060 {
13061 isDisallowedContextReadInDEV = false;
13062 }
13063}
13064function enterDisallowedContextReadInDEV() {
13065 {
13066 isDisallowedContextReadInDEV = true;
13067 }
13068}
13069function exitDisallowedContextReadInDEV() {
13070 {
13071 isDisallowedContextReadInDEV = false;
13072 }
13073}
13074function pushProvider(providerFiber, nextValue) {
13075 var context = providerFiber.type._context;
13076
13077 if (isPrimaryRenderer) {
13078 push(valueCursor, context._currentValue, providerFiber);
13079 context._currentValue = nextValue;
13080
13081 {
13082 !(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;
13083 context._currentRenderer = rendererSigil;
13084 }
13085 } else {
13086 push(valueCursor, context._currentValue2, providerFiber);
13087 context._currentValue2 = nextValue;
13088
13089 {
13090 !(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;
13091 context._currentRenderer2 = rendererSigil;
13092 }
13093 }
13094}
13095function popProvider(providerFiber) {
13096 var currentValue = valueCursor.current;
13097 pop(valueCursor, providerFiber);
13098 var context = providerFiber.type._context;
13099
13100 if (isPrimaryRenderer) {
13101 context._currentValue = currentValue;
13102 } else {
13103 context._currentValue2 = currentValue;
13104 }
13105}
13106function calculateChangedBits(context, newValue, oldValue) {
13107 if (is$1(oldValue, newValue)) {
13108 // No change
13109 return 0;
13110 } else {
13111 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
13112
13113 {
13114 !((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;
13115 }
13116
13117 return changedBits | 0;
13118 }
13119}
13120function scheduleWorkOnParentPath(parent, renderExpirationTime) {
13121 // Update the child expiration time of all the ancestors, including
13122 // the alternates.
13123 var node = parent;
13124
13125 while (node !== null) {
13126 var alternate = node.alternate;
13127
13128 if (node.childExpirationTime < renderExpirationTime) {
13129 node.childExpirationTime = renderExpirationTime;
13130
13131 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13132 alternate.childExpirationTime = renderExpirationTime;
13133 }
13134 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13135 alternate.childExpirationTime = renderExpirationTime;
13136 } else {
13137 // Neither alternate was updated, which means the rest of the
13138 // ancestor path already has sufficient priority.
13139 break;
13140 }
13141
13142 node = node.return;
13143 }
13144}
13145function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
13146 var fiber = workInProgress.child;
13147
13148 if (fiber !== null) {
13149 // Set the return pointer of the child to the work-in-progress fiber.
13150 fiber.return = workInProgress;
13151 }
13152
13153 while (fiber !== null) {
13154 var nextFiber = void 0; // Visit this fiber.
13155
13156 var list = fiber.dependencies;
13157
13158 if (list !== null) {
13159 nextFiber = fiber.child;
13160 var dependency = list.firstContext;
13161
13162 while (dependency !== null) {
13163 // Check if the context matches.
13164 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
13165 // Match! Schedule an update on this fiber.
13166 if (fiber.tag === ClassComponent) {
13167 // Schedule a force update on the work-in-progress.
13168 var update = createUpdate(renderExpirationTime, null);
13169 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
13170 // update to the current fiber, too, which means it will persist even if
13171 // this render is thrown away. Since it's a race condition, not sure it's
13172 // worth fixing.
13173
13174 enqueueUpdate(fiber, update);
13175 }
13176
13177 if (fiber.expirationTime < renderExpirationTime) {
13178 fiber.expirationTime = renderExpirationTime;
13179 }
13180
13181 var alternate = fiber.alternate;
13182
13183 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
13184 alternate.expirationTime = renderExpirationTime;
13185 }
13186
13187 scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.
13188
13189 if (list.expirationTime < renderExpirationTime) {
13190 list.expirationTime = renderExpirationTime;
13191 } // Since we already found a match, we can stop traversing the
13192 // dependency list.
13193
13194
13195 break;
13196 }
13197
13198 dependency = dependency.next;
13199 }
13200 } else if (fiber.tag === ContextProvider) {
13201 // Don't scan deeper if this is a matching provider
13202 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
13203 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedFragment) {
13204 // If a dehydrated suspense bounudary is in this subtree, we don't know
13205 // if it will have any context consumers in it. The best we can do is
13206 // mark it as having updates.
13207 var parentSuspense = fiber.return;
13208
13209 if (!(parentSuspense !== null)) {
13210 {
13211 throw Error("We just came from a parent so we must have had a parent. This is a bug in React.");
13212 }
13213 }
13214
13215 if (parentSuspense.expirationTime < renderExpirationTime) {
13216 parentSuspense.expirationTime = renderExpirationTime;
13217 }
13218
13219 var _alternate = parentSuspense.alternate;
13220
13221 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
13222 _alternate.expirationTime = renderExpirationTime;
13223 } // This is intentionally passing this fiber as the parent
13224 // because we want to schedule this fiber as having work
13225 // on its children. We'll use the childExpirationTime on
13226 // this fiber to indicate that a context has changed.
13227
13228
13229 scheduleWorkOnParentPath(parentSuspense, renderExpirationTime);
13230 nextFiber = fiber.sibling;
13231 } else {
13232 // Traverse down.
13233 nextFiber = fiber.child;
13234 }
13235
13236 if (nextFiber !== null) {
13237 // Set the return pointer of the child to the work-in-progress fiber.
13238 nextFiber.return = fiber;
13239 } else {
13240 // No child. Traverse to next sibling.
13241 nextFiber = fiber;
13242
13243 while (nextFiber !== null) {
13244 if (nextFiber === workInProgress) {
13245 // We're back to the root of this subtree. Exit.
13246 nextFiber = null;
13247 break;
13248 }
13249
13250 var sibling = nextFiber.sibling;
13251
13252 if (sibling !== null) {
13253 // Set the return pointer of the sibling to the work-in-progress fiber.
13254 sibling.return = nextFiber.return;
13255 nextFiber = sibling;
13256 break;
13257 } // No more siblings. Traverse up.
13258
13259
13260 nextFiber = nextFiber.return;
13261 }
13262 }
13263
13264 fiber = nextFiber;
13265 }
13266}
13267function prepareToReadContext(workInProgress, renderExpirationTime) {
13268 currentlyRenderingFiber = workInProgress;
13269 lastContextDependency = null;
13270 lastContextWithAllBitsObserved = null;
13271 var dependencies = workInProgress.dependencies;
13272
13273 if (dependencies !== null) {
13274 var firstContext = dependencies.firstContext;
13275
13276 if (firstContext !== null) {
13277 if (dependencies.expirationTime >= renderExpirationTime) {
13278 // Context list has a pending update. Mark that this fiber performed work.
13279 markWorkInProgressReceivedUpdate();
13280 } // Reset the work-in-progress list
13281
13282
13283 dependencies.firstContext = null;
13284 }
13285 }
13286}
13287function readContext(context, observedBits) {
13288 {
13289 // This warning would fire if you read context inside a Hook like useMemo.
13290 // Unlike the class check below, it's not enforced in production for perf.
13291 !!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;
13292 }
13293
13294 if (lastContextWithAllBitsObserved === context) {// Nothing to do. We already observe everything in this context.
13295 } else if (observedBits === false || observedBits === 0) {// Do not observe any updates.
13296 } else {
13297 var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
13298
13299 if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
13300 // Observe all updates.
13301 lastContextWithAllBitsObserved = context;
13302 resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
13303 } else {
13304 resolvedObservedBits = observedBits;
13305 }
13306
13307 var contextItem = {
13308 context: context,
13309 observedBits: resolvedObservedBits,
13310 next: null
13311 };
13312
13313 if (lastContextDependency === null) {
13314 if (!(currentlyRenderingFiber !== null)) {
13315 {
13316 throw 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().");
13317 }
13318 } // This is the first dependency for this component. Create a new list.
13319
13320
13321 lastContextDependency = contextItem;
13322 currentlyRenderingFiber.dependencies = {
13323 expirationTime: NoWork,
13324 firstContext: contextItem,
13325 responders: null
13326 };
13327 } else {
13328 // Append a new context item.
13329 lastContextDependency = lastContextDependency.next = contextItem;
13330 }
13331 }
13332
13333 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
13334}
13335
13336// UpdateQueue is a linked list of prioritized updates.
13337//
13338// Like fibers, update queues come in pairs: a current queue, which represents
13339// the visible state of the screen, and a work-in-progress queue, which can be
13340// mutated and processed asynchronously before it is committed — a form of
13341// double buffering. If a work-in-progress render is discarded before finishing,
13342// we create a new work-in-progress by cloning the current queue.
13343//
13344// Both queues share a persistent, singly-linked list structure. To schedule an
13345// update, we append it to the end of both queues. Each queue maintains a
13346// pointer to first update in the persistent list that hasn't been processed.
13347// The work-in-progress pointer always has a position equal to or greater than
13348// the current queue, since we always work on that one. The current queue's
13349// pointer is only updated during the commit phase, when we swap in the
13350// work-in-progress.
13351//
13352// For example:
13353//
13354// Current pointer: A - B - C - D - E - F
13355// Work-in-progress pointer: D - E - F
13356// ^
13357// The work-in-progress queue has
13358// processed more updates than current.
13359//
13360// The reason we append to both queues is because otherwise we might drop
13361// updates without ever processing them. For example, if we only add updates to
13362// the work-in-progress queue, some updates could be lost whenever a work-in
13363// -progress render restarts by cloning from current. Similarly, if we only add
13364// updates to the current queue, the updates will be lost whenever an already
13365// in-progress queue commits and swaps with the current queue. However, by
13366// adding to both queues, we guarantee that the update will be part of the next
13367// work-in-progress. (And because the work-in-progress queue becomes the
13368// current queue once it commits, there's no danger of applying the same
13369// update twice.)
13370//
13371// Prioritization
13372// --------------
13373//
13374// Updates are not sorted by priority, but by insertion; new updates are always
13375// appended to the end of the list.
13376//
13377// The priority is still important, though. When processing the update queue
13378// during the render phase, only the updates with sufficient priority are
13379// included in the result. If we skip an update because it has insufficient
13380// priority, it remains in the queue to be processed later, during a lower
13381// priority render. Crucially, all updates subsequent to a skipped update also
13382// remain in the queue *regardless of their priority*. That means high priority
13383// updates are sometimes processed twice, at two separate priorities. We also
13384// keep track of a base state, that represents the state before the first
13385// update in the queue is applied.
13386//
13387// For example:
13388//
13389// Given a base state of '', and the following queue of updates
13390//
13391// A1 - B2 - C1 - D2
13392//
13393// where the number indicates the priority, and the update is applied to the
13394// previous state by appending a letter, React will process these updates as
13395// two separate renders, one per distinct priority level:
13396//
13397// First render, at priority 1:
13398// Base state: ''
13399// Updates: [A1, C1]
13400// Result state: 'AC'
13401//
13402// Second render, at priority 2:
13403// Base state: 'A' <- The base state does not include C1,
13404// because B2 was skipped.
13405// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
13406// Result state: 'ABCD'
13407//
13408// Because we process updates in insertion order, and rebase high priority
13409// updates when preceding updates are skipped, the final result is deterministic
13410// regardless of priority. Intermediate state may vary according to system
13411// resources, but the final state is always the same.
13412var UpdateState = 0;
13413var ReplaceState = 1;
13414var ForceUpdate = 2;
13415var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
13416// It should only be read right after calling `processUpdateQueue`, via
13417// `checkHasForceUpdateAfterProcessing`.
13418
13419var hasForceUpdate = false;
13420var didWarnUpdateInsideUpdate;
13421var currentlyProcessingQueue;
13422
13423
13424{
13425 didWarnUpdateInsideUpdate = false;
13426 currentlyProcessingQueue = null;
13427
13428
13429}
13430
13431function createUpdateQueue(baseState) {
13432 var queue = {
13433 baseState: baseState,
13434 firstUpdate: null,
13435 lastUpdate: null,
13436 firstCapturedUpdate: null,
13437 lastCapturedUpdate: null,
13438 firstEffect: null,
13439 lastEffect: null,
13440 firstCapturedEffect: null,
13441 lastCapturedEffect: null
13442 };
13443 return queue;
13444}
13445
13446function cloneUpdateQueue(currentQueue) {
13447 var queue = {
13448 baseState: currentQueue.baseState,
13449 firstUpdate: currentQueue.firstUpdate,
13450 lastUpdate: currentQueue.lastUpdate,
13451 // TODO: With resuming, if we bail out and resuse the child tree, we should
13452 // keep these effects.
13453 firstCapturedUpdate: null,
13454 lastCapturedUpdate: null,
13455 firstEffect: null,
13456 lastEffect: null,
13457 firstCapturedEffect: null,
13458 lastCapturedEffect: null
13459 };
13460 return queue;
13461}
13462
13463function createUpdate(expirationTime, suspenseConfig) {
13464 var update = {
13465 expirationTime: expirationTime,
13466 suspenseConfig: suspenseConfig,
13467 tag: UpdateState,
13468 payload: null,
13469 callback: null,
13470 next: null,
13471 nextEffect: null
13472 };
13473
13474 {
13475 update.priority = getCurrentPriorityLevel();
13476 }
13477
13478 return update;
13479}
13480
13481function appendUpdateToQueue(queue, update) {
13482 // Append the update to the end of the list.
13483 if (queue.lastUpdate === null) {
13484 // Queue is empty
13485 queue.firstUpdate = queue.lastUpdate = update;
13486 } else {
13487 queue.lastUpdate.next = update;
13488 queue.lastUpdate = update;
13489 }
13490}
13491
13492function enqueueUpdate(fiber, update) {
13493 // Update queues are created lazily.
13494 var alternate = fiber.alternate;
13495 var queue1;
13496 var queue2;
13497
13498 if (alternate === null) {
13499 // There's only one fiber.
13500 queue1 = fiber.updateQueue;
13501 queue2 = null;
13502
13503 if (queue1 === null) {
13504 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13505 }
13506 } else {
13507 // There are two owners.
13508 queue1 = fiber.updateQueue;
13509 queue2 = alternate.updateQueue;
13510
13511 if (queue1 === null) {
13512 if (queue2 === null) {
13513 // Neither fiber has an update queue. Create new ones.
13514 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13515 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
13516 } else {
13517 // Only one fiber has an update queue. Clone to create a new one.
13518 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
13519 }
13520 } else {
13521 if (queue2 === null) {
13522 // Only one fiber has an update queue. Clone to create a new one.
13523 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
13524 } else {// Both owners have an update queue.
13525 }
13526 }
13527 }
13528
13529 if (queue2 === null || queue1 === queue2) {
13530 // There's only a single queue.
13531 appendUpdateToQueue(queue1, update);
13532 } else {
13533 // There are two queues. We need to append the update to both queues,
13534 // while accounting for the persistent structure of the list — we don't
13535 // want the same update to be added multiple times.
13536 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
13537 // One of the queues is not empty. We must add the update to both queues.
13538 appendUpdateToQueue(queue1, update);
13539 appendUpdateToQueue(queue2, update);
13540 } else {
13541 // Both queues are non-empty. The last update is the same in both lists,
13542 // because of structural sharing. So, only append to one of the lists.
13543 appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2.
13544
13545 queue2.lastUpdate = update;
13546 }
13547 }
13548
13549 {
13550 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
13551 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.');
13552 didWarnUpdateInsideUpdate = true;
13553 }
13554 }
13555}
13556function enqueueCapturedUpdate(workInProgress, update) {
13557 // Captured updates go into a separate list, and only on the work-in-
13558 // progress queue.
13559 var workInProgressQueue = workInProgress.updateQueue;
13560
13561 if (workInProgressQueue === null) {
13562 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
13563 } else {
13564 // TODO: I put this here rather than createWorkInProgress so that we don't
13565 // clone the queue unnecessarily. There's probably a better way to
13566 // structure this.
13567 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
13568 } // Append the update to the end of the list.
13569
13570
13571 if (workInProgressQueue.lastCapturedUpdate === null) {
13572 // This is the first render phase update
13573 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
13574 } else {
13575 workInProgressQueue.lastCapturedUpdate.next = update;
13576 workInProgressQueue.lastCapturedUpdate = update;
13577 }
13578}
13579
13580function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
13581 var current = workInProgress.alternate;
13582
13583 if (current !== null) {
13584 // If the work-in-progress queue is equal to the current queue,
13585 // we need to clone it first.
13586 if (queue === current.updateQueue) {
13587 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
13588 }
13589 }
13590
13591 return queue;
13592}
13593
13594function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
13595 switch (update.tag) {
13596 case ReplaceState:
13597 {
13598 var payload = update.payload;
13599
13600 if (typeof payload === 'function') {
13601 // Updater function
13602 {
13603 enterDisallowedContextReadInDEV();
13604
13605 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13606 payload.call(instance, prevState, nextProps);
13607 }
13608 }
13609
13610 var nextState = payload.call(instance, prevState, nextProps);
13611
13612 {
13613 exitDisallowedContextReadInDEV();
13614 }
13615
13616 return nextState;
13617 } // State object
13618
13619
13620 return payload;
13621 }
13622
13623 case CaptureUpdate:
13624 {
13625 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
13626 }
13627 // Intentional fallthrough
13628
13629 case UpdateState:
13630 {
13631 var _payload = update.payload;
13632 var partialState;
13633
13634 if (typeof _payload === 'function') {
13635 // Updater function
13636 {
13637 enterDisallowedContextReadInDEV();
13638
13639 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13640 _payload.call(instance, prevState, nextProps);
13641 }
13642 }
13643
13644 partialState = _payload.call(instance, prevState, nextProps);
13645
13646 {
13647 exitDisallowedContextReadInDEV();
13648 }
13649 } else {
13650 // Partial state object
13651 partialState = _payload;
13652 }
13653
13654 if (partialState === null || partialState === undefined) {
13655 // Null and undefined are treated as no-ops.
13656 return prevState;
13657 } // Merge the partial state and the previous state.
13658
13659
13660 return _assign({}, prevState, partialState);
13661 }
13662
13663 case ForceUpdate:
13664 {
13665 hasForceUpdate = true;
13666 return prevState;
13667 }
13668 }
13669
13670 return prevState;
13671}
13672
13673function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
13674 hasForceUpdate = false;
13675 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
13676
13677 {
13678 currentlyProcessingQueue = queue;
13679 } // These values may change as we process the queue.
13680
13681
13682 var newBaseState = queue.baseState;
13683 var newFirstUpdate = null;
13684 var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result.
13685
13686 var update = queue.firstUpdate;
13687 var resultState = newBaseState;
13688
13689 while (update !== null) {
13690 var updateExpirationTime = update.expirationTime;
13691
13692 if (updateExpirationTime < renderExpirationTime) {
13693 // This update does not have sufficient priority. Skip it.
13694 if (newFirstUpdate === null) {
13695 // This is the first skipped update. It will be the first update in
13696 // the new list.
13697 newFirstUpdate = update; // Since this is the first update that was skipped, the current result
13698 // is the new base state.
13699
13700 newBaseState = resultState;
13701 } // Since this update will remain in the list, update the remaining
13702 // expiration time.
13703
13704
13705 if (newExpirationTime < updateExpirationTime) {
13706 newExpirationTime = updateExpirationTime;
13707 }
13708 } else {
13709 // This update does have sufficient priority.
13710 // Mark the event time of this update as relevant to this render pass.
13711 // TODO: This should ideally use the true event time of this update rather than
13712 // its priority which is a derived and not reverseable value.
13713 // TODO: We should skip this update if it was already committed but currently
13714 // we have no way of detecting the difference between a committed and suspended
13715 // update here.
13716 markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result.
13717
13718 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13719 var callback = update.callback;
13720
13721 if (callback !== null) {
13722 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13723
13724 update.nextEffect = null;
13725
13726 if (queue.lastEffect === null) {
13727 queue.firstEffect = queue.lastEffect = update;
13728 } else {
13729 queue.lastEffect.nextEffect = update;
13730 queue.lastEffect = update;
13731 }
13732 }
13733 } // Continue to the next update.
13734
13735
13736 update = update.next;
13737 } // Separately, iterate though the list of captured updates.
13738
13739
13740 var newFirstCapturedUpdate = null;
13741 update = queue.firstCapturedUpdate;
13742
13743 while (update !== null) {
13744 var _updateExpirationTime = update.expirationTime;
13745
13746 if (_updateExpirationTime < renderExpirationTime) {
13747 // This update does not have sufficient priority. Skip it.
13748 if (newFirstCapturedUpdate === null) {
13749 // This is the first skipped captured update. It will be the first
13750 // update in the new list.
13751 newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is
13752 // the new base state.
13753
13754 if (newFirstUpdate === null) {
13755 newBaseState = resultState;
13756 }
13757 } // Since this update will remain in the list, update the remaining
13758 // expiration time.
13759
13760
13761 if (newExpirationTime < _updateExpirationTime) {
13762 newExpirationTime = _updateExpirationTime;
13763 }
13764 } else {
13765 // This update does have sufficient priority. Process it and compute
13766 // a new result.
13767 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13768 var _callback = update.callback;
13769
13770 if (_callback !== null) {
13771 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13772
13773 update.nextEffect = null;
13774
13775 if (queue.lastCapturedEffect === null) {
13776 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
13777 } else {
13778 queue.lastCapturedEffect.nextEffect = update;
13779 queue.lastCapturedEffect = update;
13780 }
13781 }
13782 }
13783
13784 update = update.next;
13785 }
13786
13787 if (newFirstUpdate === null) {
13788 queue.lastUpdate = null;
13789 }
13790
13791 if (newFirstCapturedUpdate === null) {
13792 queue.lastCapturedUpdate = null;
13793 } else {
13794 workInProgress.effectTag |= Callback;
13795 }
13796
13797 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
13798 // We processed every update, without skipping. That means the new base
13799 // state is the same as the result state.
13800 newBaseState = resultState;
13801 }
13802
13803 queue.baseState = newBaseState;
13804 queue.firstUpdate = newFirstUpdate;
13805 queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
13806 // This should be fine because the only two other things that contribute to
13807 // expiration time are props and context. We're already in the middle of the
13808 // begin phase by the time we start processing the queue, so we've already
13809 // dealt with the props. Context in components that specify
13810 // shouldComponentUpdate is tricky; but we'll have to account for
13811 // that regardless.
13812
13813 markUnprocessedUpdateTime(newExpirationTime);
13814 workInProgress.expirationTime = newExpirationTime;
13815 workInProgress.memoizedState = resultState;
13816
13817 {
13818 currentlyProcessingQueue = null;
13819 }
13820}
13821
13822function callCallback(callback, context) {
13823 if (!(typeof callback === 'function')) {
13824 {
13825 throw Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback);
13826 }
13827 }
13828
13829 callback.call(context);
13830}
13831
13832function resetHasForceUpdateBeforeProcessing() {
13833 hasForceUpdate = false;
13834}
13835function checkHasForceUpdateAfterProcessing() {
13836 return hasForceUpdate;
13837}
13838function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
13839 // If the finished render included captured updates, and there are still
13840 // lower priority updates left over, we need to keep the captured updates
13841 // in the queue so that they are rebased and not dropped once we process the
13842 // queue again at the lower priority.
13843 if (finishedQueue.firstCapturedUpdate !== null) {
13844 // Join the captured update list to the end of the normal list.
13845 if (finishedQueue.lastUpdate !== null) {
13846 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
13847 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
13848 } // Clear the list of captured updates.
13849
13850
13851 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
13852 } // Commit the effects
13853
13854
13855 commitUpdateEffects(finishedQueue.firstEffect, instance);
13856 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
13857 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
13858 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
13859}
13860
13861function commitUpdateEffects(effect, instance) {
13862 while (effect !== null) {
13863 var callback = effect.callback;
13864
13865 if (callback !== null) {
13866 effect.callback = null;
13867 callCallback(callback, instance);
13868 }
13869
13870 effect = effect.nextEffect;
13871 }
13872}
13873
13874var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
13875function requestCurrentSuspenseConfig() {
13876 return ReactCurrentBatchConfig.suspense;
13877}
13878
13879var fakeInternalInstance = {};
13880var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default.
13881// We'll use it to determine whether we need to initialize legacy refs.
13882
13883var emptyRefsObject = new React.Component().refs;
13884var didWarnAboutStateAssignmentForComponent;
13885var didWarnAboutUninitializedState;
13886var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
13887var didWarnAboutLegacyLifecyclesAndDerivedState;
13888var didWarnAboutUndefinedDerivedState;
13889var warnOnUndefinedDerivedState;
13890var warnOnInvalidCallback$1;
13891var didWarnAboutDirectlyAssigningPropsToState;
13892var didWarnAboutContextTypeAndContextTypes;
13893var didWarnAboutInvalidateContextType;
13894
13895{
13896 didWarnAboutStateAssignmentForComponent = new Set();
13897 didWarnAboutUninitializedState = new Set();
13898 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
13899 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
13900 didWarnAboutDirectlyAssigningPropsToState = new Set();
13901 didWarnAboutUndefinedDerivedState = new Set();
13902 didWarnAboutContextTypeAndContextTypes = new Set();
13903 didWarnAboutInvalidateContextType = new Set();
13904 var didWarnOnInvalidCallback = new Set();
13905
13906 warnOnInvalidCallback$1 = function (callback, callerName) {
13907 if (callback === null || typeof callback === 'function') {
13908 return;
13909 }
13910
13911 var key = callerName + "_" + callback;
13912
13913 if (!didWarnOnInvalidCallback.has(key)) {
13914 didWarnOnInvalidCallback.add(key);
13915 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
13916 }
13917 };
13918
13919 warnOnUndefinedDerivedState = function (type, partialState) {
13920 if (partialState === undefined) {
13921 var componentName = getComponentName(type) || 'Component';
13922
13923 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
13924 didWarnAboutUndefinedDerivedState.add(componentName);
13925 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
13926 }
13927 }
13928 }; // This is so gross but it's at least non-critical and can be removed if
13929 // it causes problems. This is meant to give a nicer error message for
13930 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
13931 // ...)) which otherwise throws a "_processChildContext is not a function"
13932 // exception.
13933
13934
13935 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
13936 enumerable: false,
13937 value: function () {
13938 {
13939 {
13940 throw 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).");
13941 }
13942 }
13943 }
13944 });
13945 Object.freeze(fakeInternalInstance);
13946}
13947
13948function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
13949 var prevState = workInProgress.memoizedState;
13950
13951 {
13952 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13953 // Invoke the function an extra time to help detect side-effects.
13954 getDerivedStateFromProps(nextProps, prevState);
13955 }
13956 }
13957
13958 var partialState = getDerivedStateFromProps(nextProps, prevState);
13959
13960 {
13961 warnOnUndefinedDerivedState(ctor, partialState);
13962 } // Merge the partial state and the previous state.
13963
13964
13965 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
13966 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
13967 // base state.
13968
13969 var updateQueue = workInProgress.updateQueue;
13970
13971 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
13972 updateQueue.baseState = memoizedState;
13973 }
13974}
13975var classComponentUpdater = {
13976 isMounted: isMounted,
13977 enqueueSetState: function (inst, payload, callback) {
13978 var fiber = get(inst);
13979 var currentTime = requestCurrentTimeForUpdate();
13980 var suspenseConfig = requestCurrentSuspenseConfig();
13981 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
13982 var update = createUpdate(expirationTime, suspenseConfig);
13983 update.payload = payload;
13984
13985 if (callback !== undefined && callback !== null) {
13986 {
13987 warnOnInvalidCallback$1(callback, 'setState');
13988 }
13989
13990 update.callback = callback;
13991 }
13992
13993 enqueueUpdate(fiber, update);
13994 scheduleWork(fiber, expirationTime);
13995 },
13996 enqueueReplaceState: function (inst, payload, callback) {
13997 var fiber = get(inst);
13998 var currentTime = requestCurrentTimeForUpdate();
13999 var suspenseConfig = requestCurrentSuspenseConfig();
14000 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14001 var update = createUpdate(expirationTime, suspenseConfig);
14002 update.tag = ReplaceState;
14003 update.payload = payload;
14004
14005 if (callback !== undefined && callback !== null) {
14006 {
14007 warnOnInvalidCallback$1(callback, 'replaceState');
14008 }
14009
14010 update.callback = callback;
14011 }
14012
14013 enqueueUpdate(fiber, update);
14014 scheduleWork(fiber, expirationTime);
14015 },
14016 enqueueForceUpdate: function (inst, callback) {
14017 var fiber = get(inst);
14018 var currentTime = requestCurrentTimeForUpdate();
14019 var suspenseConfig = requestCurrentSuspenseConfig();
14020 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14021 var update = createUpdate(expirationTime, suspenseConfig);
14022 update.tag = ForceUpdate;
14023
14024 if (callback !== undefined && callback !== null) {
14025 {
14026 warnOnInvalidCallback$1(callback, 'forceUpdate');
14027 }
14028
14029 update.callback = callback;
14030 }
14031
14032 enqueueUpdate(fiber, update);
14033 scheduleWork(fiber, expirationTime);
14034 }
14035};
14036
14037function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
14038 var instance = workInProgress.stateNode;
14039
14040 if (typeof instance.shouldComponentUpdate === 'function') {
14041 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
14042 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
14043 stopPhaseTimer();
14044
14045 {
14046 !(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;
14047 }
14048
14049 return shouldUpdate;
14050 }
14051
14052 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
14053 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
14054 }
14055
14056 return true;
14057}
14058
14059function checkClassInstance(workInProgress, ctor, newProps) {
14060 var instance = workInProgress.stateNode;
14061
14062 {
14063 var name = getComponentName(ctor) || 'Component';
14064 var renderPresent = instance.render;
14065
14066 if (!renderPresent) {
14067 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
14068 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
14069 } else {
14070 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
14071 }
14072 }
14073
14074 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
14075 !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;
14076 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
14077 !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;
14078 var noInstancePropTypes = !instance.propTypes;
14079 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
14080 var noInstanceContextType = !instance.contextType;
14081 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
14082
14083 if (disableLegacyContext) {
14084 if (ctor.childContextTypes) {
14085 warningWithoutStack$1(false, '%s uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', name);
14086 }
14087
14088 if (ctor.contextTypes) {
14089 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', name);
14090 }
14091 } else {
14092 var noInstanceContextTypes = !instance.contextTypes;
14093 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
14094
14095 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
14096 didWarnAboutContextTypeAndContextTypes.add(ctor);
14097 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
14098 }
14099 }
14100
14101 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
14102 !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;
14103
14104 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
14105 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');
14106 }
14107
14108 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
14109 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
14110 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
14111 !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;
14112 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
14113 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
14114 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
14115 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
14116 var hasMutatedProps = instance.props !== newProps;
14117 !(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;
14118 var noInstanceDefaultProps = !instance.defaultProps;
14119 !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;
14120
14121 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
14122 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
14123 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
14124 }
14125
14126 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
14127 !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;
14128 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
14129 !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;
14130 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
14131 !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;
14132 var _state = instance.state;
14133
14134 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
14135 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
14136 }
14137
14138 if (typeof instance.getChildContext === 'function') {
14139 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
14140 }
14141 }
14142}
14143
14144function adoptClassInstance(workInProgress, instance) {
14145 instance.updater = classComponentUpdater;
14146 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
14147
14148 set(instance, workInProgress);
14149
14150 {
14151 instance._reactInternalInstance = fakeInternalInstance;
14152 }
14153}
14154
14155function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
14156 var isLegacyContextConsumer = false;
14157 var unmaskedContext = emptyContextObject;
14158 var context = emptyContextObject;
14159 var contextType = ctor.contextType;
14160
14161 {
14162 if ('contextType' in ctor) {
14163 var isValid = // Allow null for conditional declaration
14164 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
14165
14166 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
14167 didWarnAboutInvalidateContextType.add(ctor);
14168 var addendum = '';
14169
14170 if (contextType === undefined) {
14171 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.';
14172 } else if (typeof contextType !== 'object') {
14173 addendum = ' However, it is set to a ' + typeof contextType + '.';
14174 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
14175 addendum = ' Did you accidentally pass the Context.Provider instead?';
14176 } else if (contextType._context !== undefined) {
14177 // <Context.Consumer>
14178 addendum = ' Did you accidentally pass the Context.Consumer instead?';
14179 } else {
14180 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
14181 }
14182
14183 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
14184 }
14185 }
14186 }
14187
14188 if (typeof contextType === 'object' && contextType !== null) {
14189 context = readContext(contextType);
14190 } else if (!disableLegacyContext) {
14191 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14192 var contextTypes = ctor.contextTypes;
14193 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
14194 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
14195 } // Instantiate twice to help detect side-effects.
14196
14197
14198 {
14199 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14200 new ctor(props, context); // eslint-disable-line no-new
14201 }
14202 }
14203
14204 var instance = new ctor(props, context);
14205 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
14206 adoptClassInstance(workInProgress, instance);
14207
14208 {
14209 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
14210 var componentName = getComponentName(ctor) || 'Component';
14211
14212 if (!didWarnAboutUninitializedState.has(componentName)) {
14213 didWarnAboutUninitializedState.add(componentName);
14214 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);
14215 }
14216 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
14217 // Warn about these lifecycles if they are present.
14218 // Don't warn about react-lifecycles-compat polyfilled methods though.
14219
14220
14221 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
14222 var foundWillMountName = null;
14223 var foundWillReceivePropsName = null;
14224 var foundWillUpdateName = null;
14225
14226 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
14227 foundWillMountName = 'componentWillMount';
14228 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
14229 foundWillMountName = 'UNSAFE_componentWillMount';
14230 }
14231
14232 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
14233 foundWillReceivePropsName = 'componentWillReceiveProps';
14234 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14235 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
14236 }
14237
14238 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
14239 foundWillUpdateName = 'componentWillUpdate';
14240 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14241 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
14242 }
14243
14244 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
14245 var _componentName = getComponentName(ctor) || 'Component';
14246
14247 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
14248
14249 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
14250 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
14251 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 : '');
14252 }
14253 }
14254 }
14255 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
14256 // ReactFiberContext usually updates this cache but can't for newly-created instances.
14257
14258
14259 if (isLegacyContextConsumer) {
14260 cacheContext(workInProgress, unmaskedContext, context);
14261 }
14262
14263 return instance;
14264}
14265
14266function callComponentWillMount(workInProgress, instance) {
14267 startPhaseTimer(workInProgress, 'componentWillMount');
14268 var oldState = instance.state;
14269
14270 if (typeof instance.componentWillMount === 'function') {
14271 instance.componentWillMount();
14272 }
14273
14274 if (typeof instance.UNSAFE_componentWillMount === 'function') {
14275 instance.UNSAFE_componentWillMount();
14276 }
14277
14278 stopPhaseTimer();
14279
14280 if (oldState !== instance.state) {
14281 {
14282 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');
14283 }
14284
14285 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14286 }
14287}
14288
14289function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
14290 var oldState = instance.state;
14291 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
14292
14293 if (typeof instance.componentWillReceiveProps === 'function') {
14294 instance.componentWillReceiveProps(newProps, nextContext);
14295 }
14296
14297 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14298 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
14299 }
14300
14301 stopPhaseTimer();
14302
14303 if (instance.state !== oldState) {
14304 {
14305 var componentName = getComponentName(workInProgress.type) || 'Component';
14306
14307 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
14308 didWarnAboutStateAssignmentForComponent.add(componentName);
14309 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
14310 }
14311 }
14312
14313 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14314 }
14315} // Invokes the mount life-cycles on a previously never rendered instance.
14316
14317
14318function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14319 {
14320 checkClassInstance(workInProgress, ctor, newProps);
14321 }
14322
14323 var instance = workInProgress.stateNode;
14324 instance.props = newProps;
14325 instance.state = workInProgress.memoizedState;
14326 instance.refs = emptyRefsObject;
14327 var contextType = ctor.contextType;
14328
14329 if (typeof contextType === 'object' && contextType !== null) {
14330 instance.context = readContext(contextType);
14331 } else if (disableLegacyContext) {
14332 instance.context = emptyContextObject;
14333 } else {
14334 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14335 instance.context = getMaskedContext(workInProgress, unmaskedContext);
14336 }
14337
14338 {
14339 if (instance.state === newProps) {
14340 var componentName = getComponentName(ctor) || 'Component';
14341
14342 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
14343 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
14344 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);
14345 }
14346 }
14347
14348 if (workInProgress.mode & StrictMode) {
14349 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
14350 }
14351
14352 if (warnAboutDeprecatedLifecycles) {
14353 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
14354 }
14355 }
14356
14357 var updateQueue = workInProgress.updateQueue;
14358
14359 if (updateQueue !== null) {
14360 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14361 instance.state = workInProgress.memoizedState;
14362 }
14363
14364 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14365
14366 if (typeof getDerivedStateFromProps === 'function') {
14367 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14368 instance.state = workInProgress.memoizedState;
14369 } // In order to support react-lifecycles-compat polyfilled components,
14370 // Unsafe lifecycles should not be invoked for components using the new APIs.
14371
14372
14373 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14374 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
14375 // process them now.
14376
14377 updateQueue = workInProgress.updateQueue;
14378
14379 if (updateQueue !== null) {
14380 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14381 instance.state = workInProgress.memoizedState;
14382 }
14383 }
14384
14385 if (typeof instance.componentDidMount === 'function') {
14386 workInProgress.effectTag |= Update;
14387 }
14388}
14389
14390function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14391 var instance = workInProgress.stateNode;
14392 var oldProps = workInProgress.memoizedProps;
14393 instance.props = oldProps;
14394 var oldContext = instance.context;
14395 var contextType = ctor.contextType;
14396 var nextContext = emptyContextObject;
14397
14398 if (typeof contextType === 'object' && contextType !== null) {
14399 nextContext = readContext(contextType);
14400 } else if (!disableLegacyContext) {
14401 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14402 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
14403 }
14404
14405 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14406 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14407 // ever the previously attempted to render - not the "current". However,
14408 // during componentDidUpdate we pass the "current" props.
14409 // In order to support react-lifecycles-compat polyfilled components,
14410 // Unsafe lifecycles should not be invoked for components using the new APIs.
14411
14412 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14413 if (oldProps !== newProps || oldContext !== nextContext) {
14414 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14415 }
14416 }
14417
14418 resetHasForceUpdateBeforeProcessing();
14419 var oldState = workInProgress.memoizedState;
14420 var newState = instance.state = oldState;
14421 var updateQueue = workInProgress.updateQueue;
14422
14423 if (updateQueue !== null) {
14424 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14425 newState = workInProgress.memoizedState;
14426 }
14427
14428 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14429 // If an update was already in progress, we should schedule an Update
14430 // effect even though we're bailing out, so that cWU/cDU are called.
14431 if (typeof instance.componentDidMount === 'function') {
14432 workInProgress.effectTag |= Update;
14433 }
14434
14435 return false;
14436 }
14437
14438 if (typeof getDerivedStateFromProps === 'function') {
14439 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14440 newState = workInProgress.memoizedState;
14441 }
14442
14443 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14444
14445 if (shouldUpdate) {
14446 // In order to support react-lifecycles-compat polyfilled components,
14447 // Unsafe lifecycles should not be invoked for components using the new APIs.
14448 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14449 startPhaseTimer(workInProgress, 'componentWillMount');
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
14462 if (typeof instance.componentDidMount === 'function') {
14463 workInProgress.effectTag |= Update;
14464 }
14465 } else {
14466 // If an update was already in progress, we should schedule an Update
14467 // effect even though we're bailing out, so that cWU/cDU are called.
14468 if (typeof instance.componentDidMount === 'function') {
14469 workInProgress.effectTag |= Update;
14470 } // If shouldComponentUpdate returned false, we should still update the
14471 // memoized state to indicate that this work can be reused.
14472
14473
14474 workInProgress.memoizedProps = newProps;
14475 workInProgress.memoizedState = newState;
14476 } // Update the existing instance's state, props, and context pointers even
14477 // if shouldComponentUpdate returns false.
14478
14479
14480 instance.props = newProps;
14481 instance.state = newState;
14482 instance.context = nextContext;
14483 return shouldUpdate;
14484} // Invokes the update life-cycles and returns false if it shouldn't rerender.
14485
14486
14487function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
14488 var instance = workInProgress.stateNode;
14489 var oldProps = workInProgress.memoizedProps;
14490 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
14491 var oldContext = instance.context;
14492 var contextType = ctor.contextType;
14493 var nextContext = emptyContextObject;
14494
14495 if (typeof contextType === 'object' && contextType !== null) {
14496 nextContext = readContext(contextType);
14497 } else if (!disableLegacyContext) {
14498 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14499 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
14500 }
14501
14502 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14503 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14504 // ever the previously attempted to render - not the "current". However,
14505 // during componentDidUpdate we pass the "current" props.
14506 // In order to support react-lifecycles-compat polyfilled components,
14507 // Unsafe lifecycles should not be invoked for components using the new APIs.
14508
14509 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14510 if (oldProps !== newProps || oldContext !== nextContext) {
14511 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14512 }
14513 }
14514
14515 resetHasForceUpdateBeforeProcessing();
14516 var oldState = workInProgress.memoizedState;
14517 var newState = instance.state = oldState;
14518 var updateQueue = workInProgress.updateQueue;
14519
14520 if (updateQueue !== null) {
14521 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14522 newState = workInProgress.memoizedState;
14523 }
14524
14525 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14526 // If an update was already in progress, we should schedule an Update
14527 // effect even though we're bailing out, so that cWU/cDU are called.
14528 if (typeof instance.componentDidUpdate === 'function') {
14529 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14530 workInProgress.effectTag |= Update;
14531 }
14532 }
14533
14534 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14535 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14536 workInProgress.effectTag |= Snapshot;
14537 }
14538 }
14539
14540 return false;
14541 }
14542
14543 if (typeof getDerivedStateFromProps === 'function') {
14544 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14545 newState = workInProgress.memoizedState;
14546 }
14547
14548 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14549
14550 if (shouldUpdate) {
14551 // In order to support react-lifecycles-compat polyfilled components,
14552 // Unsafe lifecycles should not be invoked for components using the new APIs.
14553 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
14554 startPhaseTimer(workInProgress, 'componentWillUpdate');
14555
14556 if (typeof instance.componentWillUpdate === 'function') {
14557 instance.componentWillUpdate(newProps, newState, nextContext);
14558 }
14559
14560 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14561 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
14562 }
14563
14564 stopPhaseTimer();
14565 }
14566
14567 if (typeof instance.componentDidUpdate === 'function') {
14568 workInProgress.effectTag |= Update;
14569 }
14570
14571 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14572 workInProgress.effectTag |= Snapshot;
14573 }
14574 } else {
14575 // If an update was already in progress, we should schedule an Update
14576 // effect even though we're bailing out, so that cWU/cDU are called.
14577 if (typeof instance.componentDidUpdate === 'function') {
14578 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14579 workInProgress.effectTag |= Update;
14580 }
14581 }
14582
14583 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14584 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14585 workInProgress.effectTag |= Snapshot;
14586 }
14587 } // If shouldComponentUpdate returned false, we should still update the
14588 // memoized props/state to indicate that this work can be reused.
14589
14590
14591 workInProgress.memoizedProps = newProps;
14592 workInProgress.memoizedState = newState;
14593 } // Update the existing instance's state, props, and context pointers even
14594 // if shouldComponentUpdate returns false.
14595
14596
14597 instance.props = newProps;
14598 instance.state = newState;
14599 instance.context = nextContext;
14600 return shouldUpdate;
14601}
14602
14603var didWarnAboutMaps;
14604var didWarnAboutGenerators;
14605var didWarnAboutStringRefs;
14606var ownerHasKeyUseWarning;
14607var ownerHasFunctionTypeWarning;
14608
14609var warnForMissingKey = function (child) {};
14610
14611{
14612 didWarnAboutMaps = false;
14613 didWarnAboutGenerators = false;
14614 didWarnAboutStringRefs = {};
14615 /**
14616 * Warn if there's no key explicitly set on dynamic arrays of children or
14617 * object keys are not valid. This allows us to keep track of children between
14618 * updates.
14619 */
14620
14621 ownerHasKeyUseWarning = {};
14622 ownerHasFunctionTypeWarning = {};
14623
14624 warnForMissingKey = function (child) {
14625 if (child === null || typeof child !== 'object') {
14626 return;
14627 }
14628
14629 if (!child._store || child._store.validated || child.key != null) {
14630 return;
14631 }
14632
14633 if (!(typeof child._store === 'object')) {
14634 {
14635 throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
14636 }
14637 }
14638
14639 child._store.validated = true;
14640 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
14641
14642 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
14643 return;
14644 }
14645
14646 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
14647 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
14648 };
14649}
14650
14651var isArray = Array.isArray;
14652
14653function coerceRef(returnFiber, current$$1, element) {
14654 var mixedRef = element.ref;
14655
14656 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
14657 {
14658 // TODO: Clean this up once we turn on the string ref warning for
14659 // everyone, because the strict mode case will no longer be relevant
14660 if (returnFiber.mode & StrictMode || warnAboutStringRefs) {
14661 var componentName = getComponentName(returnFiber.type) || 'Component';
14662
14663 if (!didWarnAboutStringRefs[componentName]) {
14664 if (warnAboutStringRefs) {
14665 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));
14666 } else {
14667 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));
14668 }
14669
14670 didWarnAboutStringRefs[componentName] = true;
14671 }
14672 }
14673 }
14674
14675 if (element._owner) {
14676 var owner = element._owner;
14677 var inst;
14678
14679 if (owner) {
14680 var ownerFiber = owner;
14681
14682 if (!(ownerFiber.tag === ClassComponent)) {
14683 {
14684 throw Error("Function components cannot have refs. Did you mean to use React.forwardRef()?");
14685 }
14686 }
14687
14688 inst = ownerFiber.stateNode;
14689 }
14690
14691 if (!inst) {
14692 {
14693 throw Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
14694 }
14695 }
14696
14697 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
14698
14699 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
14700 return current$$1.ref;
14701 }
14702
14703 var ref = function (value) {
14704 var refs = inst.refs;
14705
14706 if (refs === emptyRefsObject) {
14707 // This is a lazy pooled frozen object, so we need to initialize.
14708 refs = inst.refs = {};
14709 }
14710
14711 if (value === null) {
14712 delete refs[stringRef];
14713 } else {
14714 refs[stringRef] = value;
14715 }
14716 };
14717
14718 ref._stringRef = stringRef;
14719 return ref;
14720 } else {
14721 if (!(typeof mixedRef === 'string')) {
14722 {
14723 throw Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
14724 }
14725 }
14726
14727 if (!element._owner) {
14728 {
14729 throw 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.");
14730 }
14731 }
14732 }
14733 }
14734
14735 return mixedRef;
14736}
14737
14738function throwOnInvalidObjectType(returnFiber, newChild) {
14739 if (returnFiber.type !== 'textarea') {
14740 var addendum = '';
14741
14742 {
14743 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
14744 }
14745
14746 {
14747 {
14748 throw 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);
14749 }
14750 }
14751 }
14752}
14753
14754function warnOnFunctionType() {
14755 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();
14756
14757 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
14758 return;
14759 }
14760
14761 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
14762 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.');
14763} // This wrapper function exists because I expect to clone the code in each path
14764// to be able to optimize each path individually by branching early. This needs
14765// a compiler or we can do it manually. Helpers that don't need this branching
14766// live outside of this function.
14767
14768
14769function ChildReconciler(shouldTrackSideEffects) {
14770 function deleteChild(returnFiber, childToDelete) {
14771 if (!shouldTrackSideEffects) {
14772 // Noop.
14773 return;
14774 } // Deletions are added in reversed order so we add it to the front.
14775 // At this point, the return fiber's effect list is empty except for
14776 // deletions, so we can just append the deletion to the list. The remaining
14777 // effects aren't added until the complete phase. Once we implement
14778 // resuming, this may not be true.
14779
14780
14781 var last = returnFiber.lastEffect;
14782
14783 if (last !== null) {
14784 last.nextEffect = childToDelete;
14785 returnFiber.lastEffect = childToDelete;
14786 } else {
14787 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14788 }
14789
14790 childToDelete.nextEffect = null;
14791 childToDelete.effectTag = Deletion;
14792 }
14793
14794 function deleteRemainingChildren(returnFiber, currentFirstChild) {
14795 if (!shouldTrackSideEffects) {
14796 // Noop.
14797 return null;
14798 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
14799 // assuming that after the first child we've already added everything.
14800
14801
14802 var childToDelete = currentFirstChild;
14803
14804 while (childToDelete !== null) {
14805 deleteChild(returnFiber, childToDelete);
14806 childToDelete = childToDelete.sibling;
14807 }
14808
14809 return null;
14810 }
14811
14812 function mapRemainingChildren(returnFiber, currentFirstChild) {
14813 // Add the remaining children to a temporary map so that we can find them by
14814 // keys quickly. Implicit (null) keys get added to this set with their index
14815 // instead.
14816 var existingChildren = new Map();
14817 var existingChild = currentFirstChild;
14818
14819 while (existingChild !== null) {
14820 if (existingChild.key !== null) {
14821 existingChildren.set(existingChild.key, existingChild);
14822 } else {
14823 existingChildren.set(existingChild.index, existingChild);
14824 }
14825
14826 existingChild = existingChild.sibling;
14827 }
14828
14829 return existingChildren;
14830 }
14831
14832 function useFiber(fiber, pendingProps, expirationTime) {
14833 // We currently set sibling to null and index to 0 here because it is easy
14834 // to forget to do before returning it. E.g. for the single child case.
14835 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
14836 clone.index = 0;
14837 clone.sibling = null;
14838 return clone;
14839 }
14840
14841 function placeChild(newFiber, lastPlacedIndex, newIndex) {
14842 newFiber.index = newIndex;
14843
14844 if (!shouldTrackSideEffects) {
14845 // Noop.
14846 return lastPlacedIndex;
14847 }
14848
14849 var current$$1 = newFiber.alternate;
14850
14851 if (current$$1 !== null) {
14852 var oldIndex = current$$1.index;
14853
14854 if (oldIndex < lastPlacedIndex) {
14855 // This is a move.
14856 newFiber.effectTag = Placement;
14857 return lastPlacedIndex;
14858 } else {
14859 // This item can stay in place.
14860 return oldIndex;
14861 }
14862 } else {
14863 // This is an insertion.
14864 newFiber.effectTag = Placement;
14865 return lastPlacedIndex;
14866 }
14867 }
14868
14869 function placeSingleChild(newFiber) {
14870 // This is simpler for the single child case. We only need to do a
14871 // placement for inserting new children.
14872 if (shouldTrackSideEffects && newFiber.alternate === null) {
14873 newFiber.effectTag = Placement;
14874 }
14875
14876 return newFiber;
14877 }
14878
14879 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
14880 if (current$$1 === null || current$$1.tag !== HostText) {
14881 // Insert
14882 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
14883 created.return = returnFiber;
14884 return created;
14885 } else {
14886 // Update
14887 var existing = useFiber(current$$1, textContent, expirationTime);
14888 existing.return = returnFiber;
14889 return existing;
14890 }
14891 }
14892
14893 function updateElement(returnFiber, current$$1, element, expirationTime) {
14894 if (current$$1 !== null && (current$$1.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
14895 isCompatibleFamilyForHotReloading(current$$1, element)))) {
14896 // Move based on index
14897 var existing = useFiber(current$$1, element.props, expirationTime);
14898 existing.ref = coerceRef(returnFiber, current$$1, element);
14899 existing.return = returnFiber;
14900
14901 {
14902 existing._debugSource = element._source;
14903 existing._debugOwner = element._owner;
14904 }
14905
14906 return existing;
14907 } else {
14908 // Insert
14909 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
14910 created.ref = coerceRef(returnFiber, current$$1, element);
14911 created.return = returnFiber;
14912 return created;
14913 }
14914 }
14915
14916 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
14917 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
14918 // Insert
14919 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
14920 created.return = returnFiber;
14921 return created;
14922 } else {
14923 // Update
14924 var existing = useFiber(current$$1, portal.children || [], expirationTime);
14925 existing.return = returnFiber;
14926 return existing;
14927 }
14928 }
14929
14930 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
14931 if (current$$1 === null || current$$1.tag !== Fragment) {
14932 // Insert
14933 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
14934 created.return = returnFiber;
14935 return created;
14936 } else {
14937 // Update
14938 var existing = useFiber(current$$1, fragment, expirationTime);
14939 existing.return = returnFiber;
14940 return existing;
14941 }
14942 }
14943
14944 function createChild(returnFiber, newChild, expirationTime) {
14945 if (typeof newChild === 'string' || typeof newChild === 'number') {
14946 // Text nodes don't have keys. If the previous node is implicitly keyed
14947 // we can continue to replace it without aborting even if it is not a text
14948 // node.
14949 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
14950 created.return = returnFiber;
14951 return created;
14952 }
14953
14954 if (typeof newChild === 'object' && newChild !== null) {
14955 switch (newChild.$$typeof) {
14956 case REACT_ELEMENT_TYPE:
14957 {
14958 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
14959
14960 _created.ref = coerceRef(returnFiber, null, newChild);
14961 _created.return = returnFiber;
14962 return _created;
14963 }
14964
14965 case REACT_PORTAL_TYPE:
14966 {
14967 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
14968
14969 _created2.return = returnFiber;
14970 return _created2;
14971 }
14972 }
14973
14974 if (isArray(newChild) || getIteratorFn(newChild)) {
14975 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
14976
14977 _created3.return = returnFiber;
14978 return _created3;
14979 }
14980
14981 throwOnInvalidObjectType(returnFiber, newChild);
14982 }
14983
14984 {
14985 if (typeof newChild === 'function') {
14986 warnOnFunctionType();
14987 }
14988 }
14989
14990 return null;
14991 }
14992
14993 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
14994 // Update the fiber if the keys match, otherwise return null.
14995 var key = oldFiber !== null ? oldFiber.key : null;
14996
14997 if (typeof newChild === 'string' || typeof newChild === 'number') {
14998 // Text nodes don't have keys. If the previous node is implicitly keyed
14999 // we can continue to replace it without aborting even if it is not a text
15000 // node.
15001 if (key !== null) {
15002 return null;
15003 }
15004
15005 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
15006 }
15007
15008 if (typeof newChild === 'object' && newChild !== null) {
15009 switch (newChild.$$typeof) {
15010 case REACT_ELEMENT_TYPE:
15011 {
15012 if (newChild.key === key) {
15013 if (newChild.type === REACT_FRAGMENT_TYPE) {
15014 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
15015 }
15016
15017 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
15018 } else {
15019 return null;
15020 }
15021 }
15022
15023 case REACT_PORTAL_TYPE:
15024 {
15025 if (newChild.key === key) {
15026 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
15027 } else {
15028 return null;
15029 }
15030 }
15031 }
15032
15033 if (isArray(newChild) || getIteratorFn(newChild)) {
15034 if (key !== null) {
15035 return null;
15036 }
15037
15038 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
15039 }
15040
15041 throwOnInvalidObjectType(returnFiber, newChild);
15042 }
15043
15044 {
15045 if (typeof newChild === 'function') {
15046 warnOnFunctionType();
15047 }
15048 }
15049
15050 return null;
15051 }
15052
15053 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
15054 if (typeof newChild === 'string' || typeof newChild === 'number') {
15055 // Text nodes don't have keys, so we neither have to check the old nor
15056 // new node for the key. If both are text nodes, they match.
15057 var matchedFiber = existingChildren.get(newIdx) || null;
15058 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
15059 }
15060
15061 if (typeof newChild === 'object' && newChild !== null) {
15062 switch (newChild.$$typeof) {
15063 case REACT_ELEMENT_TYPE:
15064 {
15065 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15066
15067 if (newChild.type === REACT_FRAGMENT_TYPE) {
15068 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
15069 }
15070
15071 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
15072 }
15073
15074 case REACT_PORTAL_TYPE:
15075 {
15076 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15077
15078 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
15079 }
15080 }
15081
15082 if (isArray(newChild) || getIteratorFn(newChild)) {
15083 var _matchedFiber3 = existingChildren.get(newIdx) || null;
15084
15085 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
15086 }
15087
15088 throwOnInvalidObjectType(returnFiber, newChild);
15089 }
15090
15091 {
15092 if (typeof newChild === 'function') {
15093 warnOnFunctionType();
15094 }
15095 }
15096
15097 return null;
15098 }
15099 /**
15100 * Warns if there is a duplicate or missing key
15101 */
15102
15103
15104 function warnOnInvalidKey(child, knownKeys) {
15105 {
15106 if (typeof child !== 'object' || child === null) {
15107 return knownKeys;
15108 }
15109
15110 switch (child.$$typeof) {
15111 case REACT_ELEMENT_TYPE:
15112 case REACT_PORTAL_TYPE:
15113 warnForMissingKey(child);
15114 var key = child.key;
15115
15116 if (typeof key !== 'string') {
15117 break;
15118 }
15119
15120 if (knownKeys === null) {
15121 knownKeys = new Set();
15122 knownKeys.add(key);
15123 break;
15124 }
15125
15126 if (!knownKeys.has(key)) {
15127 knownKeys.add(key);
15128 break;
15129 }
15130
15131 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);
15132 break;
15133
15134 default:
15135 break;
15136 }
15137 }
15138
15139 return knownKeys;
15140 }
15141
15142 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
15143 // This algorithm can't optimize by searching from both ends since we
15144 // don't have backpointers on fibers. I'm trying to see how far we can get
15145 // with that model. If it ends up not being worth the tradeoffs, we can
15146 // add it later.
15147 // Even with a two ended optimization, we'd want to optimize for the case
15148 // where there are few changes and brute force the comparison instead of
15149 // going for the Map. It'd like to explore hitting that path first in
15150 // forward-only mode and only go for the Map once we notice that we need
15151 // lots of look ahead. This doesn't handle reversal as well as two ended
15152 // search but that's unusual. Besides, for the two ended optimization to
15153 // work on Iterables, we'd need to copy the whole set.
15154 // In this first iteration, we'll just live with hitting the bad case
15155 // (adding everything to a Map) in for every insert/move.
15156 // If you change this code, also update reconcileChildrenIterator() which
15157 // uses the same algorithm.
15158 {
15159 // First, validate keys.
15160 var knownKeys = null;
15161
15162 for (var i = 0; i < newChildren.length; i++) {
15163 var child = newChildren[i];
15164 knownKeys = warnOnInvalidKey(child, knownKeys);
15165 }
15166 }
15167
15168 var resultingFirstChild = null;
15169 var previousNewFiber = null;
15170 var oldFiber = currentFirstChild;
15171 var lastPlacedIndex = 0;
15172 var newIdx = 0;
15173 var nextOldFiber = null;
15174
15175 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
15176 if (oldFiber.index > newIdx) {
15177 nextOldFiber = oldFiber;
15178 oldFiber = null;
15179 } else {
15180 nextOldFiber = oldFiber.sibling;
15181 }
15182
15183 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
15184
15185 if (newFiber === null) {
15186 // TODO: This breaks on empty slots like null children. That's
15187 // unfortunate because it triggers the slow path all the time. We need
15188 // a better way to communicate whether this was a miss or null,
15189 // boolean, undefined, etc.
15190 if (oldFiber === null) {
15191 oldFiber = nextOldFiber;
15192 }
15193
15194 break;
15195 }
15196
15197 if (shouldTrackSideEffects) {
15198 if (oldFiber && newFiber.alternate === null) {
15199 // We matched the slot, but we didn't reuse the existing fiber, so we
15200 // need to delete the existing child.
15201 deleteChild(returnFiber, oldFiber);
15202 }
15203 }
15204
15205 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15206
15207 if (previousNewFiber === null) {
15208 // TODO: Move out of the loop. This only happens for the first run.
15209 resultingFirstChild = newFiber;
15210 } else {
15211 // TODO: Defer siblings if we're not at the right index for this slot.
15212 // I.e. if we had null values before, then we want to defer this
15213 // for each null value. However, we also don't want to call updateSlot
15214 // with the previous one.
15215 previousNewFiber.sibling = newFiber;
15216 }
15217
15218 previousNewFiber = newFiber;
15219 oldFiber = nextOldFiber;
15220 }
15221
15222 if (newIdx === newChildren.length) {
15223 // We've reached the end of the new children. We can delete the rest.
15224 deleteRemainingChildren(returnFiber, oldFiber);
15225 return resultingFirstChild;
15226 }
15227
15228 if (oldFiber === null) {
15229 // If we don't have any more existing children we can choose a fast path
15230 // since the rest will all be insertions.
15231 for (; newIdx < newChildren.length; newIdx++) {
15232 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
15233
15234 if (_newFiber === null) {
15235 continue;
15236 }
15237
15238 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
15239
15240 if (previousNewFiber === null) {
15241 // TODO: Move out of the loop. This only happens for the first run.
15242 resultingFirstChild = _newFiber;
15243 } else {
15244 previousNewFiber.sibling = _newFiber;
15245 }
15246
15247 previousNewFiber = _newFiber;
15248 }
15249
15250 return resultingFirstChild;
15251 } // Add all children to a key map for quick lookups.
15252
15253
15254 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15255
15256 for (; newIdx < newChildren.length; newIdx++) {
15257 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
15258
15259 if (_newFiber2 !== null) {
15260 if (shouldTrackSideEffects) {
15261 if (_newFiber2.alternate !== null) {
15262 // The new fiber is a work in progress, but if there exists a
15263 // current, that means that we reused the fiber. We need to delete
15264 // it from the child list so that we don't add it to the deletion
15265 // list.
15266 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
15267 }
15268 }
15269
15270 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
15271
15272 if (previousNewFiber === null) {
15273 resultingFirstChild = _newFiber2;
15274 } else {
15275 previousNewFiber.sibling = _newFiber2;
15276 }
15277
15278 previousNewFiber = _newFiber2;
15279 }
15280 }
15281
15282 if (shouldTrackSideEffects) {
15283 // Any existing children that weren't consumed above were deleted. We need
15284 // to add them to the deletion list.
15285 existingChildren.forEach(function (child) {
15286 return deleteChild(returnFiber, child);
15287 });
15288 }
15289
15290 return resultingFirstChild;
15291 }
15292
15293 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
15294 // This is the same implementation as reconcileChildrenArray(),
15295 // but using the iterator instead.
15296 var iteratorFn = getIteratorFn(newChildrenIterable);
15297
15298 if (!(typeof iteratorFn === 'function')) {
15299 {
15300 throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
15301 }
15302 }
15303
15304 {
15305 // We don't support rendering Generators because it's a mutation.
15306 // See https://github.com/facebook/react/issues/12995
15307 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
15308 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
15309 !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;
15310 didWarnAboutGenerators = true;
15311 } // Warn about using Maps as children
15312
15313
15314 if (newChildrenIterable.entries === iteratorFn) {
15315 !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;
15316 didWarnAboutMaps = true;
15317 } // First, validate keys.
15318 // We'll get a different iterator later for the main pass.
15319
15320
15321 var _newChildren = iteratorFn.call(newChildrenIterable);
15322
15323 if (_newChildren) {
15324 var knownKeys = null;
15325
15326 var _step = _newChildren.next();
15327
15328 for (; !_step.done; _step = _newChildren.next()) {
15329 var child = _step.value;
15330 knownKeys = warnOnInvalidKey(child, knownKeys);
15331 }
15332 }
15333 }
15334
15335 var newChildren = iteratorFn.call(newChildrenIterable);
15336
15337 if (!(newChildren != null)) {
15338 {
15339 throw Error("An iterable object provided no iterator.");
15340 }
15341 }
15342
15343 var resultingFirstChild = null;
15344 var previousNewFiber = null;
15345 var oldFiber = currentFirstChild;
15346 var lastPlacedIndex = 0;
15347 var newIdx = 0;
15348 var nextOldFiber = null;
15349 var step = newChildren.next();
15350
15351 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
15352 if (oldFiber.index > newIdx) {
15353 nextOldFiber = oldFiber;
15354 oldFiber = null;
15355 } else {
15356 nextOldFiber = oldFiber.sibling;
15357 }
15358
15359 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
15360
15361 if (newFiber === null) {
15362 // TODO: This breaks on empty slots like null children. That's
15363 // unfortunate because it triggers the slow path all the time. We need
15364 // a better way to communicate whether this was a miss or null,
15365 // boolean, undefined, etc.
15366 if (oldFiber === null) {
15367 oldFiber = nextOldFiber;
15368 }
15369
15370 break;
15371 }
15372
15373 if (shouldTrackSideEffects) {
15374 if (oldFiber && newFiber.alternate === null) {
15375 // We matched the slot, but we didn't reuse the existing fiber, so we
15376 // need to delete the existing child.
15377 deleteChild(returnFiber, oldFiber);
15378 }
15379 }
15380
15381 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15382
15383 if (previousNewFiber === null) {
15384 // TODO: Move out of the loop. This only happens for the first run.
15385 resultingFirstChild = newFiber;
15386 } else {
15387 // TODO: Defer siblings if we're not at the right index for this slot.
15388 // I.e. if we had null values before, then we want to defer this
15389 // for each null value. However, we also don't want to call updateSlot
15390 // with the previous one.
15391 previousNewFiber.sibling = newFiber;
15392 }
15393
15394 previousNewFiber = newFiber;
15395 oldFiber = nextOldFiber;
15396 }
15397
15398 if (step.done) {
15399 // We've reached the end of the new children. We can delete the rest.
15400 deleteRemainingChildren(returnFiber, oldFiber);
15401 return resultingFirstChild;
15402 }
15403
15404 if (oldFiber === null) {
15405 // If we don't have any more existing children we can choose a fast path
15406 // since the rest will all be insertions.
15407 for (; !step.done; newIdx++, step = newChildren.next()) {
15408 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
15409
15410 if (_newFiber3 === null) {
15411 continue;
15412 }
15413
15414 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
15415
15416 if (previousNewFiber === null) {
15417 // TODO: Move out of the loop. This only happens for the first run.
15418 resultingFirstChild = _newFiber3;
15419 } else {
15420 previousNewFiber.sibling = _newFiber3;
15421 }
15422
15423 previousNewFiber = _newFiber3;
15424 }
15425
15426 return resultingFirstChild;
15427 } // Add all children to a key map for quick lookups.
15428
15429
15430 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15431
15432 for (; !step.done; newIdx++, step = newChildren.next()) {
15433 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
15434
15435 if (_newFiber4 !== null) {
15436 if (shouldTrackSideEffects) {
15437 if (_newFiber4.alternate !== null) {
15438 // The new fiber is a work in progress, but if there exists a
15439 // current, that means that we reused the fiber. We need to delete
15440 // it from the child list so that we don't add it to the deletion
15441 // list.
15442 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
15443 }
15444 }
15445
15446 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
15447
15448 if (previousNewFiber === null) {
15449 resultingFirstChild = _newFiber4;
15450 } else {
15451 previousNewFiber.sibling = _newFiber4;
15452 }
15453
15454 previousNewFiber = _newFiber4;
15455 }
15456 }
15457
15458 if (shouldTrackSideEffects) {
15459 // Any existing children that weren't consumed above were deleted. We need
15460 // to add them to the deletion list.
15461 existingChildren.forEach(function (child) {
15462 return deleteChild(returnFiber, child);
15463 });
15464 }
15465
15466 return resultingFirstChild;
15467 }
15468
15469 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
15470 // There's no need to check for keys on text nodes since we don't have a
15471 // way to define them.
15472 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
15473 // We already have an existing node so let's just update it and delete
15474 // the rest.
15475 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
15476 var existing = useFiber(currentFirstChild, textContent, expirationTime);
15477 existing.return = returnFiber;
15478 return existing;
15479 } // The existing first child is not a text node so we need to create one
15480 // and delete the existing ones.
15481
15482
15483 deleteRemainingChildren(returnFiber, currentFirstChild);
15484 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15485 created.return = returnFiber;
15486 return created;
15487 }
15488
15489 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
15490 var key = element.key;
15491 var child = currentFirstChild;
15492
15493 while (child !== null) {
15494 // TODO: If key === null and child.key === null, then this only applies to
15495 // the first item in the list.
15496 if (child.key === key) {
15497 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:
15498 isCompatibleFamilyForHotReloading(child, element))) {
15499 deleteRemainingChildren(returnFiber, child.sibling);
15500 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
15501 existing.ref = coerceRef(returnFiber, child, element);
15502 existing.return = returnFiber;
15503
15504 {
15505 existing._debugSource = element._source;
15506 existing._debugOwner = element._owner;
15507 }
15508
15509 return existing;
15510 } else {
15511 deleteRemainingChildren(returnFiber, child);
15512 break;
15513 }
15514 } else {
15515 deleteChild(returnFiber, child);
15516 }
15517
15518 child = child.sibling;
15519 }
15520
15521 if (element.type === REACT_FRAGMENT_TYPE) {
15522 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
15523 created.return = returnFiber;
15524 return created;
15525 } else {
15526 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
15527
15528 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
15529 _created4.return = returnFiber;
15530 return _created4;
15531 }
15532 }
15533
15534 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
15535 var key = portal.key;
15536 var child = currentFirstChild;
15537
15538 while (child !== null) {
15539 // TODO: If key === null and child.key === null, then this only applies to
15540 // the first item in the list.
15541 if (child.key === key) {
15542 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
15543 deleteRemainingChildren(returnFiber, child.sibling);
15544 var existing = useFiber(child, portal.children || [], expirationTime);
15545 existing.return = returnFiber;
15546 return existing;
15547 } else {
15548 deleteRemainingChildren(returnFiber, child);
15549 break;
15550 }
15551 } else {
15552 deleteChild(returnFiber, child);
15553 }
15554
15555 child = child.sibling;
15556 }
15557
15558 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15559 created.return = returnFiber;
15560 return created;
15561 } // This API will tag the children with the side-effect of the reconciliation
15562 // itself. They will be added to the side-effect list as we pass through the
15563 // children and the parent.
15564
15565
15566 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
15567 // This function is not recursive.
15568 // If the top level item is an array, we treat it as a set of children,
15569 // not as a fragment. Nested arrays on the other hand will be treated as
15570 // fragment nodes. Recursion happens at the normal flow.
15571 // Handle top level unkeyed fragments as if they were arrays.
15572 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
15573 // We treat the ambiguous cases above the same.
15574 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
15575
15576 if (isUnkeyedTopLevelFragment) {
15577 newChild = newChild.props.children;
15578 } // Handle object types
15579
15580
15581 var isObject = typeof newChild === 'object' && newChild !== null;
15582
15583 if (isObject) {
15584 switch (newChild.$$typeof) {
15585 case REACT_ELEMENT_TYPE:
15586 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
15587
15588 case REACT_PORTAL_TYPE:
15589 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
15590 }
15591 }
15592
15593 if (typeof newChild === 'string' || typeof newChild === 'number') {
15594 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
15595 }
15596
15597 if (isArray(newChild)) {
15598 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
15599 }
15600
15601 if (getIteratorFn(newChild)) {
15602 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
15603 }
15604
15605 if (isObject) {
15606 throwOnInvalidObjectType(returnFiber, newChild);
15607 }
15608
15609 {
15610 if (typeof newChild === 'function') {
15611 warnOnFunctionType();
15612 }
15613 }
15614
15615 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
15616 // If the new child is undefined, and the return fiber is a composite
15617 // component, throw an error. If Fiber return types are disabled,
15618 // we already threw above.
15619 switch (returnFiber.tag) {
15620 case ClassComponent:
15621 {
15622 {
15623 var instance = returnFiber.stateNode;
15624
15625 if (instance.render._isMockFunction) {
15626 // We allow auto-mocks to proceed as if they're returning null.
15627 break;
15628 }
15629 }
15630 }
15631 // Intentionally fall through to the next case, which handles both
15632 // functions and classes
15633 // eslint-disable-next-lined no-fallthrough
15634
15635 case FunctionComponent:
15636 {
15637 var Component = returnFiber.type;
15638
15639 {
15640 {
15641 throw 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.");
15642 }
15643 }
15644 }
15645 }
15646 } // Remaining cases are all treated as empty.
15647
15648
15649 return deleteRemainingChildren(returnFiber, currentFirstChild);
15650 }
15651
15652 return reconcileChildFibers;
15653}
15654
15655var reconcileChildFibers = ChildReconciler(true);
15656var mountChildFibers = ChildReconciler(false);
15657function cloneChildFibers(current$$1, workInProgress) {
15658 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
15659 {
15660 throw Error("Resuming work not yet implemented.");
15661 }
15662 }
15663
15664 if (workInProgress.child === null) {
15665 return;
15666 }
15667
15668 var currentChild = workInProgress.child;
15669 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15670 workInProgress.child = newChild;
15671 newChild.return = workInProgress;
15672
15673 while (currentChild.sibling !== null) {
15674 currentChild = currentChild.sibling;
15675 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15676 newChild.return = workInProgress;
15677 }
15678
15679 newChild.sibling = null;
15680} // Reset a workInProgress child set to prepare it for a second pass.
15681
15682function resetChildFibers(workInProgress, renderExpirationTime) {
15683 var child = workInProgress.child;
15684
15685 while (child !== null) {
15686 resetWorkInProgress(child, renderExpirationTime);
15687 child = child.sibling;
15688 }
15689}
15690
15691var NO_CONTEXT = {};
15692var contextStackCursor$1 = createCursor(NO_CONTEXT);
15693var contextFiberStackCursor = createCursor(NO_CONTEXT);
15694var rootInstanceStackCursor = createCursor(NO_CONTEXT);
15695
15696function requiredContext(c) {
15697 if (!(c !== NO_CONTEXT)) {
15698 {
15699 throw Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
15700 }
15701 }
15702
15703 return c;
15704}
15705
15706function getRootHostContainer() {
15707 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15708 return rootInstance;
15709}
15710
15711function pushHostContainer(fiber, nextRootInstance) {
15712 // Push current root instance onto the stack;
15713 // This allows us to reset root when portals are popped.
15714 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
15715 // This enables us to pop only Fibers that provide unique contexts.
15716
15717 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
15718 // However, we can't just call getRootHostContext() and push it because
15719 // we'd have a different number of entries on the stack depending on
15720 // whether getRootHostContext() throws somewhere in renderer code or not.
15721 // So we push an empty value first. This lets us safely unwind on errors.
15722
15723 push(contextStackCursor$1, NO_CONTEXT, fiber);
15724 var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
15725
15726 pop(contextStackCursor$1, fiber);
15727 push(contextStackCursor$1, nextRootContext, fiber);
15728}
15729
15730function popHostContainer(fiber) {
15731 pop(contextStackCursor$1, fiber);
15732 pop(contextFiberStackCursor, fiber);
15733 pop(rootInstanceStackCursor, fiber);
15734}
15735
15736function getHostContext() {
15737 var context = requiredContext(contextStackCursor$1.current);
15738 return context;
15739}
15740
15741function pushHostContext(fiber) {
15742 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15743 var context = requiredContext(contextStackCursor$1.current);
15744 var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique.
15745
15746 if (context === nextContext) {
15747 return;
15748 } // Track the context and the Fiber that provided it.
15749 // This enables us to pop only Fibers that provide unique contexts.
15750
15751
15752 push(contextFiberStackCursor, fiber, fiber);
15753 push(contextStackCursor$1, nextContext, fiber);
15754}
15755
15756function popHostContext(fiber) {
15757 // Do not pop unless this Fiber provided the current context.
15758 // pushHostContext() only pushes Fibers that provide unique contexts.
15759 if (contextFiberStackCursor.current !== fiber) {
15760 return;
15761 }
15762
15763 pop(contextStackCursor$1, fiber);
15764 pop(contextFiberStackCursor, fiber);
15765}
15766
15767var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
15768// inherited deeply down the subtree. The upper bits only affect
15769// this immediate suspense boundary and gets reset each new
15770// boundary or suspense list.
15771
15772var SubtreeSuspenseContextMask = 1; // Subtree Flags:
15773// InvisibleParentSuspenseContext indicates that one of our parent Suspense
15774// boundaries is not currently showing visible main content.
15775// Either because it is already showing a fallback or is not mounted at all.
15776// We can use this to determine if it is desirable to trigger a fallback at
15777// the parent. If not, then we might need to trigger undesirable boundaries
15778// and/or suspend the commit to avoid hiding the parent content.
15779
15780var InvisibleParentSuspenseContext = 1; // Shallow Flags:
15781// ForceSuspenseFallback can be used by SuspenseList to force newly added
15782// items into their fallback state during one of the render passes.
15783
15784var ForceSuspenseFallback = 2;
15785var suspenseStackCursor = createCursor(DefaultSuspenseContext);
15786function hasSuspenseContext(parentContext, flag) {
15787 return (parentContext & flag) !== 0;
15788}
15789function setDefaultShallowSuspenseContext(parentContext) {
15790 return parentContext & SubtreeSuspenseContextMask;
15791}
15792function setShallowSuspenseContext(parentContext, shallowContext) {
15793 return parentContext & SubtreeSuspenseContextMask | shallowContext;
15794}
15795function addSubtreeSuspenseContext(parentContext, subtreeContext) {
15796 return parentContext | subtreeContext;
15797}
15798function pushSuspenseContext(fiber, newContext) {
15799 push(suspenseStackCursor, newContext, fiber);
15800}
15801function popSuspenseContext(fiber) {
15802 pop(suspenseStackCursor, fiber);
15803}
15804
15805function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
15806 // If it was the primary children that just suspended, capture and render the
15807 // fallback. Otherwise, don't capture and bubble to the next boundary.
15808 var nextState = workInProgress.memoizedState;
15809
15810 if (nextState !== null) {
15811 if (nextState.dehydrated !== null) {
15812 // A dehydrated boundary always captures.
15813 return true;
15814 }
15815
15816 return false;
15817 }
15818
15819 var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
15820
15821 if (props.fallback === undefined) {
15822 return false;
15823 } // Regular boundaries always capture.
15824
15825
15826 if (props.unstable_avoidThisFallback !== true) {
15827 return true;
15828 } // If it's a boundary we should avoid, then we prefer to bubble up to the
15829 // parent boundary if it is currently invisible.
15830
15831
15832 if (hasInvisibleParent) {
15833 return false;
15834 } // If the parent is not able to handle it, we must handle it.
15835
15836
15837 return true;
15838}
15839function findFirstSuspended(row) {
15840 var node = row;
15841
15842 while (node !== null) {
15843 if (node.tag === SuspenseComponent) {
15844 var state = node.memoizedState;
15845
15846 if (state !== null) {
15847 var dehydrated = state.dehydrated;
15848
15849 if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
15850 return node;
15851 }
15852 }
15853 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
15854 // keep track of whether it suspended or not.
15855 node.memoizedProps.revealOrder !== undefined) {
15856 var didSuspend = (node.effectTag & DidCapture) !== NoEffect;
15857
15858 if (didSuspend) {
15859 return node;
15860 }
15861 } else if (node.child !== null) {
15862 node.child.return = node;
15863 node = node.child;
15864 continue;
15865 }
15866
15867 if (node === row) {
15868 return null;
15869 }
15870
15871 while (node.sibling === null) {
15872 if (node.return === null || node.return === row) {
15873 return null;
15874 }
15875
15876 node = node.return;
15877 }
15878
15879 node.sibling.return = node.return;
15880 node = node.sibling;
15881 }
15882
15883 return null;
15884}
15885
15886var emptyObject = {};
15887var isArray$2 = Array.isArray;
15888function createResponderInstance(responder, responderProps, responderState, fiber) {
15889 return {
15890 fiber: fiber,
15891 props: responderProps,
15892 responder: responder,
15893 rootEventTypes: null,
15894 state: responderState
15895 };
15896}
15897
15898function mountEventResponder$1(responder, responderProps, fiber, respondersMap, rootContainerInstance) {
15899 var responderState = emptyObject;
15900 var getInitialState = responder.getInitialState;
15901
15902 if (getInitialState !== null) {
15903 responderState = getInitialState(responderProps);
15904 }
15905
15906 var responderInstance = createResponderInstance(responder, responderProps, responderState, fiber);
15907
15908 if (!rootContainerInstance) {
15909 var node = fiber;
15910
15911 while (node !== null) {
15912 var tag = node.tag;
15913
15914 if (tag === HostComponent) {
15915 rootContainerInstance = node.stateNode;
15916 break;
15917 } else if (tag === HostRoot) {
15918 rootContainerInstance = node.stateNode.containerInfo;
15919 break;
15920 }
15921
15922 node = node.return;
15923 }
15924 }
15925
15926 mountResponderInstance(responder, responderInstance, responderProps, responderState, rootContainerInstance);
15927 respondersMap.set(responder, responderInstance);
15928}
15929
15930function updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance) {
15931 var responder;
15932 var props;
15933
15934 if (listener) {
15935 responder = listener.responder;
15936 props = listener.props;
15937 }
15938
15939 if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) {
15940 {
15941 throw Error("An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder().");
15942 }
15943 }
15944
15945 var listenerProps = props;
15946
15947 if (visistedResponders.has(responder)) {
15948 // show warning
15949 {
15950 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);
15951 }
15952
15953 return;
15954 }
15955
15956 visistedResponders.add(responder);
15957 var responderInstance = respondersMap.get(responder);
15958
15959 if (responderInstance === undefined) {
15960 // Mount (happens in either complete or commit phase)
15961 mountEventResponder$1(responder, listenerProps, fiber, respondersMap, rootContainerInstance);
15962 } else {
15963 // Update (happens during commit phase only)
15964 responderInstance.props = listenerProps;
15965 responderInstance.fiber = fiber;
15966 }
15967}
15968
15969function updateEventListeners(listeners, fiber, rootContainerInstance) {
15970 var visistedResponders = new Set();
15971 var dependencies = fiber.dependencies;
15972
15973 if (listeners != null) {
15974 if (dependencies === null) {
15975 dependencies = fiber.dependencies = {
15976 expirationTime: NoWork,
15977 firstContext: null,
15978 responders: new Map()
15979 };
15980 }
15981
15982 var respondersMap = dependencies.responders;
15983
15984 if (respondersMap === null) {
15985 respondersMap = new Map();
15986 }
15987
15988 if (isArray$2(listeners)) {
15989 for (var i = 0, length = listeners.length; i < length; i++) {
15990 var listener = listeners[i];
15991 updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance);
15992 }
15993 } else {
15994 updateEventListener(listeners, fiber, visistedResponders, respondersMap, rootContainerInstance);
15995 }
15996 }
15997
15998 if (dependencies !== null) {
15999 var _respondersMap = dependencies.responders;
16000
16001 if (_respondersMap !== null) {
16002 // Unmount
16003 var mountedResponders = Array.from(_respondersMap.keys());
16004
16005 for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) {
16006 var mountedResponder = mountedResponders[_i];
16007
16008 if (!visistedResponders.has(mountedResponder)) {
16009 var responderInstance = _respondersMap.get(mountedResponder);
16010
16011 unmountResponderInstance(responderInstance);
16012
16013 _respondersMap.delete(mountedResponder);
16014 }
16015 }
16016 }
16017 }
16018}
16019function createResponderListener(responder, props) {
16020 var eventResponderListener = {
16021 responder: responder,
16022 props: props
16023 };
16024
16025 {
16026 Object.freeze(eventResponderListener);
16027 }
16028
16029 return eventResponderListener;
16030}
16031
16032var NoEffect$1 =
16033/* */
160340;
16035var UnmountSnapshot =
16036/* */
160372;
16038var UnmountMutation =
16039/* */
160404;
16041var MountMutation =
16042/* */
160438;
16044var UnmountLayout =
16045/* */
1604616;
16047var MountLayout =
16048/* */
1604932;
16050var MountPassive =
16051/* */
1605264;
16053var UnmountPassive =
16054/* */
16055128;
16056
16057var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
16058var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
16059var didWarnAboutMismatchedHooksForComponent;
16060
16061{
16062 didWarnAboutMismatchedHooksForComponent = new Set();
16063}
16064
16065// These are set right before calling the component.
16066var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
16067// the work-in-progress hook.
16068
16069var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
16070// current hook list is the list that belongs to the current fiber. The
16071// work-in-progress hook list is a new list that will be added to the
16072// work-in-progress fiber.
16073
16074var currentHook = null;
16075var nextCurrentHook = null;
16076var firstWorkInProgressHook = null;
16077var workInProgressHook = null;
16078var nextWorkInProgressHook = null;
16079var remainingExpirationTime = NoWork;
16080var componentUpdateQueue = null;
16081var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the
16082// end of the current pass. We can't store these updates on the normal queue,
16083// because if the work is aborted, they should be discarded. Because this is
16084// a relatively rare case, we also don't want to add an additional field to
16085// either the hook or queue object types. So we store them in a lazily create
16086// map of queue -> render-phase updates, which are discarded once the component
16087// completes without re-rendering.
16088// Whether an update was scheduled during the currently executing render pass.
16089
16090var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates
16091
16092var renderPhaseUpdates = null; // Counter to prevent infinite loops.
16093
16094var numberOfReRenders = 0;
16095var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
16096
16097var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
16098// The list stores the order of hooks used during the initial render (mount).
16099// Subsequent renders (updates) reference this list.
16100
16101var hookTypesDev = null;
16102var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
16103// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
16104// When true, such Hooks will always be "remounted". Only used during hot reload.
16105
16106var ignorePreviousDependencies = false;
16107
16108function mountHookTypesDev() {
16109 {
16110 var hookName = currentHookNameInDev;
16111
16112 if (hookTypesDev === null) {
16113 hookTypesDev = [hookName];
16114 } else {
16115 hookTypesDev.push(hookName);
16116 }
16117 }
16118}
16119
16120function updateHookTypesDev() {
16121 {
16122 var hookName = currentHookNameInDev;
16123
16124 if (hookTypesDev !== null) {
16125 hookTypesUpdateIndexDev++;
16126
16127 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
16128 warnOnHookMismatchInDev(hookName);
16129 }
16130 }
16131 }
16132}
16133
16134function checkDepsAreArrayDev(deps) {
16135 {
16136 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
16137 // Verify deps, but only on mount to avoid extra checks.
16138 // It's unlikely their type would change as usually you define them inline.
16139 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);
16140 }
16141 }
16142}
16143
16144function warnOnHookMismatchInDev(currentHookName) {
16145 {
16146 var componentName = getComponentName(currentlyRenderingFiber$1.type);
16147
16148 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
16149 didWarnAboutMismatchedHooksForComponent.add(componentName);
16150
16151 if (hookTypesDev !== null) {
16152 var table = '';
16153 var secondColumnStart = 30;
16154
16155 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
16156 var oldHookName = hookTypesDev[i];
16157 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
16158 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
16159 // lol @ IE not supporting String#repeat
16160
16161 while (row.length < secondColumnStart) {
16162 row += ' ';
16163 }
16164
16165 row += newHookName + '\n';
16166 table += row;
16167 }
16168
16169 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);
16170 }
16171 }
16172 }
16173}
16174
16175function throwInvalidHookError() {
16176 {
16177 {
16178 throw 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.");
16179 }
16180 }
16181}
16182
16183function areHookInputsEqual(nextDeps, prevDeps) {
16184 {
16185 if (ignorePreviousDependencies) {
16186 // Only true when this component is being hot reloaded.
16187 return false;
16188 }
16189 }
16190
16191 if (prevDeps === null) {
16192 {
16193 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);
16194 }
16195
16196 return false;
16197 }
16198
16199 {
16200 // Don't bother comparing lengths in prod because these arrays should be
16201 // passed inline.
16202 if (nextDeps.length !== prevDeps.length) {
16203 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(', ') + "]");
16204 }
16205 }
16206
16207 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
16208 if (is$1(nextDeps[i], prevDeps[i])) {
16209 continue;
16210 }
16211
16212 return false;
16213 }
16214
16215 return true;
16216}
16217
16218function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
16219 renderExpirationTime$1 = nextRenderExpirationTime;
16220 currentlyRenderingFiber$1 = workInProgress;
16221 nextCurrentHook = current !== null ? current.memoizedState : null;
16222
16223 {
16224 hookTypesDev = current !== null ? current._debugHookTypes : null;
16225 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
16226
16227 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
16228 } // The following should have already been reset
16229 // currentHook = null;
16230 // workInProgressHook = null;
16231 // remainingExpirationTime = NoWork;
16232 // componentUpdateQueue = null;
16233 // didScheduleRenderPhaseUpdate = false;
16234 // renderPhaseUpdates = null;
16235 // numberOfReRenders = 0;
16236 // sideEffectTag = 0;
16237 // TODO Warn if no hooks are used at all during mount, then some are used during update.
16238 // Currently we will identify the update render as a mount because nextCurrentHook === null.
16239 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
16240 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
16241 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
16242 // so nextCurrentHook would be null during updates and mounts.
16243
16244
16245 {
16246 if (nextCurrentHook !== null) {
16247 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16248 } else if (hookTypesDev !== null) {
16249 // This dispatcher handles an edge case where a component is updating,
16250 // but no stateful hooks have been used.
16251 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
16252 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
16253 // This dispatcher does that.
16254 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
16255 } else {
16256 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
16257 }
16258 }
16259
16260 var children = Component(props, refOrContext);
16261
16262 if (didScheduleRenderPhaseUpdate) {
16263 do {
16264 didScheduleRenderPhaseUpdate = false;
16265 numberOfReRenders += 1;
16266
16267 {
16268 // Even when hot reloading, allow dependencies to stabilize
16269 // after first render to prevent infinite render phase updates.
16270 ignorePreviousDependencies = false;
16271 } // Start over from the beginning of the list
16272
16273
16274 nextCurrentHook = current !== null ? current.memoizedState : null;
16275 nextWorkInProgressHook = firstWorkInProgressHook;
16276 currentHook = null;
16277 workInProgressHook = null;
16278 componentUpdateQueue = null;
16279
16280 {
16281 // Also validate hook order for cascading updates.
16282 hookTypesUpdateIndexDev = -1;
16283 }
16284
16285 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16286 children = Component(props, refOrContext);
16287 } while (didScheduleRenderPhaseUpdate);
16288
16289 renderPhaseUpdates = null;
16290 numberOfReRenders = 0;
16291 } // We can assume the previous dispatcher is always this one, since we set it
16292 // at the beginning of the render phase and there's no re-entrancy.
16293
16294
16295 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
16296 var renderedWork = currentlyRenderingFiber$1;
16297 renderedWork.memoizedState = firstWorkInProgressHook;
16298 renderedWork.expirationTime = remainingExpirationTime;
16299 renderedWork.updateQueue = componentUpdateQueue;
16300 renderedWork.effectTag |= sideEffectTag;
16301
16302 {
16303 renderedWork._debugHookTypes = hookTypesDev;
16304 } // This check uses currentHook so that it works the same in DEV and prod bundles.
16305 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
16306
16307
16308 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
16309 renderExpirationTime$1 = NoWork;
16310 currentlyRenderingFiber$1 = null;
16311 currentHook = null;
16312 nextCurrentHook = null;
16313 firstWorkInProgressHook = null;
16314 workInProgressHook = null;
16315 nextWorkInProgressHook = null;
16316
16317 {
16318 currentHookNameInDev = null;
16319 hookTypesDev = null;
16320 hookTypesUpdateIndexDev = -1;
16321 }
16322
16323 remainingExpirationTime = NoWork;
16324 componentUpdateQueue = null;
16325 sideEffectTag = 0; // These were reset above
16326 // didScheduleRenderPhaseUpdate = false;
16327 // renderPhaseUpdates = null;
16328 // numberOfReRenders = 0;
16329
16330 if (!!didRenderTooFewHooks) {
16331 {
16332 throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
16333 }
16334 }
16335
16336 return children;
16337}
16338function bailoutHooks(current, workInProgress, expirationTime) {
16339 workInProgress.updateQueue = current.updateQueue;
16340 workInProgress.effectTag &= ~(Passive | Update);
16341
16342 if (current.expirationTime <= expirationTime) {
16343 current.expirationTime = NoWork;
16344 }
16345}
16346function resetHooks() {
16347 // We can assume the previous dispatcher is always this one, since we set it
16348 // at the beginning of the render phase and there's no re-entrancy.
16349 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws.
16350 // It's also called inside mountIndeterminateComponent if we determine the
16351 // component is a module-style component.
16352
16353 renderExpirationTime$1 = NoWork;
16354 currentlyRenderingFiber$1 = null;
16355 currentHook = null;
16356 nextCurrentHook = null;
16357 firstWorkInProgressHook = null;
16358 workInProgressHook = null;
16359 nextWorkInProgressHook = null;
16360
16361 {
16362 hookTypesDev = null;
16363 hookTypesUpdateIndexDev = -1;
16364 currentHookNameInDev = null;
16365 }
16366
16367 remainingExpirationTime = NoWork;
16368 componentUpdateQueue = null;
16369 sideEffectTag = 0;
16370 didScheduleRenderPhaseUpdate = false;
16371 renderPhaseUpdates = null;
16372 numberOfReRenders = 0;
16373}
16374
16375function mountWorkInProgressHook() {
16376 var hook = {
16377 memoizedState: null,
16378 baseState: null,
16379 queue: null,
16380 baseUpdate: null,
16381 next: null
16382 };
16383
16384 if (workInProgressHook === null) {
16385 // This is the first hook in the list
16386 firstWorkInProgressHook = workInProgressHook = hook;
16387 } else {
16388 // Append to the end of the list
16389 workInProgressHook = workInProgressHook.next = hook;
16390 }
16391
16392 return workInProgressHook;
16393}
16394
16395function updateWorkInProgressHook() {
16396 // This function is used both for updates and for re-renders triggered by a
16397 // render phase update. It assumes there is either a current hook we can
16398 // clone, or a work-in-progress hook from a previous render pass that we can
16399 // use as a base. When we reach the end of the base list, we must switch to
16400 // the dispatcher used for mounts.
16401 if (nextWorkInProgressHook !== null) {
16402 // There's already a work-in-progress. Reuse it.
16403 workInProgressHook = nextWorkInProgressHook;
16404 nextWorkInProgressHook = workInProgressHook.next;
16405 currentHook = nextCurrentHook;
16406 nextCurrentHook = currentHook !== null ? currentHook.next : null;
16407 } else {
16408 // Clone from the current hook.
16409 if (!(nextCurrentHook !== null)) {
16410 {
16411 throw Error("Rendered more hooks than during the previous render.");
16412 }
16413 }
16414
16415 currentHook = nextCurrentHook;
16416 var newHook = {
16417 memoizedState: currentHook.memoizedState,
16418 baseState: currentHook.baseState,
16419 queue: currentHook.queue,
16420 baseUpdate: currentHook.baseUpdate,
16421 next: null
16422 };
16423
16424 if (workInProgressHook === null) {
16425 // This is the first hook in the list.
16426 workInProgressHook = firstWorkInProgressHook = newHook;
16427 } else {
16428 // Append to the end of the list.
16429 workInProgressHook = workInProgressHook.next = newHook;
16430 }
16431
16432 nextCurrentHook = currentHook.next;
16433 }
16434
16435 return workInProgressHook;
16436}
16437
16438function createFunctionComponentUpdateQueue() {
16439 return {
16440 lastEffect: null
16441 };
16442}
16443
16444function basicStateReducer(state, action) {
16445 return typeof action === 'function' ? action(state) : action;
16446}
16447
16448function mountReducer(reducer, initialArg, init) {
16449 var hook = mountWorkInProgressHook();
16450 var initialState;
16451
16452 if (init !== undefined) {
16453 initialState = init(initialArg);
16454 } else {
16455 initialState = initialArg;
16456 }
16457
16458 hook.memoizedState = hook.baseState = initialState;
16459 var queue = hook.queue = {
16460 last: null,
16461 dispatch: null,
16462 lastRenderedReducer: reducer,
16463 lastRenderedState: initialState
16464 };
16465 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16466 currentlyRenderingFiber$1, queue);
16467 return [hook.memoizedState, dispatch];
16468}
16469
16470function updateReducer(reducer, initialArg, init) {
16471 var hook = updateWorkInProgressHook();
16472 var queue = hook.queue;
16473
16474 if (!(queue !== null)) {
16475 {
16476 throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
16477 }
16478 }
16479
16480 queue.lastRenderedReducer = reducer;
16481
16482 if (numberOfReRenders > 0) {
16483 // This is a re-render. Apply the new render phase updates to the previous
16484 // work-in-progress hook.
16485 var _dispatch = queue.dispatch;
16486
16487 if (renderPhaseUpdates !== null) {
16488 // Render phase updates are stored in a map of queue -> linked list
16489 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16490
16491 if (firstRenderPhaseUpdate !== undefined) {
16492 renderPhaseUpdates.delete(queue);
16493 var newState = hook.memoizedState;
16494 var update = firstRenderPhaseUpdate;
16495
16496 do {
16497 // Process this render phase update. We don't have to check the
16498 // priority because it will always be the same as the current
16499 // render's.
16500 var action = update.action;
16501 newState = reducer(newState, action);
16502 update = update.next;
16503 } while (update !== null); // Mark that the fiber performed work, but only if the new state is
16504 // different from the current state.
16505
16506
16507 if (!is$1(newState, hook.memoizedState)) {
16508 markWorkInProgressReceivedUpdate();
16509 }
16510
16511 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
16512 // the base state unless the queue is empty.
16513 // TODO: Not sure if this is the desired semantics, but it's what we
16514 // do for gDSFP. I can't remember why.
16515
16516 if (hook.baseUpdate === queue.last) {
16517 hook.baseState = newState;
16518 }
16519
16520 queue.lastRenderedState = newState;
16521 return [newState, _dispatch];
16522 }
16523 }
16524
16525 return [hook.memoizedState, _dispatch];
16526 } // The last update in the entire queue
16527
16528
16529 var last = queue.last; // The last update that is part of the base state.
16530
16531 var baseUpdate = hook.baseUpdate;
16532 var baseState = hook.baseState; // Find the first unprocessed update.
16533
16534 var first;
16535
16536 if (baseUpdate !== null) {
16537 if (last !== null) {
16538 // For the first update, the queue is a circular linked list where
16539 // `queue.last.next = queue.first`. Once the first update commits, and
16540 // the `baseUpdate` is no longer empty, we can unravel the list.
16541 last.next = null;
16542 }
16543
16544 first = baseUpdate.next;
16545 } else {
16546 first = last !== null ? last.next : null;
16547 }
16548
16549 if (first !== null) {
16550 var _newState = baseState;
16551 var newBaseState = null;
16552 var newBaseUpdate = null;
16553 var prevUpdate = baseUpdate;
16554 var _update = first;
16555 var didSkip = false;
16556
16557 do {
16558 var updateExpirationTime = _update.expirationTime;
16559
16560 if (updateExpirationTime < renderExpirationTime$1) {
16561 // Priority is insufficient. Skip this update. If this is the first
16562 // skipped update, the previous update/state is the new base
16563 // update/state.
16564 if (!didSkip) {
16565 didSkip = true;
16566 newBaseUpdate = prevUpdate;
16567 newBaseState = _newState;
16568 } // Update the remaining priority in the queue.
16569
16570
16571 if (updateExpirationTime > remainingExpirationTime) {
16572 remainingExpirationTime = updateExpirationTime;
16573 markUnprocessedUpdateTime(remainingExpirationTime);
16574 }
16575 } else {
16576 // This update does have sufficient priority.
16577 // Mark the event time of this update as relevant to this render pass.
16578 // TODO: This should ideally use the true event time of this update rather than
16579 // its priority which is a derived and not reverseable value.
16580 // TODO: We should skip this update if it was already committed but currently
16581 // we have no way of detecting the difference between a committed and suspended
16582 // update here.
16583 markRenderEventTimeAndConfig(updateExpirationTime, _update.suspenseConfig); // Process this update.
16584
16585 if (_update.eagerReducer === reducer) {
16586 // If this update was processed eagerly, and its reducer matches the
16587 // current reducer, we can use the eagerly computed state.
16588 _newState = _update.eagerState;
16589 } else {
16590 var _action = _update.action;
16591 _newState = reducer(_newState, _action);
16592 }
16593 }
16594
16595 prevUpdate = _update;
16596 _update = _update.next;
16597 } while (_update !== null && _update !== first);
16598
16599 if (!didSkip) {
16600 newBaseUpdate = prevUpdate;
16601 newBaseState = _newState;
16602 } // Mark that the fiber performed work, but only if the new state is
16603 // different from the current state.
16604
16605
16606 if (!is$1(_newState, hook.memoizedState)) {
16607 markWorkInProgressReceivedUpdate();
16608 }
16609
16610 hook.memoizedState = _newState;
16611 hook.baseUpdate = newBaseUpdate;
16612 hook.baseState = newBaseState;
16613 queue.lastRenderedState = _newState;
16614 }
16615
16616 var dispatch = queue.dispatch;
16617 return [hook.memoizedState, dispatch];
16618}
16619
16620function mountState(initialState) {
16621 var hook = mountWorkInProgressHook();
16622
16623 if (typeof initialState === 'function') {
16624 initialState = initialState();
16625 }
16626
16627 hook.memoizedState = hook.baseState = initialState;
16628 var queue = hook.queue = {
16629 last: null,
16630 dispatch: null,
16631 lastRenderedReducer: basicStateReducer,
16632 lastRenderedState: initialState
16633 };
16634 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16635 currentlyRenderingFiber$1, queue);
16636 return [hook.memoizedState, dispatch];
16637}
16638
16639function updateState(initialState) {
16640 return updateReducer(basicStateReducer, initialState);
16641}
16642
16643function pushEffect(tag, create, destroy, deps) {
16644 var effect = {
16645 tag: tag,
16646 create: create,
16647 destroy: destroy,
16648 deps: deps,
16649 // Circular
16650 next: null
16651 };
16652
16653 if (componentUpdateQueue === null) {
16654 componentUpdateQueue = createFunctionComponentUpdateQueue();
16655 componentUpdateQueue.lastEffect = effect.next = effect;
16656 } else {
16657 var lastEffect = componentUpdateQueue.lastEffect;
16658
16659 if (lastEffect === null) {
16660 componentUpdateQueue.lastEffect = effect.next = effect;
16661 } else {
16662 var firstEffect = lastEffect.next;
16663 lastEffect.next = effect;
16664 effect.next = firstEffect;
16665 componentUpdateQueue.lastEffect = effect;
16666 }
16667 }
16668
16669 return effect;
16670}
16671
16672function mountRef(initialValue) {
16673 var hook = mountWorkInProgressHook();
16674 var ref = {
16675 current: initialValue
16676 };
16677
16678 {
16679 Object.seal(ref);
16680 }
16681
16682 hook.memoizedState = ref;
16683 return ref;
16684}
16685
16686function updateRef(initialValue) {
16687 var hook = updateWorkInProgressHook();
16688 return hook.memoizedState;
16689}
16690
16691function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16692 var hook = mountWorkInProgressHook();
16693 var nextDeps = deps === undefined ? null : deps;
16694 sideEffectTag |= fiberEffectTag;
16695 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
16696}
16697
16698function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16699 var hook = updateWorkInProgressHook();
16700 var nextDeps = deps === undefined ? null : deps;
16701 var destroy = undefined;
16702
16703 if (currentHook !== null) {
16704 var prevEffect = currentHook.memoizedState;
16705 destroy = prevEffect.destroy;
16706
16707 if (nextDeps !== null) {
16708 var prevDeps = prevEffect.deps;
16709
16710 if (areHookInputsEqual(nextDeps, prevDeps)) {
16711 pushEffect(NoEffect$1, create, destroy, nextDeps);
16712 return;
16713 }
16714 }
16715 }
16716
16717 sideEffectTag |= fiberEffectTag;
16718 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
16719}
16720
16721function mountEffect(create, deps) {
16722 {
16723 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16724 if ('undefined' !== typeof jest) {
16725 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16726 }
16727 }
16728
16729 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16730}
16731
16732function updateEffect(create, deps) {
16733 {
16734 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16735 if ('undefined' !== typeof jest) {
16736 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16737 }
16738 }
16739
16740 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16741}
16742
16743function mountLayoutEffect(create, deps) {
16744 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16745}
16746
16747function updateLayoutEffect(create, deps) {
16748 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16749}
16750
16751function imperativeHandleEffect(create, ref) {
16752 if (typeof ref === 'function') {
16753 var refCallback = ref;
16754
16755 var _inst = create();
16756
16757 refCallback(_inst);
16758 return function () {
16759 refCallback(null);
16760 };
16761 } else if (ref !== null && ref !== undefined) {
16762 var refObject = ref;
16763
16764 {
16765 !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;
16766 }
16767
16768 var _inst2 = create();
16769
16770 refObject.current = _inst2;
16771 return function () {
16772 refObject.current = null;
16773 };
16774 }
16775}
16776
16777function mountImperativeHandle(ref, create, deps) {
16778 {
16779 !(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;
16780 } // TODO: If deps are provided, should we skip comparing the ref itself?
16781
16782
16783 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16784 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16785}
16786
16787function updateImperativeHandle(ref, create, deps) {
16788 {
16789 !(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;
16790 } // TODO: If deps are provided, should we skip comparing the ref itself?
16791
16792
16793 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16794 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16795}
16796
16797function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
16798 // The react-debug-hooks package injects its own implementation
16799 // so that e.g. DevTools can display custom hook values.
16800}
16801
16802var updateDebugValue = mountDebugValue;
16803
16804function mountCallback(callback, deps) {
16805 var hook = mountWorkInProgressHook();
16806 var nextDeps = deps === undefined ? null : deps;
16807 hook.memoizedState = [callback, nextDeps];
16808 return callback;
16809}
16810
16811function updateCallback(callback, deps) {
16812 var hook = updateWorkInProgressHook();
16813 var nextDeps = deps === undefined ? null : deps;
16814 var prevState = hook.memoizedState;
16815
16816 if (prevState !== null) {
16817 if (nextDeps !== null) {
16818 var prevDeps = prevState[1];
16819
16820 if (areHookInputsEqual(nextDeps, prevDeps)) {
16821 return prevState[0];
16822 }
16823 }
16824 }
16825
16826 hook.memoizedState = [callback, nextDeps];
16827 return callback;
16828}
16829
16830function mountMemo(nextCreate, deps) {
16831 var hook = mountWorkInProgressHook();
16832 var nextDeps = deps === undefined ? null : deps;
16833 var nextValue = nextCreate();
16834 hook.memoizedState = [nextValue, nextDeps];
16835 return nextValue;
16836}
16837
16838function updateMemo(nextCreate, deps) {
16839 var hook = updateWorkInProgressHook();
16840 var nextDeps = deps === undefined ? null : deps;
16841 var prevState = hook.memoizedState;
16842
16843 if (prevState !== null) {
16844 // Assume these are defined. If they're not, areHookInputsEqual will warn.
16845 if (nextDeps !== null) {
16846 var prevDeps = prevState[1];
16847
16848 if (areHookInputsEqual(nextDeps, prevDeps)) {
16849 return prevState[0];
16850 }
16851 }
16852 }
16853
16854 var nextValue = nextCreate();
16855 hook.memoizedState = [nextValue, nextDeps];
16856 return nextValue;
16857}
16858
16859function mountDeferredValue(value, config) {
16860 var _mountState = mountState(value),
16861 prevValue = _mountState[0],
16862 setValue = _mountState[1];
16863
16864 mountEffect(function () {
16865 Scheduler.unstable_next(function () {
16866 var previousConfig = ReactCurrentBatchConfig$1.suspense;
16867 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
16868
16869 try {
16870 setValue(value);
16871 } finally {
16872 ReactCurrentBatchConfig$1.suspense = previousConfig;
16873 }
16874 });
16875 }, [value, config]);
16876 return prevValue;
16877}
16878
16879function updateDeferredValue(value, config) {
16880 var _updateState = updateState(value),
16881 prevValue = _updateState[0],
16882 setValue = _updateState[1];
16883
16884 updateEffect(function () {
16885 Scheduler.unstable_next(function () {
16886 var previousConfig = ReactCurrentBatchConfig$1.suspense;
16887 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
16888
16889 try {
16890 setValue(value);
16891 } finally {
16892 ReactCurrentBatchConfig$1.suspense = previousConfig;
16893 }
16894 });
16895 }, [value, config]);
16896 return prevValue;
16897}
16898
16899function mountTransition(config) {
16900 var _mountState2 = mountState(false),
16901 isPending = _mountState2[0],
16902 setPending = _mountState2[1];
16903
16904 var startTransition = mountCallback(function (callback) {
16905 setPending(true);
16906 Scheduler.unstable_next(function () {
16907 var previousConfig = ReactCurrentBatchConfig$1.suspense;
16908 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
16909
16910 try {
16911 setPending(false);
16912 callback();
16913 } finally {
16914 ReactCurrentBatchConfig$1.suspense = previousConfig;
16915 }
16916 });
16917 }, [config, isPending]);
16918 return [startTransition, isPending];
16919}
16920
16921function updateTransition(config) {
16922 var _updateState2 = updateState(false),
16923 isPending = _updateState2[0],
16924 setPending = _updateState2[1];
16925
16926 var startTransition = updateCallback(function (callback) {
16927 setPending(true);
16928 Scheduler.unstable_next(function () {
16929 var previousConfig = ReactCurrentBatchConfig$1.suspense;
16930 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
16931
16932 try {
16933 setPending(false);
16934 callback();
16935 } finally {
16936 ReactCurrentBatchConfig$1.suspense = previousConfig;
16937 }
16938 });
16939 }, [config, isPending]);
16940 return [startTransition, isPending];
16941}
16942
16943function dispatchAction(fiber, queue, action) {
16944 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
16945 {
16946 throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
16947 }
16948 }
16949
16950 {
16951 !(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;
16952 }
16953
16954 var alternate = fiber.alternate;
16955
16956 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
16957 // This is a render phase update. Stash it in a lazily-created map of
16958 // queue -> linked list of updates. After this render pass, we'll restart
16959 // and apply the stashed updates on top of the work-in-progress hook.
16960 didScheduleRenderPhaseUpdate = true;
16961 var update = {
16962 expirationTime: renderExpirationTime$1,
16963 suspenseConfig: null,
16964 action: action,
16965 eagerReducer: null,
16966 eagerState: null,
16967 next: null
16968 };
16969
16970 {
16971 update.priority = getCurrentPriorityLevel();
16972 }
16973
16974 if (renderPhaseUpdates === null) {
16975 renderPhaseUpdates = new Map();
16976 }
16977
16978 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16979
16980 if (firstRenderPhaseUpdate === undefined) {
16981 renderPhaseUpdates.set(queue, update);
16982 } else {
16983 // Append the update to the end of the list.
16984 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
16985
16986 while (lastRenderPhaseUpdate.next !== null) {
16987 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
16988 }
16989
16990 lastRenderPhaseUpdate.next = update;
16991 }
16992 } else {
16993 var currentTime = requestCurrentTimeForUpdate();
16994 var suspenseConfig = requestCurrentSuspenseConfig();
16995 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
16996 var _update2 = {
16997 expirationTime: expirationTime,
16998 suspenseConfig: suspenseConfig,
16999 action: action,
17000 eagerReducer: null,
17001 eagerState: null,
17002 next: null
17003 };
17004
17005 {
17006 _update2.priority = getCurrentPriorityLevel();
17007 } // Append the update to the end of the list.
17008
17009
17010 var last = queue.last;
17011
17012 if (last === null) {
17013 // This is the first update. Create a circular list.
17014 _update2.next = _update2;
17015 } else {
17016 var first = last.next;
17017
17018 if (first !== null) {
17019 // Still circular.
17020 _update2.next = first;
17021 }
17022
17023 last.next = _update2;
17024 }
17025
17026 queue.last = _update2;
17027
17028 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
17029 // The queue is currently empty, which means we can eagerly compute the
17030 // next state before entering the render phase. If the new state is the
17031 // same as the current state, we may be able to bail out entirely.
17032 var lastRenderedReducer = queue.lastRenderedReducer;
17033
17034 if (lastRenderedReducer !== null) {
17035 var prevDispatcher;
17036
17037 {
17038 prevDispatcher = ReactCurrentDispatcher$1.current;
17039 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17040 }
17041
17042 try {
17043 var currentState = queue.lastRenderedState;
17044 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
17045 // it, on the update object. If the reducer hasn't changed by the
17046 // time we enter the render phase, then the eager state can be used
17047 // without calling the reducer again.
17048
17049 _update2.eagerReducer = lastRenderedReducer;
17050 _update2.eagerState = eagerState;
17051
17052 if (is$1(eagerState, currentState)) {
17053 // Fast path. We can bail out without scheduling React to re-render.
17054 // It's still possible that we'll need to rebase this update later,
17055 // if the component re-renders for a different reason and by that
17056 // time the reducer has changed.
17057 return;
17058 }
17059 } catch (error) {// Suppress the error. It will throw again in the render phase.
17060 } finally {
17061 {
17062 ReactCurrentDispatcher$1.current = prevDispatcher;
17063 }
17064 }
17065 }
17066 }
17067
17068 {
17069 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
17070 if ('undefined' !== typeof jest) {
17071 warnIfNotScopedWithMatchingAct(fiber);
17072 warnIfNotCurrentlyActingUpdatesInDev(fiber);
17073 }
17074 }
17075
17076 scheduleWork(fiber, expirationTime);
17077 }
17078}
17079
17080var ContextOnlyDispatcher = {
17081 readContext: readContext,
17082 useCallback: throwInvalidHookError,
17083 useContext: throwInvalidHookError,
17084 useEffect: throwInvalidHookError,
17085 useImperativeHandle: throwInvalidHookError,
17086 useLayoutEffect: throwInvalidHookError,
17087 useMemo: throwInvalidHookError,
17088 useReducer: throwInvalidHookError,
17089 useRef: throwInvalidHookError,
17090 useState: throwInvalidHookError,
17091 useDebugValue: throwInvalidHookError,
17092 useResponder: throwInvalidHookError,
17093 useDeferredValue: throwInvalidHookError,
17094 useTransition: throwInvalidHookError
17095};
17096var HooksDispatcherOnMountInDEV = null;
17097var HooksDispatcherOnMountWithHookTypesInDEV = null;
17098var HooksDispatcherOnUpdateInDEV = null;
17099var InvalidNestedHooksDispatcherOnMountInDEV = null;
17100var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
17101
17102{
17103 var warnInvalidContextAccess = function () {
17104 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().');
17105 };
17106
17107 var warnInvalidHookAccess = function () {
17108 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');
17109 };
17110
17111 HooksDispatcherOnMountInDEV = {
17112 readContext: function (context, observedBits) {
17113 return readContext(context, observedBits);
17114 },
17115 useCallback: function (callback, deps) {
17116 currentHookNameInDev = 'useCallback';
17117 mountHookTypesDev();
17118 checkDepsAreArrayDev(deps);
17119 return mountCallback(callback, deps);
17120 },
17121 useContext: function (context, observedBits) {
17122 currentHookNameInDev = 'useContext';
17123 mountHookTypesDev();
17124 return readContext(context, observedBits);
17125 },
17126 useEffect: function (create, deps) {
17127 currentHookNameInDev = 'useEffect';
17128 mountHookTypesDev();
17129 checkDepsAreArrayDev(deps);
17130 return mountEffect(create, deps);
17131 },
17132 useImperativeHandle: function (ref, create, deps) {
17133 currentHookNameInDev = 'useImperativeHandle';
17134 mountHookTypesDev();
17135 checkDepsAreArrayDev(deps);
17136 return mountImperativeHandle(ref, create, deps);
17137 },
17138 useLayoutEffect: function (create, deps) {
17139 currentHookNameInDev = 'useLayoutEffect';
17140 mountHookTypesDev();
17141 checkDepsAreArrayDev(deps);
17142 return mountLayoutEffect(create, deps);
17143 },
17144 useMemo: function (create, deps) {
17145 currentHookNameInDev = 'useMemo';
17146 mountHookTypesDev();
17147 checkDepsAreArrayDev(deps);
17148 var prevDispatcher = ReactCurrentDispatcher$1.current;
17149 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17150
17151 try {
17152 return mountMemo(create, deps);
17153 } finally {
17154 ReactCurrentDispatcher$1.current = prevDispatcher;
17155 }
17156 },
17157 useReducer: function (reducer, initialArg, init) {
17158 currentHookNameInDev = 'useReducer';
17159 mountHookTypesDev();
17160 var prevDispatcher = ReactCurrentDispatcher$1.current;
17161 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17162
17163 try {
17164 return mountReducer(reducer, initialArg, init);
17165 } finally {
17166 ReactCurrentDispatcher$1.current = prevDispatcher;
17167 }
17168 },
17169 useRef: function (initialValue) {
17170 currentHookNameInDev = 'useRef';
17171 mountHookTypesDev();
17172 return mountRef(initialValue);
17173 },
17174 useState: function (initialState) {
17175 currentHookNameInDev = 'useState';
17176 mountHookTypesDev();
17177 var prevDispatcher = ReactCurrentDispatcher$1.current;
17178 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17179
17180 try {
17181 return mountState(initialState);
17182 } finally {
17183 ReactCurrentDispatcher$1.current = prevDispatcher;
17184 }
17185 },
17186 useDebugValue: function (value, formatterFn) {
17187 currentHookNameInDev = 'useDebugValue';
17188 mountHookTypesDev();
17189 return mountDebugValue(value, formatterFn);
17190 },
17191 useResponder: function (responder, props) {
17192 currentHookNameInDev = 'useResponder';
17193 mountHookTypesDev();
17194 return createResponderListener(responder, props);
17195 },
17196 useDeferredValue: function (value, config) {
17197 currentHookNameInDev = 'useDeferredValue';
17198 mountHookTypesDev();
17199 return mountDeferredValue(value, config);
17200 },
17201 useTransition: function (config) {
17202 currentHookNameInDev = 'useTransition';
17203 mountHookTypesDev();
17204 return mountTransition(config);
17205 }
17206 };
17207 HooksDispatcherOnMountWithHookTypesInDEV = {
17208 readContext: function (context, observedBits) {
17209 return readContext(context, observedBits);
17210 },
17211 useCallback: function (callback, deps) {
17212 currentHookNameInDev = 'useCallback';
17213 updateHookTypesDev();
17214 return mountCallback(callback, deps);
17215 },
17216 useContext: function (context, observedBits) {
17217 currentHookNameInDev = 'useContext';
17218 updateHookTypesDev();
17219 return readContext(context, observedBits);
17220 },
17221 useEffect: function (create, deps) {
17222 currentHookNameInDev = 'useEffect';
17223 updateHookTypesDev();
17224 return mountEffect(create, deps);
17225 },
17226 useImperativeHandle: function (ref, create, deps) {
17227 currentHookNameInDev = 'useImperativeHandle';
17228 updateHookTypesDev();
17229 return mountImperativeHandle(ref, create, deps);
17230 },
17231 useLayoutEffect: function (create, deps) {
17232 currentHookNameInDev = 'useLayoutEffect';
17233 updateHookTypesDev();
17234 return mountLayoutEffect(create, deps);
17235 },
17236 useMemo: function (create, deps) {
17237 currentHookNameInDev = 'useMemo';
17238 updateHookTypesDev();
17239 var prevDispatcher = ReactCurrentDispatcher$1.current;
17240 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17241
17242 try {
17243 return mountMemo(create, deps);
17244 } finally {
17245 ReactCurrentDispatcher$1.current = prevDispatcher;
17246 }
17247 },
17248 useReducer: function (reducer, initialArg, init) {
17249 currentHookNameInDev = 'useReducer';
17250 updateHookTypesDev();
17251 var prevDispatcher = ReactCurrentDispatcher$1.current;
17252 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17253
17254 try {
17255 return mountReducer(reducer, initialArg, init);
17256 } finally {
17257 ReactCurrentDispatcher$1.current = prevDispatcher;
17258 }
17259 },
17260 useRef: function (initialValue) {
17261 currentHookNameInDev = 'useRef';
17262 updateHookTypesDev();
17263 return mountRef(initialValue);
17264 },
17265 useState: function (initialState) {
17266 currentHookNameInDev = 'useState';
17267 updateHookTypesDev();
17268 var prevDispatcher = ReactCurrentDispatcher$1.current;
17269 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17270
17271 try {
17272 return mountState(initialState);
17273 } finally {
17274 ReactCurrentDispatcher$1.current = prevDispatcher;
17275 }
17276 },
17277 useDebugValue: function (value, formatterFn) {
17278 currentHookNameInDev = 'useDebugValue';
17279 updateHookTypesDev();
17280 return mountDebugValue(value, formatterFn);
17281 },
17282 useResponder: function (responder, props) {
17283 currentHookNameInDev = 'useResponder';
17284 updateHookTypesDev();
17285 return createResponderListener(responder, props);
17286 },
17287 useDeferredValue: function (value, config) {
17288 currentHookNameInDev = 'useDeferredValue';
17289 updateHookTypesDev();
17290 return mountDeferredValue(value, config);
17291 },
17292 useTransition: function (config) {
17293 currentHookNameInDev = 'useTransition';
17294 updateHookTypesDev();
17295 return mountTransition(config);
17296 }
17297 };
17298 HooksDispatcherOnUpdateInDEV = {
17299 readContext: function (context, observedBits) {
17300 return readContext(context, observedBits);
17301 },
17302 useCallback: function (callback, deps) {
17303 currentHookNameInDev = 'useCallback';
17304 updateHookTypesDev();
17305 return updateCallback(callback, deps);
17306 },
17307 useContext: function (context, observedBits) {
17308 currentHookNameInDev = 'useContext';
17309 updateHookTypesDev();
17310 return readContext(context, observedBits);
17311 },
17312 useEffect: function (create, deps) {
17313 currentHookNameInDev = 'useEffect';
17314 updateHookTypesDev();
17315 return updateEffect(create, deps);
17316 },
17317 useImperativeHandle: function (ref, create, deps) {
17318 currentHookNameInDev = 'useImperativeHandle';
17319 updateHookTypesDev();
17320 return updateImperativeHandle(ref, create, deps);
17321 },
17322 useLayoutEffect: function (create, deps) {
17323 currentHookNameInDev = 'useLayoutEffect';
17324 updateHookTypesDev();
17325 return updateLayoutEffect(create, deps);
17326 },
17327 useMemo: function (create, deps) {
17328 currentHookNameInDev = 'useMemo';
17329 updateHookTypesDev();
17330 var prevDispatcher = ReactCurrentDispatcher$1.current;
17331 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17332
17333 try {
17334 return updateMemo(create, deps);
17335 } finally {
17336 ReactCurrentDispatcher$1.current = prevDispatcher;
17337 }
17338 },
17339 useReducer: function (reducer, initialArg, init) {
17340 currentHookNameInDev = 'useReducer';
17341 updateHookTypesDev();
17342 var prevDispatcher = ReactCurrentDispatcher$1.current;
17343 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17344
17345 try {
17346 return updateReducer(reducer, initialArg, init);
17347 } finally {
17348 ReactCurrentDispatcher$1.current = prevDispatcher;
17349 }
17350 },
17351 useRef: function (initialValue) {
17352 currentHookNameInDev = 'useRef';
17353 updateHookTypesDev();
17354 return updateRef(initialValue);
17355 },
17356 useState: function (initialState) {
17357 currentHookNameInDev = 'useState';
17358 updateHookTypesDev();
17359 var prevDispatcher = ReactCurrentDispatcher$1.current;
17360 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17361
17362 try {
17363 return updateState(initialState);
17364 } finally {
17365 ReactCurrentDispatcher$1.current = prevDispatcher;
17366 }
17367 },
17368 useDebugValue: function (value, formatterFn) {
17369 currentHookNameInDev = 'useDebugValue';
17370 updateHookTypesDev();
17371 return updateDebugValue(value, formatterFn);
17372 },
17373 useResponder: function (responder, props) {
17374 currentHookNameInDev = 'useResponder';
17375 updateHookTypesDev();
17376 return createResponderListener(responder, props);
17377 },
17378 useDeferredValue: function (value, config) {
17379 currentHookNameInDev = 'useDeferredValue';
17380 updateHookTypesDev();
17381 return updateDeferredValue(value, config);
17382 },
17383 useTransition: function (config) {
17384 currentHookNameInDev = 'useTransition';
17385 updateHookTypesDev();
17386 return updateTransition(config);
17387 }
17388 };
17389 InvalidNestedHooksDispatcherOnMountInDEV = {
17390 readContext: function (context, observedBits) {
17391 warnInvalidContextAccess();
17392 return readContext(context, observedBits);
17393 },
17394 useCallback: function (callback, deps) {
17395 currentHookNameInDev = 'useCallback';
17396 warnInvalidHookAccess();
17397 mountHookTypesDev();
17398 return mountCallback(callback, deps);
17399 },
17400 useContext: function (context, observedBits) {
17401 currentHookNameInDev = 'useContext';
17402 warnInvalidHookAccess();
17403 mountHookTypesDev();
17404 return readContext(context, observedBits);
17405 },
17406 useEffect: function (create, deps) {
17407 currentHookNameInDev = 'useEffect';
17408 warnInvalidHookAccess();
17409 mountHookTypesDev();
17410 return mountEffect(create, deps);
17411 },
17412 useImperativeHandle: function (ref, create, deps) {
17413 currentHookNameInDev = 'useImperativeHandle';
17414 warnInvalidHookAccess();
17415 mountHookTypesDev();
17416 return mountImperativeHandle(ref, create, deps);
17417 },
17418 useLayoutEffect: function (create, deps) {
17419 currentHookNameInDev = 'useLayoutEffect';
17420 warnInvalidHookAccess();
17421 mountHookTypesDev();
17422 return mountLayoutEffect(create, deps);
17423 },
17424 useMemo: function (create, deps) {
17425 currentHookNameInDev = 'useMemo';
17426 warnInvalidHookAccess();
17427 mountHookTypesDev();
17428 var prevDispatcher = ReactCurrentDispatcher$1.current;
17429 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17430
17431 try {
17432 return mountMemo(create, deps);
17433 } finally {
17434 ReactCurrentDispatcher$1.current = prevDispatcher;
17435 }
17436 },
17437 useReducer: function (reducer, initialArg, init) {
17438 currentHookNameInDev = 'useReducer';
17439 warnInvalidHookAccess();
17440 mountHookTypesDev();
17441 var prevDispatcher = ReactCurrentDispatcher$1.current;
17442 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17443
17444 try {
17445 return mountReducer(reducer, initialArg, init);
17446 } finally {
17447 ReactCurrentDispatcher$1.current = prevDispatcher;
17448 }
17449 },
17450 useRef: function (initialValue) {
17451 currentHookNameInDev = 'useRef';
17452 warnInvalidHookAccess();
17453 mountHookTypesDev();
17454 return mountRef(initialValue);
17455 },
17456 useState: function (initialState) {
17457 currentHookNameInDev = 'useState';
17458 warnInvalidHookAccess();
17459 mountHookTypesDev();
17460 var prevDispatcher = ReactCurrentDispatcher$1.current;
17461 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17462
17463 try {
17464 return mountState(initialState);
17465 } finally {
17466 ReactCurrentDispatcher$1.current = prevDispatcher;
17467 }
17468 },
17469 useDebugValue: function (value, formatterFn) {
17470 currentHookNameInDev = 'useDebugValue';
17471 warnInvalidHookAccess();
17472 mountHookTypesDev();
17473 return mountDebugValue(value, formatterFn);
17474 },
17475 useResponder: function (responder, props) {
17476 currentHookNameInDev = 'useResponder';
17477 warnInvalidHookAccess();
17478 mountHookTypesDev();
17479 return createResponderListener(responder, props);
17480 },
17481 useDeferredValue: function (value, config) {
17482 currentHookNameInDev = 'useDeferredValue';
17483 warnInvalidHookAccess();
17484 mountHookTypesDev();
17485 return mountDeferredValue(value, config);
17486 },
17487 useTransition: function (config) {
17488 currentHookNameInDev = 'useTransition';
17489 warnInvalidHookAccess();
17490 mountHookTypesDev();
17491 return mountTransition(config);
17492 }
17493 };
17494 InvalidNestedHooksDispatcherOnUpdateInDEV = {
17495 readContext: function (context, observedBits) {
17496 warnInvalidContextAccess();
17497 return readContext(context, observedBits);
17498 },
17499 useCallback: function (callback, deps) {
17500 currentHookNameInDev = 'useCallback';
17501 warnInvalidHookAccess();
17502 updateHookTypesDev();
17503 return updateCallback(callback, deps);
17504 },
17505 useContext: function (context, observedBits) {
17506 currentHookNameInDev = 'useContext';
17507 warnInvalidHookAccess();
17508 updateHookTypesDev();
17509 return readContext(context, observedBits);
17510 },
17511 useEffect: function (create, deps) {
17512 currentHookNameInDev = 'useEffect';
17513 warnInvalidHookAccess();
17514 updateHookTypesDev();
17515 return updateEffect(create, deps);
17516 },
17517 useImperativeHandle: function (ref, create, deps) {
17518 currentHookNameInDev = 'useImperativeHandle';
17519 warnInvalidHookAccess();
17520 updateHookTypesDev();
17521 return updateImperativeHandle(ref, create, deps);
17522 },
17523 useLayoutEffect: function (create, deps) {
17524 currentHookNameInDev = 'useLayoutEffect';
17525 warnInvalidHookAccess();
17526 updateHookTypesDev();
17527 return updateLayoutEffect(create, deps);
17528 },
17529 useMemo: function (create, deps) {
17530 currentHookNameInDev = 'useMemo';
17531 warnInvalidHookAccess();
17532 updateHookTypesDev();
17533 var prevDispatcher = ReactCurrentDispatcher$1.current;
17534 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17535
17536 try {
17537 return updateMemo(create, deps);
17538 } finally {
17539 ReactCurrentDispatcher$1.current = prevDispatcher;
17540 }
17541 },
17542 useReducer: function (reducer, initialArg, init) {
17543 currentHookNameInDev = 'useReducer';
17544 warnInvalidHookAccess();
17545 updateHookTypesDev();
17546 var prevDispatcher = ReactCurrentDispatcher$1.current;
17547 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17548
17549 try {
17550 return updateReducer(reducer, initialArg, init);
17551 } finally {
17552 ReactCurrentDispatcher$1.current = prevDispatcher;
17553 }
17554 },
17555 useRef: function (initialValue) {
17556 currentHookNameInDev = 'useRef';
17557 warnInvalidHookAccess();
17558 updateHookTypesDev();
17559 return updateRef(initialValue);
17560 },
17561 useState: function (initialState) {
17562 currentHookNameInDev = 'useState';
17563 warnInvalidHookAccess();
17564 updateHookTypesDev();
17565 var prevDispatcher = ReactCurrentDispatcher$1.current;
17566 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17567
17568 try {
17569 return updateState(initialState);
17570 } finally {
17571 ReactCurrentDispatcher$1.current = prevDispatcher;
17572 }
17573 },
17574 useDebugValue: function (value, formatterFn) {
17575 currentHookNameInDev = 'useDebugValue';
17576 warnInvalidHookAccess();
17577 updateHookTypesDev();
17578 return updateDebugValue(value, formatterFn);
17579 },
17580 useResponder: function (responder, props) {
17581 currentHookNameInDev = 'useResponder';
17582 warnInvalidHookAccess();
17583 updateHookTypesDev();
17584 return createResponderListener(responder, props);
17585 },
17586 useDeferredValue: function (value, config) {
17587 currentHookNameInDev = 'useDeferredValue';
17588 warnInvalidHookAccess();
17589 updateHookTypesDev();
17590 return updateDeferredValue(value, config);
17591 },
17592 useTransition: function (config) {
17593 currentHookNameInDev = 'useTransition';
17594 warnInvalidHookAccess();
17595 updateHookTypesDev();
17596 return updateTransition(config);
17597 }
17598 };
17599}
17600
17601// CommonJS interop named imports.
17602
17603var now$1 = Scheduler.unstable_now;
17604var commitTime = 0;
17605var profilerStartTime = -1;
17606
17607function getCommitTime() {
17608 return commitTime;
17609}
17610
17611function recordCommitTime() {
17612 if (!enableProfilerTimer) {
17613 return;
17614 }
17615
17616 commitTime = now$1();
17617}
17618
17619function startProfilerTimer(fiber) {
17620 if (!enableProfilerTimer) {
17621 return;
17622 }
17623
17624 profilerStartTime = now$1();
17625
17626 if (fiber.actualStartTime < 0) {
17627 fiber.actualStartTime = now$1();
17628 }
17629}
17630
17631function stopProfilerTimerIfRunning(fiber) {
17632 if (!enableProfilerTimer) {
17633 return;
17634 }
17635
17636 profilerStartTime = -1;
17637}
17638
17639function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
17640 if (!enableProfilerTimer) {
17641 return;
17642 }
17643
17644 if (profilerStartTime >= 0) {
17645 var elapsedTime = now$1() - profilerStartTime;
17646 fiber.actualDuration += elapsedTime;
17647
17648 if (overrideBaseTime) {
17649 fiber.selfBaseDuration = elapsedTime;
17650 }
17651
17652 profilerStartTime = -1;
17653 }
17654}
17655
17656// This may have been an insertion or a hydration.
17657
17658var hydrationParentFiber = null;
17659var nextHydratableInstance = null;
17660var isHydrating = false;
17661
17662function warnIfHydrating() {
17663 {
17664 !!isHydrating ? warning$1(false, 'We should not be hydrating here. This is a bug in React. Please file a bug.') : void 0;
17665 }
17666}
17667
17668function enterHydrationState(fiber) {
17669 if (!supportsHydration) {
17670 return false;
17671 }
17672
17673 var parentInstance = fiber.stateNode.containerInfo;
17674 nextHydratableInstance = getFirstHydratableChild(parentInstance);
17675 hydrationParentFiber = fiber;
17676 isHydrating = true;
17677 return true;
17678}
17679
17680function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance) {
17681 if (!supportsHydration) {
17682 return false;
17683 }
17684
17685 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
17686 popToNextHostParent(fiber);
17687 isHydrating = true;
17688 return true;
17689}
17690
17691function deleteHydratableInstance(returnFiber, instance) {
17692 {
17693 switch (returnFiber.tag) {
17694 case HostRoot:
17695 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
17696 break;
17697
17698 case HostComponent:
17699 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
17700 break;
17701 }
17702 }
17703
17704 var childToDelete = createFiberFromHostInstanceForDeletion();
17705 childToDelete.stateNode = instance;
17706 childToDelete.return = returnFiber;
17707 childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
17708 // these children are not part of the reconciliation list of children.
17709 // Even if we abort and rereconcile the children, that will try to hydrate
17710 // again and the nodes are still in the host tree so these will be
17711 // recreated.
17712
17713 if (returnFiber.lastEffect !== null) {
17714 returnFiber.lastEffect.nextEffect = childToDelete;
17715 returnFiber.lastEffect = childToDelete;
17716 } else {
17717 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
17718 }
17719}
17720
17721function insertNonHydratedInstance(returnFiber, fiber) {
17722 fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
17723
17724 {
17725 switch (returnFiber.tag) {
17726 case HostRoot:
17727 {
17728 var parentContainer = returnFiber.stateNode.containerInfo;
17729
17730 switch (fiber.tag) {
17731 case HostComponent:
17732 var type = fiber.type;
17733 var props = fiber.pendingProps;
17734 didNotFindHydratableContainerInstance(parentContainer, type, props);
17735 break;
17736
17737 case HostText:
17738 var text = fiber.pendingProps;
17739 didNotFindHydratableContainerTextInstance(parentContainer, text);
17740 break;
17741
17742 case SuspenseComponent:
17743
17744 break;
17745 }
17746
17747 break;
17748 }
17749
17750 case HostComponent:
17751 {
17752 var parentType = returnFiber.type;
17753 var parentProps = returnFiber.memoizedProps;
17754 var parentInstance = returnFiber.stateNode;
17755
17756 switch (fiber.tag) {
17757 case HostComponent:
17758 var _type = fiber.type;
17759 var _props = fiber.pendingProps;
17760 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
17761 break;
17762
17763 case HostText:
17764 var _text = fiber.pendingProps;
17765 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
17766 break;
17767
17768 case SuspenseComponent:
17769 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
17770 break;
17771 }
17772
17773 break;
17774 }
17775
17776 default:
17777 return;
17778 }
17779 }
17780}
17781
17782function tryHydrate(fiber, nextInstance) {
17783 switch (fiber.tag) {
17784 case HostComponent:
17785 {
17786 var type = fiber.type;
17787 var props = fiber.pendingProps;
17788 var instance = canHydrateInstance(nextInstance, type, props);
17789
17790 if (instance !== null) {
17791 fiber.stateNode = instance;
17792 return true;
17793 }
17794
17795 return false;
17796 }
17797
17798 case HostText:
17799 {
17800 var text = fiber.pendingProps;
17801 var textInstance = canHydrateTextInstance(nextInstance, text);
17802
17803 if (textInstance !== null) {
17804 fiber.stateNode = textInstance;
17805 return true;
17806 }
17807
17808 return false;
17809 }
17810
17811 case SuspenseComponent:
17812 {
17813 if (enableSuspenseServerRenderer) {
17814 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
17815
17816 if (suspenseInstance !== null) {
17817 var suspenseState = {
17818 dehydrated: suspenseInstance,
17819 retryTime: Never
17820 };
17821 fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
17822 // This simplifies the code for getHostSibling and deleting nodes,
17823 // since it doesn't have to consider all Suspense boundaries and
17824 // check if they're dehydrated ones or not.
17825
17826 var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
17827 dehydratedFragment.return = fiber;
17828 fiber.child = dehydratedFragment;
17829 return true;
17830 }
17831 }
17832
17833 return false;
17834 }
17835
17836 default:
17837 return false;
17838 }
17839}
17840
17841function tryToClaimNextHydratableInstance(fiber) {
17842 if (!isHydrating) {
17843 return;
17844 }
17845
17846 var nextInstance = nextHydratableInstance;
17847
17848 if (!nextInstance) {
17849 // Nothing to hydrate. Make it an insertion.
17850 insertNonHydratedInstance(hydrationParentFiber, fiber);
17851 isHydrating = false;
17852 hydrationParentFiber = fiber;
17853 return;
17854 }
17855
17856 var firstAttemptedInstance = nextInstance;
17857
17858 if (!tryHydrate(fiber, nextInstance)) {
17859 // If we can't hydrate this instance let's try the next one.
17860 // We use this as a heuristic. It's based on intuition and not data so it
17861 // might be flawed or unnecessary.
17862 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
17863
17864 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
17865 // Nothing to hydrate. Make it an insertion.
17866 insertNonHydratedInstance(hydrationParentFiber, fiber);
17867 isHydrating = false;
17868 hydrationParentFiber = fiber;
17869 return;
17870 } // We matched the next one, we'll now assume that the first one was
17871 // superfluous and we'll delete it. Since we can't eagerly delete it
17872 // we'll have to schedule a deletion. To do that, this node needs a dummy
17873 // fiber associated with it.
17874
17875
17876 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
17877 }
17878
17879 hydrationParentFiber = fiber;
17880 nextHydratableInstance = getFirstHydratableChild(nextInstance);
17881}
17882
17883function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
17884 if (!supportsHydration) {
17885 {
17886 {
17887 throw Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
17888 }
17889 }
17890 }
17891
17892 var instance = fiber.stateNode;
17893 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.
17894
17895 fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
17896 // is a new ref we mark this as an update.
17897
17898 if (updatePayload !== null) {
17899 return true;
17900 }
17901
17902 return false;
17903}
17904
17905function prepareToHydrateHostTextInstance(fiber) {
17906 if (!supportsHydration) {
17907 {
17908 {
17909 throw Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
17910 }
17911 }
17912 }
17913
17914 var textInstance = fiber.stateNode;
17915 var textContent = fiber.memoizedProps;
17916 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
17917
17918 {
17919 if (shouldUpdate) {
17920 // We assume that prepareToHydrateHostTextInstance is called in a context where the
17921 // hydration parent is the parent host component of this host text.
17922 var returnFiber = hydrationParentFiber;
17923
17924 if (returnFiber !== null) {
17925 switch (returnFiber.tag) {
17926 case HostRoot:
17927 {
17928 var parentContainer = returnFiber.stateNode.containerInfo;
17929 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
17930 break;
17931 }
17932
17933 case HostComponent:
17934 {
17935 var parentType = returnFiber.type;
17936 var parentProps = returnFiber.memoizedProps;
17937 var parentInstance = returnFiber.stateNode;
17938 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
17939 break;
17940 }
17941 }
17942 }
17943 }
17944 }
17945
17946 return shouldUpdate;
17947}
17948
17949function prepareToHydrateHostSuspenseInstance(fiber) {
17950 if (!supportsHydration) {
17951 {
17952 {
17953 throw Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
17954 }
17955 }
17956 }
17957
17958 var suspenseState = fiber.memoizedState;
17959 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
17960
17961 if (!suspenseInstance) {
17962 {
17963 throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
17964 }
17965 }
17966
17967 hydrateSuspenseInstance(suspenseInstance, fiber);
17968}
17969
17970function skipPastDehydratedSuspenseInstance(fiber) {
17971 if (!supportsHydration) {
17972 {
17973 {
17974 throw Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
17975 }
17976 }
17977 }
17978
17979 var suspenseState = fiber.memoizedState;
17980 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
17981
17982 if (!suspenseInstance) {
17983 {
17984 throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
17985 }
17986 }
17987
17988 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
17989}
17990
17991function popToNextHostParent(fiber) {
17992 var parent = fiber.return;
17993
17994 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
17995 parent = parent.return;
17996 }
17997
17998 hydrationParentFiber = parent;
17999}
18000
18001function popHydrationState(fiber) {
18002 if (!supportsHydration) {
18003 return false;
18004 }
18005
18006 if (fiber !== hydrationParentFiber) {
18007 // We're deeper than the current hydration context, inside an inserted
18008 // tree.
18009 return false;
18010 }
18011
18012 if (!isHydrating) {
18013 // If we're not currently hydrating but we're in a hydration context, then
18014 // we were an insertion and now need to pop up reenter hydration of our
18015 // siblings.
18016 popToNextHostParent(fiber);
18017 isHydrating = true;
18018 return false;
18019 }
18020
18021 var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
18022 // We only do this deeper than head and body since they tend to have random
18023 // other nodes in them. We also ignore components with pure text content in
18024 // side of them.
18025 // TODO: Better heuristic.
18026
18027 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
18028 var nextInstance = nextHydratableInstance;
18029
18030 while (nextInstance) {
18031 deleteHydratableInstance(fiber, nextInstance);
18032 nextInstance = getNextHydratableSibling(nextInstance);
18033 }
18034 }
18035
18036 popToNextHostParent(fiber);
18037
18038 if (fiber.tag === SuspenseComponent) {
18039 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
18040 } else {
18041 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
18042 }
18043
18044 return true;
18045}
18046
18047function resetHydrationState() {
18048 if (!supportsHydration) {
18049 return;
18050 }
18051
18052 hydrationParentFiber = null;
18053 nextHydratableInstance = null;
18054 isHydrating = false;
18055}
18056
18057var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
18058var didReceiveUpdate = false;
18059var didWarnAboutBadClass;
18060var didWarnAboutModulePatternComponent;
18061var didWarnAboutContextTypeOnFunctionComponent;
18062var didWarnAboutGetDerivedStateOnFunctionComponent;
18063var didWarnAboutFunctionRefs;
18064var didWarnAboutReassigningProps;
18065var didWarnAboutMaxDuration;
18066var didWarnAboutRevealOrder;
18067var didWarnAboutTailOptions;
18068var didWarnAboutDefaultPropsOnFunctionComponent;
18069
18070{
18071 didWarnAboutBadClass = {};
18072 didWarnAboutModulePatternComponent = {};
18073 didWarnAboutContextTypeOnFunctionComponent = {};
18074 didWarnAboutGetDerivedStateOnFunctionComponent = {};
18075 didWarnAboutFunctionRefs = {};
18076 didWarnAboutReassigningProps = false;
18077 didWarnAboutMaxDuration = false;
18078 didWarnAboutRevealOrder = {};
18079 didWarnAboutTailOptions = {};
18080 didWarnAboutDefaultPropsOnFunctionComponent = {};
18081}
18082
18083function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18084 if (current$$1 === null) {
18085 // If this is a fresh new component that hasn't been rendered yet, we
18086 // won't update its child set by applying minimal side-effects. Instead,
18087 // we will add them all to the child before it gets rendered. That means
18088 // we can optimize this reconciliation pass by not tracking side-effects.
18089 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18090 } else {
18091 // If the current child is the same as the work in progress, it means that
18092 // we haven't yet started any work on these children. Therefore, we use
18093 // the clone algorithm to create a copy of all the current children.
18094 // If we had any progressed work already, that is invalid at this point so
18095 // let's throw it out.
18096 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
18097 }
18098}
18099
18100function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18101 // This function is fork of reconcileChildren. It's used in cases where we
18102 // want to reconcile without matching against the existing set. This has the
18103 // effect of all current children being unmounted; even if the type and key
18104 // are the same, the old child is unmounted and a new child is created.
18105 //
18106 // To do this, we're going to go through the reconcile algorithm twice. In
18107 // the first pass, we schedule a deletion for all the current children by
18108 // passing null.
18109 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
18110 // pass null in place of where we usually pass the current child set. This has
18111 // the effect of remounting all children regardless of whether their their
18112 // identity matches.
18113
18114 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18115}
18116
18117function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18118 // TODO: current can be non-null here even if the component
18119 // hasn't yet mounted. This happens after the first render suspends.
18120 // We'll need to figure out if this is fine or can cause issues.
18121 {
18122 if (workInProgress.type !== workInProgress.elementType) {
18123 // Lazy component props can't be validated in createElement
18124 // because they're only guaranteed to be resolved here.
18125 var innerPropTypes = Component.propTypes;
18126
18127 if (innerPropTypes) {
18128 checkPropTypes(innerPropTypes, nextProps, // Resolved props
18129 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18130 }
18131 }
18132 }
18133
18134 var render = Component.render;
18135 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
18136
18137 var nextChildren;
18138 prepareToReadContext(workInProgress, renderExpirationTime);
18139
18140 {
18141 ReactCurrentOwner$3.current = workInProgress;
18142 setCurrentPhase('render');
18143 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18144
18145 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18146 // Only double-render components with Hooks
18147 if (workInProgress.memoizedState !== null) {
18148 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18149 }
18150 }
18151
18152 setCurrentPhase(null);
18153 }
18154
18155 if (current$$1 !== null && !didReceiveUpdate) {
18156 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18157 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18158 } // React DevTools reads this flag.
18159
18160
18161 workInProgress.effectTag |= PerformedWork;
18162 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18163 return workInProgress.child;
18164}
18165
18166function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18167 if (current$$1 === null) {
18168 var type = Component.type;
18169
18170 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
18171 Component.defaultProps === undefined) {
18172 var resolvedType = type;
18173
18174 {
18175 resolvedType = resolveFunctionForHotReloading(type);
18176 } // If this is a plain function component without default props,
18177 // and with only the default shallow comparison, we upgrade it
18178 // to a SimpleMemoComponent to allow fast path updates.
18179
18180
18181 workInProgress.tag = SimpleMemoComponent;
18182 workInProgress.type = resolvedType;
18183
18184 {
18185 validateFunctionComponentInDev(workInProgress, type);
18186 }
18187
18188 return updateSimpleMemoComponent(current$$1, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
18189 }
18190
18191 {
18192 var innerPropTypes = type.propTypes;
18193
18194 if (innerPropTypes) {
18195 // Inner memo component props aren't currently validated in createElement.
18196 // We could move it there, but we'd still need this for lazy code path.
18197 checkPropTypes(innerPropTypes, nextProps, // Resolved props
18198 'prop', getComponentName(type), getCurrentFiberStackInDev);
18199 }
18200 }
18201
18202 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
18203 child.ref = workInProgress.ref;
18204 child.return = workInProgress;
18205 workInProgress.child = child;
18206 return child;
18207 }
18208
18209 {
18210 var _type = Component.type;
18211 var _innerPropTypes = _type.propTypes;
18212
18213 if (_innerPropTypes) {
18214 // Inner memo component props aren't currently validated in createElement.
18215 // We could move it there, but we'd still need this for lazy code path.
18216 checkPropTypes(_innerPropTypes, nextProps, // Resolved props
18217 'prop', getComponentName(_type), getCurrentFiberStackInDev);
18218 }
18219 }
18220
18221 var currentChild = current$$1.child; // This is always exactly one child
18222
18223 if (updateExpirationTime < renderExpirationTime) {
18224 // This will be the props with resolved defaultProps,
18225 // unlike current.memoizedProps which will be the unresolved ones.
18226 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
18227
18228 var compare = Component.compare;
18229 compare = compare !== null ? compare : shallowEqual;
18230
18231 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
18232 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18233 }
18234 } // React DevTools reads this flag.
18235
18236
18237 workInProgress.effectTag |= PerformedWork;
18238 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
18239 newChild.ref = workInProgress.ref;
18240 newChild.return = workInProgress;
18241 workInProgress.child = newChild;
18242 return newChild;
18243}
18244
18245function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18246 // TODO: current can be non-null here even if the component
18247 // hasn't yet mounted. This happens when the inner render suspends.
18248 // We'll need to figure out if this is fine or can cause issues.
18249 {
18250 if (workInProgress.type !== workInProgress.elementType) {
18251 // Lazy component props can't be validated in createElement
18252 // because they're only guaranteed to be resolved here.
18253 var outerMemoType = workInProgress.elementType;
18254
18255 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
18256 // We warn when you define propTypes on lazy()
18257 // so let's just skip over it to find memo() outer wrapper.
18258 // Inner props for memo are validated later.
18259 outerMemoType = refineResolvedLazyComponent(outerMemoType);
18260 }
18261
18262 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
18263
18264 if (outerPropTypes) {
18265 checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
18266 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
18267 } // Inner propTypes will be validated in the function component path.
18268
18269 }
18270 }
18271
18272 if (current$$1 !== null) {
18273 var prevProps = current$$1.memoizedProps;
18274
18275 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload:
18276 workInProgress.type === current$$1.type)) {
18277 didReceiveUpdate = false;
18278
18279 if (updateExpirationTime < renderExpirationTime) {
18280 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18281 }
18282 }
18283 }
18284
18285 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18286}
18287
18288function updateFragment(current$$1, workInProgress, renderExpirationTime) {
18289 var nextChildren = workInProgress.pendingProps;
18290 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18291 return workInProgress.child;
18292}
18293
18294function updateMode(current$$1, workInProgress, renderExpirationTime) {
18295 var nextChildren = workInProgress.pendingProps.children;
18296 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18297 return workInProgress.child;
18298}
18299
18300function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
18301 if (enableProfilerTimer) {
18302 workInProgress.effectTag |= Update;
18303 }
18304
18305 var nextProps = workInProgress.pendingProps;
18306 var nextChildren = nextProps.children;
18307 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18308 return workInProgress.child;
18309}
18310
18311function markRef(current$$1, workInProgress) {
18312 var ref = workInProgress.ref;
18313
18314 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
18315 // Schedule a Ref effect
18316 workInProgress.effectTag |= Ref;
18317 }
18318}
18319
18320function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18321 {
18322 if (workInProgress.type !== workInProgress.elementType) {
18323 // Lazy component props can't be validated in createElement
18324 // because they're only guaranteed to be resolved here.
18325 var innerPropTypes = Component.propTypes;
18326
18327 if (innerPropTypes) {
18328 checkPropTypes(innerPropTypes, nextProps, // Resolved props
18329 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18330 }
18331 }
18332 }
18333
18334 var context;
18335
18336 if (!disableLegacyContext) {
18337 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
18338 context = getMaskedContext(workInProgress, unmaskedContext);
18339 }
18340
18341 var nextChildren;
18342 prepareToReadContext(workInProgress, renderExpirationTime);
18343
18344 {
18345 ReactCurrentOwner$3.current = workInProgress;
18346 setCurrentPhase('render');
18347 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18348
18349 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18350 // Only double-render components with Hooks
18351 if (workInProgress.memoizedState !== null) {
18352 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18353 }
18354 }
18355
18356 setCurrentPhase(null);
18357 }
18358
18359 if (current$$1 !== null && !didReceiveUpdate) {
18360 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18361 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18362 } // React DevTools reads this flag.
18363
18364
18365 workInProgress.effectTag |= PerformedWork;
18366 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18367 return workInProgress.child;
18368}
18369
18370function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18371 {
18372 if (workInProgress.type !== workInProgress.elementType) {
18373 // Lazy component props can't be validated in createElement
18374 // because they're only guaranteed to be resolved here.
18375 var innerPropTypes = Component.propTypes;
18376
18377 if (innerPropTypes) {
18378 checkPropTypes(innerPropTypes, nextProps, // Resolved props
18379 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18380 }
18381 }
18382 } // Push context providers early to prevent context stack mismatches.
18383 // During mounting we don't know the child context yet as the instance doesn't exist.
18384 // We will invalidate the child context in finishClassComponent() right after rendering.
18385
18386
18387 var hasContext;
18388
18389 if (isContextProvider(Component)) {
18390 hasContext = true;
18391 pushContextProvider(workInProgress);
18392 } else {
18393 hasContext = false;
18394 }
18395
18396 prepareToReadContext(workInProgress, renderExpirationTime);
18397 var instance = workInProgress.stateNode;
18398 var shouldUpdate;
18399
18400 if (instance === null) {
18401 if (current$$1 !== null) {
18402 // An class component without an instance only mounts if it suspended
18403 // inside a non- concurrent tree, in an inconsistent state. We want to
18404 // tree it like a new mount, even though an empty version of it already
18405 // committed. Disconnect the alternate pointers.
18406 current$$1.alternate = null;
18407 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18408
18409 workInProgress.effectTag |= Placement;
18410 } // In the initial pass we might need to construct the instance.
18411
18412
18413 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18414 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18415 shouldUpdate = true;
18416 } else if (current$$1 === null) {
18417 // In a resume, we'll already have an instance we can reuse.
18418 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18419 } else {
18420 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18421 }
18422
18423 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
18424
18425 {
18426 var inst = workInProgress.stateNode;
18427
18428 if (inst.props !== nextProps) {
18429 !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;
18430 didWarnAboutReassigningProps = true;
18431 }
18432 }
18433
18434 return nextUnitOfWork;
18435}
18436
18437function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
18438 // Refs should update even if shouldComponentUpdate returns false
18439 markRef(current$$1, workInProgress);
18440 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
18441
18442 if (!shouldUpdate && !didCaptureError) {
18443 // Context providers should defer to sCU for rendering
18444 if (hasContext) {
18445 invalidateContextProvider(workInProgress, Component, false);
18446 }
18447
18448 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18449 }
18450
18451 var instance = workInProgress.stateNode; // Rerender
18452
18453 ReactCurrentOwner$3.current = workInProgress;
18454 var nextChildren;
18455
18456 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
18457 // If we captured an error, but getDerivedStateFrom catch is not defined,
18458 // unmount all the children. componentDidCatch will schedule an update to
18459 // re-render a fallback. This is temporary until we migrate everyone to
18460 // the new API.
18461 // TODO: Warn in a future release.
18462 nextChildren = null;
18463
18464 if (enableProfilerTimer) {
18465 stopProfilerTimerIfRunning(workInProgress);
18466 }
18467 } else {
18468 {
18469 setCurrentPhase('render');
18470 nextChildren = instance.render();
18471
18472 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18473 instance.render();
18474 }
18475
18476 setCurrentPhase(null);
18477 }
18478 } // React DevTools reads this flag.
18479
18480
18481 workInProgress.effectTag |= PerformedWork;
18482
18483 if (current$$1 !== null && didCaptureError) {
18484 // If we're recovering from an error, reconcile without reusing any of
18485 // the existing children. Conceptually, the normal children and the children
18486 // that are shown on error are two different sets, so we shouldn't reuse
18487 // normal children even if their identities match.
18488 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
18489 } else {
18490 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18491 } // Memoize state using the values we just used to render.
18492 // TODO: Restructure so we never read values from the instance.
18493
18494
18495 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
18496
18497 if (hasContext) {
18498 invalidateContextProvider(workInProgress, Component, true);
18499 }
18500
18501 return workInProgress.child;
18502}
18503
18504function pushHostRootContext(workInProgress) {
18505 var root = workInProgress.stateNode;
18506
18507 if (root.pendingContext) {
18508 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
18509 } else if (root.context) {
18510 // Should always be set
18511 pushTopLevelContextObject(workInProgress, root.context, false);
18512 }
18513
18514 pushHostContainer(workInProgress, root.containerInfo);
18515}
18516
18517function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
18518 pushHostRootContext(workInProgress);
18519 var updateQueue = workInProgress.updateQueue;
18520
18521 if (!(updateQueue !== null)) {
18522 {
18523 throw 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.");
18524 }
18525 }
18526
18527 var nextProps = workInProgress.pendingProps;
18528 var prevState = workInProgress.memoizedState;
18529 var prevChildren = prevState !== null ? prevState.element : null;
18530 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
18531 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
18532 // being called "element".
18533
18534 var nextChildren = nextState.element;
18535
18536 if (nextChildren === prevChildren) {
18537 // If the state is the same as before, that's a bailout because we had
18538 // no work that expires at this time.
18539 resetHydrationState();
18540 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18541 }
18542
18543 var root = workInProgress.stateNode;
18544
18545 if (root.hydrate && enterHydrationState(workInProgress)) {
18546 // If we don't have any current children this might be the first pass.
18547 // We always try to hydrate. If this isn't a hydration pass there won't
18548 // be any children to hydrate which is effectively the same thing as
18549 // not hydrating.
18550 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18551 workInProgress.child = child;
18552 var node = child;
18553
18554 while (node) {
18555 // Mark each child as hydrating. This is a fast path to know whether this
18556 // tree is part of a hydrating tree. This is used to determine if a child
18557 // node has fully mounted yet, and for scheduling event replaying.
18558 // Conceptually this is similar to Placement in that a new subtree is
18559 // inserted into the React tree here. It just happens to not need DOM
18560 // mutations because it already exists.
18561 node.effectTag = node.effectTag & ~Placement | Hydrating;
18562 node = node.sibling;
18563 }
18564 } else {
18565 // Otherwise reset hydration state in case we aborted and resumed another
18566 // root.
18567 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18568 resetHydrationState();
18569 }
18570
18571 return workInProgress.child;
18572}
18573
18574function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
18575 pushHostContext(workInProgress);
18576
18577 if (current$$1 === null) {
18578 tryToClaimNextHydratableInstance(workInProgress);
18579 }
18580
18581 var type = workInProgress.type;
18582 var nextProps = workInProgress.pendingProps;
18583 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
18584 var nextChildren = nextProps.children;
18585 var isDirectTextChild = shouldSetTextContent(type, nextProps);
18586
18587 if (isDirectTextChild) {
18588 // We special case a direct text child of a host node. This is a common
18589 // case. We won't handle it as a reified child. We will instead handle
18590 // this in the host environment that also have access to this prop. That
18591 // avoids allocating another HostText fiber and traversing it.
18592 nextChildren = null;
18593 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
18594 // If we're switching from a direct text child to a normal child, or to
18595 // empty, we need to schedule the text content to be reset.
18596 workInProgress.effectTag |= ContentReset;
18597 }
18598
18599 markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden.
18600
18601 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
18602 if (enableSchedulerTracing) {
18603 markSpawnedWork(Never);
18604 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
18605
18606
18607 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
18608 return null;
18609 }
18610
18611 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18612 return workInProgress.child;
18613}
18614
18615function updateHostText(current$$1, workInProgress) {
18616 if (current$$1 === null) {
18617 tryToClaimNextHydratableInstance(workInProgress);
18618 } // Nothing to do here. This is terminal. We'll do the completion step
18619 // immediately after.
18620
18621
18622 return null;
18623}
18624
18625function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
18626 if (_current !== null) {
18627 // An lazy component only mounts if it suspended inside a non-
18628 // concurrent tree, in an inconsistent state. We want to treat it like
18629 // a new mount, even though an empty version of it already committed.
18630 // Disconnect the alternate pointers.
18631 _current.alternate = null;
18632 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18633
18634 workInProgress.effectTag |= Placement;
18635 }
18636
18637 var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
18638 // Cancel and resume right after we know the tag.
18639
18640 cancelWorkTimer(workInProgress);
18641 var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
18642
18643 workInProgress.type = Component;
18644 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
18645 startWorkTimer(workInProgress);
18646 var resolvedProps = resolveDefaultProps(Component, props);
18647 var child;
18648
18649 switch (resolvedTag) {
18650 case FunctionComponent:
18651 {
18652 {
18653 validateFunctionComponentInDev(workInProgress, Component);
18654 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
18655 }
18656
18657 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18658 break;
18659 }
18660
18661 case ClassComponent:
18662 {
18663 {
18664 workInProgress.type = Component = resolveClassForHotReloading(Component);
18665 }
18666
18667 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18668 break;
18669 }
18670
18671 case ForwardRef:
18672 {
18673 {
18674 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
18675 }
18676
18677 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18678 break;
18679 }
18680
18681 case MemoComponent:
18682 {
18683 {
18684 if (workInProgress.type !== workInProgress.elementType) {
18685 var outerPropTypes = Component.propTypes;
18686
18687 if (outerPropTypes) {
18688 checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
18689 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18690 }
18691 }
18692 }
18693
18694 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
18695 updateExpirationTime, renderExpirationTime);
18696 break;
18697 }
18698
18699 default:
18700 {
18701 var hint = '';
18702
18703 {
18704 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
18705 hint = ' Did you wrap a component in React.lazy() more than once?';
18706 }
18707 } // This message intentionally doesn't mention ForwardRef or MemoComponent
18708 // because the fact that it's a separate type of work is an
18709 // implementation detail.
18710
18711
18712 {
18713 {
18714 throw Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint);
18715 }
18716 }
18717 }
18718 }
18719
18720 return child;
18721}
18722
18723function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
18724 if (_current !== null) {
18725 // An incomplete component only mounts if it suspended inside a non-
18726 // concurrent tree, in an inconsistent state. We want to treat it like
18727 // a new mount, even though an empty version of it already committed.
18728 // Disconnect the alternate pointers.
18729 _current.alternate = null;
18730 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18731
18732 workInProgress.effectTag |= Placement;
18733 } // Promote the fiber to a class and try rendering again.
18734
18735
18736 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
18737 // Push context providers early to prevent context stack mismatches.
18738 // During mounting we don't know the child context yet as the instance doesn't exist.
18739 // We will invalidate the child context in finishClassComponent() right after rendering.
18740
18741 var hasContext;
18742
18743 if (isContextProvider(Component)) {
18744 hasContext = true;
18745 pushContextProvider(workInProgress);
18746 } else {
18747 hasContext = false;
18748 }
18749
18750 prepareToReadContext(workInProgress, renderExpirationTime);
18751 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18752 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18753 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18754}
18755
18756function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
18757 if (_current !== null) {
18758 // An indeterminate component only mounts if it suspended inside a non-
18759 // concurrent tree, in an inconsistent state. We want to treat it like
18760 // a new mount, even though an empty version of it already committed.
18761 // Disconnect the alternate pointers.
18762 _current.alternate = null;
18763 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18764
18765 workInProgress.effectTag |= Placement;
18766 }
18767
18768 var props = workInProgress.pendingProps;
18769 var context;
18770
18771 if (!disableLegacyContext) {
18772 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
18773 context = getMaskedContext(workInProgress, unmaskedContext);
18774 }
18775
18776 prepareToReadContext(workInProgress, renderExpirationTime);
18777 var value;
18778
18779 {
18780 if (Component.prototype && typeof Component.prototype.render === 'function') {
18781 var componentName = getComponentName(Component) || 'Unknown';
18782
18783 if (!didWarnAboutBadClass[componentName]) {
18784 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);
18785 didWarnAboutBadClass[componentName] = true;
18786 }
18787 }
18788
18789 if (workInProgress.mode & StrictMode) {
18790 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
18791 }
18792
18793 ReactCurrentOwner$3.current = workInProgress;
18794 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18795 } // React DevTools reads this flag.
18796
18797
18798 workInProgress.effectTag |= PerformedWork;
18799
18800 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
18801 {
18802 var _componentName = getComponentName(Component) || 'Unknown';
18803
18804 if (!didWarnAboutModulePatternComponent[_componentName]) {
18805 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);
18806 didWarnAboutModulePatternComponent[_componentName] = true;
18807 }
18808 } // Proceed under the assumption that this is a class instance
18809
18810
18811 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
18812
18813 resetHooks(); // Push context providers early to prevent context stack mismatches.
18814 // During mounting we don't know the child context yet as the instance doesn't exist.
18815 // We will invalidate the child context in finishClassComponent() right after rendering.
18816
18817 var hasContext = false;
18818
18819 if (isContextProvider(Component)) {
18820 hasContext = true;
18821 pushContextProvider(workInProgress);
18822 } else {
18823 hasContext = false;
18824 }
18825
18826 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
18827 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
18828
18829 if (typeof getDerivedStateFromProps === 'function') {
18830 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
18831 }
18832
18833 adoptClassInstance(workInProgress, value);
18834 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
18835 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18836 } else {
18837 // Proceed under the assumption that this is a function component
18838 workInProgress.tag = FunctionComponent;
18839
18840 {
18841 if (disableLegacyContext && Component.contextTypes) {
18842 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentName(Component) || 'Unknown');
18843 }
18844
18845 if (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18846 // Only double-render components with Hooks
18847 if (workInProgress.memoizedState !== null) {
18848 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18849 }
18850 }
18851 }
18852
18853 reconcileChildren(null, workInProgress, value, renderExpirationTime);
18854
18855 {
18856 validateFunctionComponentInDev(workInProgress, Component);
18857 }
18858
18859 return workInProgress.child;
18860 }
18861}
18862
18863function validateFunctionComponentInDev(workInProgress, Component) {
18864 if (Component) {
18865 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
18866 }
18867
18868 if (workInProgress.ref !== null) {
18869 var info = '';
18870 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
18871
18872 if (ownerName) {
18873 info += '\n\nCheck the render method of `' + ownerName + '`.';
18874 }
18875
18876 var warningKey = ownerName || workInProgress._debugID || '';
18877 var debugSource = workInProgress._debugSource;
18878
18879 if (debugSource) {
18880 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
18881 }
18882
18883 if (!didWarnAboutFunctionRefs[warningKey]) {
18884 didWarnAboutFunctionRefs[warningKey] = true;
18885 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);
18886 }
18887 }
18888
18889 if (warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined) {
18890 var componentName = getComponentName(Component) || 'Unknown';
18891
18892 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
18893 warningWithoutStack$1(false, '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
18894 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
18895 }
18896 }
18897
18898 if (typeof Component.getDerivedStateFromProps === 'function') {
18899 var _componentName2 = getComponentName(Component) || 'Unknown';
18900
18901 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
18902 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', _componentName2);
18903 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
18904 }
18905 }
18906
18907 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
18908 var _componentName3 = getComponentName(Component) || 'Unknown';
18909
18910 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
18911 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName3);
18912 didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
18913 }
18914 }
18915}
18916
18917var SUSPENDED_MARKER = {
18918 dehydrated: null,
18919 retryTime: NoWork
18920};
18921
18922function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) {
18923 // If the context is telling us that we should show a fallback, and we're not
18924 // already showing content, then we should show the fallback instead.
18925 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current$$1 === null || current$$1.memoizedState !== null);
18926}
18927
18928function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
18929 var mode = workInProgress.mode;
18930 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
18931
18932 {
18933 if (shouldSuspend(workInProgress)) {
18934 workInProgress.effectTag |= DidCapture;
18935 }
18936 }
18937
18938 var suspenseContext = suspenseStackCursor.current;
18939 var nextDidTimeout = false;
18940 var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
18941
18942 if (didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress)) {
18943 // Something in this boundary's subtree already suspended. Switch to
18944 // rendering the fallback children.
18945 nextDidTimeout = true;
18946 workInProgress.effectTag &= ~DidCapture;
18947 } else {
18948 // Attempting the main content
18949 if (current$$1 === null || current$$1.memoizedState !== null) {
18950 // This is a new mount or this boundary is already showing a fallback state.
18951 // Mark this subtree context as having at least one invisible parent that could
18952 // handle the fallback state.
18953 // Boundaries without fallbacks or should be avoided are not considered since
18954 // they cannot handle preferred fallback states.
18955 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
18956 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
18957 }
18958 }
18959 }
18960
18961 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
18962 pushSuspenseContext(workInProgress, suspenseContext);
18963
18964 {
18965 if ('maxDuration' in nextProps) {
18966 if (!didWarnAboutMaxDuration) {
18967 didWarnAboutMaxDuration = true;
18968 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
18969 }
18970 }
18971 } // This next part is a bit confusing. If the children timeout, we switch to
18972 // showing the fallback children in place of the "primary" children.
18973 // However, we don't want to delete the primary children because then their
18974 // state will be lost (both the React state and the host state, e.g.
18975 // uncontrolled form inputs). Instead we keep them mounted and hide them.
18976 // Both the fallback children AND the primary children are rendered at the
18977 // same time. Once the primary children are un-suspended, we can delete
18978 // the fallback children — don't need to preserve their state.
18979 //
18980 // The two sets of children are siblings in the host environment, but
18981 // semantically, for purposes of reconciliation, they are two separate sets.
18982 // So we store them using two fragment fibers.
18983 //
18984 // However, we want to avoid allocating extra fibers for every placeholder.
18985 // They're only necessary when the children time out, because that's the
18986 // only time when both sets are mounted.
18987 //
18988 // So, the extra fragment fibers are only used if the children time out.
18989 // Otherwise, we render the primary children directly. This requires some
18990 // custom reconciliation logic to preserve the state of the primary
18991 // children. It's essentially a very basic form of re-parenting.
18992
18993
18994 if (current$$1 === null) {
18995 // If we're currently hydrating, try to hydrate this boundary.
18996 // But only if this has a fallback.
18997 if (nextProps.fallback !== undefined) {
18998 tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
18999
19000 if (enableSuspenseServerRenderer) {
19001 var suspenseState = workInProgress.memoizedState;
19002
19003 if (suspenseState !== null) {
19004 var dehydrated = suspenseState.dehydrated;
19005
19006 if (dehydrated !== null) {
19007 return mountDehydratedSuspenseComponent(workInProgress, dehydrated, renderExpirationTime);
19008 }
19009 }
19010 }
19011 } // This is the initial mount. This branch is pretty simple because there's
19012 // no previous state that needs to be preserved.
19013
19014
19015 if (nextDidTimeout) {
19016 // Mount separate fragments for primary and fallback children.
19017 var nextFallbackChildren = nextProps.fallback;
19018 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
19019 primaryChildFragment.return = workInProgress;
19020
19021 if ((workInProgress.mode & BlockingMode) === NoMode) {
19022 // Outside of blocking mode, we commit the effects from the
19023 // partially completed, timed-out tree, too.
19024 var progressedState = workInProgress.memoizedState;
19025 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
19026 primaryChildFragment.child = progressedPrimaryChild;
19027 var progressedChild = progressedPrimaryChild;
19028
19029 while (progressedChild !== null) {
19030 progressedChild.return = primaryChildFragment;
19031 progressedChild = progressedChild.sibling;
19032 }
19033 }
19034
19035 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
19036 fallbackChildFragment.return = workInProgress;
19037 primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
19038 // fallback children.
19039
19040 workInProgress.memoizedState = SUSPENDED_MARKER;
19041 workInProgress.child = primaryChildFragment;
19042 return fallbackChildFragment;
19043 } else {
19044 // Mount the primary children without an intermediate fragment fiber.
19045 var nextPrimaryChildren = nextProps.children;
19046 workInProgress.memoizedState = null;
19047 return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
19048 }
19049 } else {
19050 // This is an update. This branch is more complicated because we need to
19051 // ensure the state of the primary children is preserved.
19052 var prevState = current$$1.memoizedState;
19053
19054 if (prevState !== null) {
19055 if (enableSuspenseServerRenderer) {
19056 var _dehydrated = prevState.dehydrated;
19057
19058 if (_dehydrated !== null) {
19059 if (!didSuspend) {
19060 return updateDehydratedSuspenseComponent(current$$1, workInProgress, _dehydrated, prevState, renderExpirationTime);
19061 } else if (workInProgress.memoizedState !== null) {
19062 // Something suspended and we should still be in dehydrated mode.
19063 // Leave the existing child in place.
19064 workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there
19065 // but the normal suspense pass doesn't.
19066
19067 workInProgress.effectTag |= DidCapture;
19068 return null;
19069 } else {
19070 // Suspended but we should no longer be in dehydrated mode.
19071 // Therefore we now have to render the fallback. Wrap the children
19072 // in a fragment fiber to keep them separate from the fallback
19073 // children.
19074 var _nextFallbackChildren = nextProps.fallback;
19075
19076 var _primaryChildFragment = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19077 // going to render this fragment.
19078 null, mode, NoWork, null);
19079
19080 _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child
19081 // that we're not going to hydrate.
19082
19083 _primaryChildFragment.child = null;
19084
19085 if ((workInProgress.mode & BlockingMode) === NoMode) {
19086 // Outside of blocking mode, we commit the effects from the
19087 // partially completed, timed-out tree, too.
19088 var _progressedChild = _primaryChildFragment.child = workInProgress.child;
19089
19090 while (_progressedChild !== null) {
19091 _progressedChild.return = _primaryChildFragment;
19092 _progressedChild = _progressedChild.sibling;
19093 }
19094 } else {
19095 // We will have dropped the effect list which contains the deletion.
19096 // We need to reconcile to delete the current child.
19097 reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
19098 } // Because primaryChildFragment is a new fiber that we're inserting as the
19099 // parent of a new tree, we need to set its treeBaseDuration.
19100
19101
19102 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19103 // treeBaseDuration is the sum of all the child tree base durations.
19104 var treeBaseDuration = 0;
19105 var hiddenChild = _primaryChildFragment.child;
19106
19107 while (hiddenChild !== null) {
19108 treeBaseDuration += hiddenChild.treeBaseDuration;
19109 hiddenChild = hiddenChild.sibling;
19110 }
19111
19112 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
19113 } // Create a fragment from the fallback children, too.
19114
19115
19116 var _fallbackChildFragment = createFiberFromFragment(_nextFallbackChildren, mode, renderExpirationTime, null);
19117
19118 _fallbackChildFragment.return = workInProgress;
19119 _primaryChildFragment.sibling = _fallbackChildFragment;
19120 _fallbackChildFragment.effectTag |= Placement;
19121 _primaryChildFragment.childExpirationTime = NoWork;
19122 workInProgress.memoizedState = SUSPENDED_MARKER;
19123 workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the
19124 // fallback children.
19125
19126 return _fallbackChildFragment;
19127 }
19128 }
19129 } // The current tree already timed out. That means each child set is
19130 // wrapped in a fragment fiber.
19131
19132
19133 var currentPrimaryChildFragment = current$$1.child;
19134 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
19135
19136 if (nextDidTimeout) {
19137 // Still timed out. Reuse the current primary children by cloning
19138 // its fragment. We're going to skip over these entirely.
19139 var _nextFallbackChildren2 = nextProps.fallback;
19140
19141 var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
19142
19143 _primaryChildFragment2.return = workInProgress;
19144
19145 if ((workInProgress.mode & BlockingMode) === NoMode) {
19146 // Outside of blocking mode, we commit the effects from the
19147 // partially completed, timed-out tree, too.
19148 var _progressedState = workInProgress.memoizedState;
19149
19150 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
19151
19152 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
19153 _primaryChildFragment2.child = _progressedPrimaryChild;
19154 var _progressedChild2 = _progressedPrimaryChild;
19155
19156 while (_progressedChild2 !== null) {
19157 _progressedChild2.return = _primaryChildFragment2;
19158 _progressedChild2 = _progressedChild2.sibling;
19159 }
19160 }
19161 } // Because primaryChildFragment is a new fiber that we're inserting as the
19162 // parent of a new tree, we need to set its treeBaseDuration.
19163
19164
19165 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19166 // treeBaseDuration is the sum of all the child tree base durations.
19167 var _treeBaseDuration = 0;
19168 var _hiddenChild = _primaryChildFragment2.child;
19169
19170 while (_hiddenChild !== null) {
19171 _treeBaseDuration += _hiddenChild.treeBaseDuration;
19172 _hiddenChild = _hiddenChild.sibling;
19173 }
19174
19175 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
19176 } // Clone the fallback child fragment, too. These we'll continue
19177 // working on.
19178
19179
19180 var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2, currentFallbackChildFragment.expirationTime);
19181
19182 _fallbackChildFragment2.return = workInProgress;
19183 _primaryChildFragment2.sibling = _fallbackChildFragment2;
19184 _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19185 // fallback children.
19186
19187 workInProgress.memoizedState = SUSPENDED_MARKER;
19188 workInProgress.child = _primaryChildFragment2;
19189 return _fallbackChildFragment2;
19190 } else {
19191 // No longer suspended. Switch back to showing the primary children,
19192 // and remove the intermediate fragment fiber.
19193 var _nextPrimaryChildren = nextProps.children;
19194 var currentPrimaryChild = currentPrimaryChildFragment.child;
19195 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
19196 // children. Wait until the complete phase, after we've confirmed the
19197 // fallback is no longer needed.
19198 // TODO: Would it be better to store the fallback fragment on
19199 // the stateNode?
19200 // Continue rendering the children, like we normally do.
19201
19202 workInProgress.memoizedState = null;
19203 return workInProgress.child = primaryChild;
19204 }
19205 } else {
19206 // The current tree has not already timed out. That means the primary
19207 // children are not wrapped in a fragment fiber.
19208 var _currentPrimaryChild = current$$1.child;
19209
19210 if (nextDidTimeout) {
19211 // Timed out. Wrap the children in a fragment fiber to keep them
19212 // separate from the fallback children.
19213 var _nextFallbackChildren3 = nextProps.fallback;
19214
19215 var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19216 // going to render this fragment.
19217 null, mode, NoWork, null);
19218
19219 _primaryChildFragment3.return = workInProgress;
19220 _primaryChildFragment3.child = _currentPrimaryChild;
19221
19222 if (_currentPrimaryChild !== null) {
19223 _currentPrimaryChild.return = _primaryChildFragment3;
19224 } // Even though we're creating a new fiber, there are no new children,
19225 // because we're reusing an already mounted tree. So we don't need to
19226 // schedule a placement.
19227 // primaryChildFragment.effectTag |= Placement;
19228
19229
19230 if ((workInProgress.mode & BlockingMode) === NoMode) {
19231 // Outside of blocking mode, we commit the effects from the
19232 // partially completed, timed-out tree, too.
19233 var _progressedState2 = workInProgress.memoizedState;
19234
19235 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
19236
19237 _primaryChildFragment3.child = _progressedPrimaryChild2;
19238 var _progressedChild3 = _progressedPrimaryChild2;
19239
19240 while (_progressedChild3 !== null) {
19241 _progressedChild3.return = _primaryChildFragment3;
19242 _progressedChild3 = _progressedChild3.sibling;
19243 }
19244 } // Because primaryChildFragment is a new fiber that we're inserting as the
19245 // parent of a new tree, we need to set its treeBaseDuration.
19246
19247
19248 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19249 // treeBaseDuration is the sum of all the child tree base durations.
19250 var _treeBaseDuration2 = 0;
19251 var _hiddenChild2 = _primaryChildFragment3.child;
19252
19253 while (_hiddenChild2 !== null) {
19254 _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
19255 _hiddenChild2 = _hiddenChild2.sibling;
19256 }
19257
19258 _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
19259 } // Create a fragment from the fallback children, too.
19260
19261
19262 var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
19263
19264 _fallbackChildFragment3.return = workInProgress;
19265 _primaryChildFragment3.sibling = _fallbackChildFragment3;
19266 _fallbackChildFragment3.effectTag |= Placement;
19267 _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19268 // fallback children.
19269
19270 workInProgress.memoizedState = SUSPENDED_MARKER;
19271 workInProgress.child = _primaryChildFragment3;
19272 return _fallbackChildFragment3;
19273 } else {
19274 // Still haven't timed out. Continue rendering the children, like we
19275 // normally do.
19276 workInProgress.memoizedState = null;
19277 var _nextPrimaryChildren2 = nextProps.children;
19278 return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
19279 }
19280 }
19281 }
19282}
19283
19284function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
19285 // We're now not suspended nor dehydrated.
19286 workInProgress.memoizedState = null; // Retry with the full children.
19287
19288 var nextProps = workInProgress.pendingProps;
19289 var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and
19290 // that the old child gets a Deletion effect.
19291 // We could also call forceUnmountCurrentAndReconcile.
19292
19293 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19294 return workInProgress.child;
19295}
19296
19297function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderExpirationTime) {
19298 // During the first pass, we'll bail out and not drill into the children.
19299 // Instead, we'll leave the content in place and try to hydrate it later.
19300 if ((workInProgress.mode & BlockingMode) === NoMode) {
19301 {
19302 warning$1(false, 'Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOM.createBlockingRoot(container, { hydrate: true })' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
19303 }
19304
19305 workInProgress.expirationTime = Sync;
19306 } else if (isSuspenseInstanceFallback(suspenseInstance)) {
19307 // This is a client-only boundary. Since we won't get any content from the server
19308 // for this, we need to schedule that at a higher priority based on when it would
19309 // have timed out. In theory we could render it in this pass but it would have the
19310 // wrong priority associated with it and will prevent hydration of parent path.
19311 // Instead, we'll leave work left on it to render it in a separate commit.
19312 // TODO This time should be the time at which the server rendered response that is
19313 // a parent to this boundary was displayed. However, since we currently don't have
19314 // a protocol to transfer that time, we'll just estimate it by using the current
19315 // time. This will mean that Suspense timeouts are slightly shifted to later than
19316 // they should be.
19317 var serverDisplayTime = requestCurrentTimeForUpdate(); // Schedule a normal pri update to render this content.
19318
19319 var newExpirationTime = computeAsyncExpiration(serverDisplayTime);
19320
19321 if (enableSchedulerTracing) {
19322 markSpawnedWork(newExpirationTime);
19323 }
19324
19325 workInProgress.expirationTime = newExpirationTime;
19326 } else {
19327 // We'll continue hydrating the rest at offscreen priority since we'll already
19328 // be showing the right content coming from the server, it is no rush.
19329 workInProgress.expirationTime = Never;
19330
19331 if (enableSchedulerTracing) {
19332 markSpawnedWork(Never);
19333 }
19334 }
19335
19336 return null;
19337}
19338
19339function updateDehydratedSuspenseComponent(current$$1, workInProgress, suspenseInstance, suspenseState, renderExpirationTime) {
19340 // We should never be hydrating at this point because it is the first pass,
19341 // but after we've already committed once.
19342 warnIfHydrating();
19343
19344 if ((workInProgress.mode & BlockingMode) === NoMode) {
19345 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19346 }
19347
19348 if (isSuspenseInstanceFallback(suspenseInstance)) {
19349 // This boundary is in a permanent fallback state. In this case, we'll never
19350 // get an update and we'll never be able to hydrate the final content. Let's just try the
19351 // client side render instead.
19352 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19353 } // We use childExpirationTime to indicate that a child might depend on context, so if
19354 // any context has changed, we need to treat is as if the input might have changed.
19355
19356
19357 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
19358
19359 if (didReceiveUpdate || hasContextChanged$$1) {
19360 // This boundary has changed since the first render. This means that we are now unable to
19361 // hydrate it. We might still be able to hydrate it using an earlier expiration time, if
19362 // we are rendering at lower expiration than sync.
19363 if (renderExpirationTime < Sync) {
19364 if (suspenseState.retryTime <= renderExpirationTime) {
19365 // This render is even higher pri than we've seen before, let's try again
19366 // at even higher pri.
19367 var attemptHydrationAtExpirationTime = renderExpirationTime + 1;
19368 suspenseState.retryTime = attemptHydrationAtExpirationTime;
19369 scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render.
19370 } else {// We have already tried to ping at a higher priority than we're rendering with
19371 // so if we got here, we must have failed to hydrate at those levels. We must
19372 // now give up. Instead, we're going to delete the whole subtree and instead inject
19373 // a new real Suspense boundary to take its place, which may render content
19374 // or fallback. This might suspend for a while and if it does we might still have
19375 // an opportunity to hydrate before this pass commits.
19376 }
19377 } // If we have scheduled higher pri work above, this will probably just abort the render
19378 // since we now have higher priority work, but in case it doesn't, we need to prepare to
19379 // render something, if we time out. Even if that requires us to delete everything and
19380 // skip hydration.
19381 // Delay having to do this as long as the suspense timeout allows us.
19382
19383
19384 renderDidSuspendDelayIfPossible();
19385 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19386 } else if (isSuspenseInstancePending(suspenseInstance)) {
19387 // This component is still pending more data from the server, so we can't hydrate its
19388 // content. We treat it as if this component suspended itself. It might seem as if
19389 // we could just try to render it client-side instead. However, this will perform a
19390 // lot of unnecessary work and is unlikely to complete since it often will suspend
19391 // on missing data anyway. Additionally, the server might be able to render more
19392 // than we can on the client yet. In that case we'd end up with more fallback states
19393 // on the client than if we just leave it alone. If the server times out or errors
19394 // these should update this boundary to the permanent Fallback state instead.
19395 // Mark it as having captured (i.e. suspended).
19396 workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
19397
19398 workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result.
19399
19400 registerSuspenseInstanceRetry(suspenseInstance, retryDehydratedSuspenseBoundary.bind(null, current$$1));
19401 return null;
19402 } else {
19403 // This is the first attempt.
19404 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance);
19405 var nextProps = workInProgress.pendingProps;
19406 var nextChildren = nextProps.children;
19407 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19408 var node = child;
19409
19410 while (node) {
19411 // Mark each child as hydrating. This is a fast path to know whether this
19412 // tree is part of a hydrating tree. This is used to determine if a child
19413 // node has fully mounted yet, and for scheduling event replaying.
19414 // Conceptually this is similar to Placement in that a new subtree is
19415 // inserted into the React tree here. It just happens to not need DOM
19416 // mutations because it already exists.
19417 node.effectTag |= Hydrating;
19418 node = node.sibling;
19419 }
19420
19421 workInProgress.child = child;
19422 return workInProgress.child;
19423 }
19424}
19425
19426function scheduleWorkOnFiber(fiber, renderExpirationTime) {
19427 if (fiber.expirationTime < renderExpirationTime) {
19428 fiber.expirationTime = renderExpirationTime;
19429 }
19430
19431 var alternate = fiber.alternate;
19432
19433 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
19434 alternate.expirationTime = renderExpirationTime;
19435 }
19436
19437 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
19438}
19439
19440function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
19441 // Mark any Suspense boundaries with fallbacks as having work to do.
19442 // If they were previously forced into fallbacks, they may now be able
19443 // to unblock.
19444 var node = firstChild;
19445
19446 while (node !== null) {
19447 if (node.tag === SuspenseComponent) {
19448 var state = node.memoizedState;
19449
19450 if (state !== null) {
19451 scheduleWorkOnFiber(node, renderExpirationTime);
19452 }
19453 } else if (node.tag === SuspenseListComponent) {
19454 // If the tail is hidden there might not be an Suspense boundaries
19455 // to schedule work on. In this case we have to schedule it on the
19456 // list itself.
19457 // We don't have to traverse to the children of the list since
19458 // the list will propagate the change when it rerenders.
19459 scheduleWorkOnFiber(node, renderExpirationTime);
19460 } else if (node.child !== null) {
19461 node.child.return = node;
19462 node = node.child;
19463 continue;
19464 }
19465
19466 if (node === workInProgress) {
19467 return;
19468 }
19469
19470 while (node.sibling === null) {
19471 if (node.return === null || node.return === workInProgress) {
19472 return;
19473 }
19474
19475 node = node.return;
19476 }
19477
19478 node.sibling.return = node.return;
19479 node = node.sibling;
19480 }
19481}
19482
19483function findLastContentRow(firstChild) {
19484 // This is going to find the last row among these children that is already
19485 // showing content on the screen, as opposed to being in fallback state or
19486 // new. If a row has multiple Suspense boundaries, any of them being in the
19487 // fallback state, counts as the whole row being in a fallback state.
19488 // Note that the "rows" will be workInProgress, but any nested children
19489 // will still be current since we haven't rendered them yet. The mounted
19490 // order may not be the same as the new order. We use the new order.
19491 var row = firstChild;
19492 var lastContentRow = null;
19493
19494 while (row !== null) {
19495 var currentRow = row.alternate; // New rows can't be content rows.
19496
19497 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19498 lastContentRow = row;
19499 }
19500
19501 row = row.sibling;
19502 }
19503
19504 return lastContentRow;
19505}
19506
19507function validateRevealOrder(revealOrder) {
19508 {
19509 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
19510 didWarnAboutRevealOrder[revealOrder] = true;
19511
19512 if (typeof revealOrder === 'string') {
19513 switch (revealOrder.toLowerCase()) {
19514 case 'together':
19515 case 'forwards':
19516 case 'backwards':
19517 {
19518 warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
19519 break;
19520 }
19521
19522 case 'forward':
19523 case 'backward':
19524 {
19525 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());
19526 break;
19527 }
19528
19529 default:
19530 warning$1(false, '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19531 break;
19532 }
19533 } else {
19534 warning$1(false, '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19535 }
19536 }
19537 }
19538}
19539
19540function validateTailOptions(tailMode, revealOrder) {
19541 {
19542 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
19543 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
19544 didWarnAboutTailOptions[tailMode] = true;
19545 warning$1(false, '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
19546 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
19547 didWarnAboutTailOptions[tailMode] = true;
19548 warning$1(false, '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
19549 }
19550 }
19551 }
19552}
19553
19554function validateSuspenseListNestedChild(childSlot, index) {
19555 {
19556 var isArray = Array.isArray(childSlot);
19557 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
19558
19559 if (isArray || isIterable) {
19560 var type = isArray ? 'array' : 'iterable';
19561 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);
19562 return false;
19563 }
19564 }
19565
19566 return true;
19567}
19568
19569function validateSuspenseListChildren(children, revealOrder) {
19570 {
19571 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
19572 if (Array.isArray(children)) {
19573 for (var i = 0; i < children.length; i++) {
19574 if (!validateSuspenseListNestedChild(children[i], i)) {
19575 return;
19576 }
19577 }
19578 } else {
19579 var iteratorFn = getIteratorFn(children);
19580
19581 if (typeof iteratorFn === 'function') {
19582 var childrenIterator = iteratorFn.call(children);
19583
19584 if (childrenIterator) {
19585 var step = childrenIterator.next();
19586 var _i = 0;
19587
19588 for (; !step.done; step = childrenIterator.next()) {
19589 if (!validateSuspenseListNestedChild(step.value, _i)) {
19590 return;
19591 }
19592
19593 _i++;
19594 }
19595 }
19596 } else {
19597 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);
19598 }
19599 }
19600 }
19601 }
19602}
19603
19604function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
19605 var renderState = workInProgress.memoizedState;
19606
19607 if (renderState === null) {
19608 workInProgress.memoizedState = {
19609 isBackwards: isBackwards,
19610 rendering: null,
19611 last: lastContentRow,
19612 tail: tail,
19613 tailExpiration: 0,
19614 tailMode: tailMode,
19615 lastEffect: lastEffectBeforeRendering
19616 };
19617 } else {
19618 // We can reuse the existing object from previous renders.
19619 renderState.isBackwards = isBackwards;
19620 renderState.rendering = null;
19621 renderState.last = lastContentRow;
19622 renderState.tail = tail;
19623 renderState.tailExpiration = 0;
19624 renderState.tailMode = tailMode;
19625 renderState.lastEffect = lastEffectBeforeRendering;
19626 }
19627} // This can end up rendering this component multiple passes.
19628// The first pass splits the children fibers into two sets. A head and tail.
19629// We first render the head. If anything is in fallback state, we do another
19630// pass through beginWork to rerender all children (including the tail) with
19631// the force suspend context. If the first render didn't have anything in
19632// in fallback state. Then we render each row in the tail one-by-one.
19633// That happens in the completeWork phase without going back to beginWork.
19634
19635
19636function updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime) {
19637 var nextProps = workInProgress.pendingProps;
19638 var revealOrder = nextProps.revealOrder;
19639 var tailMode = nextProps.tail;
19640 var newChildren = nextProps.children;
19641 validateRevealOrder(revealOrder);
19642 validateTailOptions(tailMode, revealOrder);
19643 validateSuspenseListChildren(newChildren, revealOrder);
19644 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19645 var suspenseContext = suspenseStackCursor.current;
19646 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
19647
19648 if (shouldForceFallback) {
19649 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
19650 workInProgress.effectTag |= DidCapture;
19651 } else {
19652 var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect;
19653
19654 if (didSuspendBefore) {
19655 // If we previously forced a fallback, we need to schedule work
19656 // on any nested boundaries to let them know to try to render
19657 // again. This is the same as context updating.
19658 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
19659 }
19660
19661 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19662 }
19663
19664 pushSuspenseContext(workInProgress, suspenseContext);
19665
19666 if ((workInProgress.mode & BlockingMode) === NoMode) {
19667 // Outside of blocking mode, SuspenseList doesn't work so we just
19668 // use make it a noop by treating it as the default revealOrder.
19669 workInProgress.memoizedState = null;
19670 } else {
19671 switch (revealOrder) {
19672 case 'forwards':
19673 {
19674 var lastContentRow = findLastContentRow(workInProgress.child);
19675 var tail;
19676
19677 if (lastContentRow === null) {
19678 // The whole list is part of the tail.
19679 // TODO: We could fast path by just rendering the tail now.
19680 tail = workInProgress.child;
19681 workInProgress.child = null;
19682 } else {
19683 // Disconnect the tail rows after the content row.
19684 // We're going to render them separately later.
19685 tail = lastContentRow.sibling;
19686 lastContentRow.sibling = null;
19687 }
19688
19689 initSuspenseListRenderState(workInProgress, false, // isBackwards
19690 tail, lastContentRow, tailMode, workInProgress.lastEffect);
19691 break;
19692 }
19693
19694 case 'backwards':
19695 {
19696 // We're going to find the first row that has existing content.
19697 // At the same time we're going to reverse the list of everything
19698 // we pass in the meantime. That's going to be our tail in reverse
19699 // order.
19700 var _tail = null;
19701 var row = workInProgress.child;
19702 workInProgress.child = null;
19703
19704 while (row !== null) {
19705 var currentRow = row.alternate; // New rows can't be content rows.
19706
19707 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19708 // This is the beginning of the main content.
19709 workInProgress.child = row;
19710 break;
19711 }
19712
19713 var nextRow = row.sibling;
19714 row.sibling = _tail;
19715 _tail = row;
19716 row = nextRow;
19717 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
19718
19719
19720 initSuspenseListRenderState(workInProgress, true, // isBackwards
19721 _tail, null, // last
19722 tailMode, workInProgress.lastEffect);
19723 break;
19724 }
19725
19726 case 'together':
19727 {
19728 initSuspenseListRenderState(workInProgress, false, // isBackwards
19729 null, // tail
19730 null, // last
19731 undefined, workInProgress.lastEffect);
19732 break;
19733 }
19734
19735 default:
19736 {
19737 // The default reveal order is the same as not having
19738 // a boundary.
19739 workInProgress.memoizedState = null;
19740 }
19741 }
19742 }
19743
19744 return workInProgress.child;
19745}
19746
19747function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
19748 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19749 var nextChildren = workInProgress.pendingProps;
19750
19751 if (current$$1 === null) {
19752 // Portals are special because we don't append the children during mount
19753 // but at commit. Therefore we need to track insertions which the normal
19754 // flow doesn't do during mount. This doesn't happen at the root because
19755 // the root always starts with a "current" with a null child.
19756 // TODO: Consider unifying this with how the root works.
19757 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19758 } else {
19759 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19760 }
19761
19762 return workInProgress.child;
19763}
19764
19765function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
19766 var providerType = workInProgress.type;
19767 var context = providerType._context;
19768 var newProps = workInProgress.pendingProps;
19769 var oldProps = workInProgress.memoizedProps;
19770 var newValue = newProps.value;
19771
19772 {
19773 var providerPropTypes = workInProgress.type.propTypes;
19774
19775 if (providerPropTypes) {
19776 checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
19777 }
19778 }
19779
19780 pushProvider(workInProgress, newValue);
19781
19782 if (oldProps !== null) {
19783 var oldValue = oldProps.value;
19784 var changedBits = calculateChangedBits(context, newValue, oldValue);
19785
19786 if (changedBits === 0) {
19787 // No change. Bailout early if children are the same.
19788 if (oldProps.children === newProps.children && !hasContextChanged()) {
19789 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
19790 }
19791 } else {
19792 // The context value changed. Search for matching consumers and schedule
19793 // them to update.
19794 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
19795 }
19796 }
19797
19798 var newChildren = newProps.children;
19799 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19800 return workInProgress.child;
19801}
19802
19803var hasWarnedAboutUsingContextAsConsumer = false;
19804
19805function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
19806 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
19807 // DEV mode, we create a separate object for Context.Consumer that acts
19808 // like a proxy to Context. This proxy object adds unnecessary code in PROD
19809 // so we use the old behaviour (Context.Consumer references Context) to
19810 // reduce size and overhead. The separate object references context via
19811 // a property called "_context", which also gives us the ability to check
19812 // in DEV mode if this property exists or not and warn if it does not.
19813
19814 {
19815 if (context._context === undefined) {
19816 // This may be because it's a Context (rather than a Consumer).
19817 // Or it may be because it's older React where they're the same thing.
19818 // We only want to warn if we're sure it's a new React.
19819 if (context !== context.Consumer) {
19820 if (!hasWarnedAboutUsingContextAsConsumer) {
19821 hasWarnedAboutUsingContextAsConsumer = true;
19822 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?');
19823 }
19824 }
19825 } else {
19826 context = context._context;
19827 }
19828 }
19829
19830 var newProps = workInProgress.pendingProps;
19831 var render = newProps.children;
19832
19833 {
19834 !(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;
19835 }
19836
19837 prepareToReadContext(workInProgress, renderExpirationTime);
19838 var newValue = readContext(context, newProps.unstable_observedBits);
19839 var newChildren;
19840
19841 {
19842 ReactCurrentOwner$3.current = workInProgress;
19843 setCurrentPhase('render');
19844 newChildren = render(newValue);
19845 setCurrentPhase(null);
19846 } // React DevTools reads this flag.
19847
19848
19849 workInProgress.effectTag |= PerformedWork;
19850 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19851 return workInProgress.child;
19852}
19853
19854function updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime) {
19855 var fundamentalImpl = workInProgress.type.impl;
19856
19857 if (fundamentalImpl.reconcileChildren === false) {
19858 return null;
19859 }
19860
19861 var nextProps = workInProgress.pendingProps;
19862 var nextChildren = nextProps.children;
19863 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19864 return workInProgress.child;
19865}
19866
19867function updateScopeComponent(current$$1, workInProgress, renderExpirationTime) {
19868 var nextProps = workInProgress.pendingProps;
19869 var nextChildren = nextProps.children;
19870 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19871 return workInProgress.child;
19872}
19873
19874function markWorkInProgressReceivedUpdate() {
19875 didReceiveUpdate = true;
19876}
19877
19878function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
19879 cancelWorkTimer(workInProgress);
19880
19881 if (current$$1 !== null) {
19882 // Reuse previous dependencies
19883 workInProgress.dependencies = current$$1.dependencies;
19884 }
19885
19886 if (enableProfilerTimer) {
19887 // Don't update "base" render times for bailouts.
19888 stopProfilerTimerIfRunning(workInProgress);
19889 }
19890
19891 var updateExpirationTime = workInProgress.expirationTime;
19892
19893 if (updateExpirationTime !== NoWork) {
19894 markUnprocessedUpdateTime(updateExpirationTime);
19895 } // Check if the children have any pending work.
19896
19897
19898 var childExpirationTime = workInProgress.childExpirationTime;
19899
19900 if (childExpirationTime < renderExpirationTime) {
19901 // The children don't have any work either. We can skip them.
19902 // TODO: Once we add back resuming, we should check if the children are
19903 // a work-in-progress set. If so, we need to transfer their effects.
19904 return null;
19905 } else {
19906 // This fiber doesn't have work, but its subtree does. Clone the child
19907 // fibers and continue.
19908 cloneChildFibers(current$$1, workInProgress);
19909 return workInProgress.child;
19910 }
19911}
19912
19913function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
19914 {
19915 var returnFiber = oldWorkInProgress.return;
19916
19917 if (returnFiber === null) {
19918 throw new Error('Cannot swap the root fiber.');
19919 } // Disconnect from the old current.
19920 // It will get deleted.
19921
19922
19923 current$$1.alternate = null;
19924 oldWorkInProgress.alternate = null; // Connect to the new tree.
19925
19926 newWorkInProgress.index = oldWorkInProgress.index;
19927 newWorkInProgress.sibling = oldWorkInProgress.sibling;
19928 newWorkInProgress.return = oldWorkInProgress.return;
19929 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
19930
19931 if (oldWorkInProgress === returnFiber.child) {
19932 returnFiber.child = newWorkInProgress;
19933 } else {
19934 var prevSibling = returnFiber.child;
19935
19936 if (prevSibling === null) {
19937 throw new Error('Expected parent to have a child.');
19938 }
19939
19940 while (prevSibling.sibling !== oldWorkInProgress) {
19941 prevSibling = prevSibling.sibling;
19942
19943 if (prevSibling === null) {
19944 throw new Error('Expected to find the previous sibling.');
19945 }
19946 }
19947
19948 prevSibling.sibling = newWorkInProgress;
19949 } // Delete the old fiber and place the new one.
19950 // Since the old fiber is disconnected, we have to schedule it manually.
19951
19952
19953 var last = returnFiber.lastEffect;
19954
19955 if (last !== null) {
19956 last.nextEffect = current$$1;
19957 returnFiber.lastEffect = current$$1;
19958 } else {
19959 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
19960 }
19961
19962 current$$1.nextEffect = null;
19963 current$$1.effectTag = Deletion;
19964 newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
19965
19966 return newWorkInProgress;
19967 }
19968}
19969
19970function beginWork$1(current$$1, workInProgress, renderExpirationTime) {
19971 var updateExpirationTime = workInProgress.expirationTime;
19972
19973 {
19974 if (workInProgress._debugNeedsRemount && current$$1 !== null) {
19975 // This will restart the begin phase with a new fiber.
19976 return remountFiber(current$$1, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
19977 }
19978 }
19979
19980 if (current$$1 !== null) {
19981 var oldProps = current$$1.memoizedProps;
19982 var newProps = workInProgress.pendingProps;
19983
19984 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
19985 workInProgress.type !== current$$1.type)) {
19986 // If props or context changed, mark the fiber as having performed work.
19987 // This may be unset if the props are determined to be equal later (memo).
19988 didReceiveUpdate = true;
19989 } else if (updateExpirationTime < renderExpirationTime) {
19990 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
19991 // the begin phase. There's still some bookkeeping we that needs to be done
19992 // in this optimized path, mostly pushing stuff onto the stack.
19993
19994 switch (workInProgress.tag) {
19995 case HostRoot:
19996 pushHostRootContext(workInProgress);
19997 resetHydrationState();
19998 break;
19999
20000 case HostComponent:
20001 pushHostContext(workInProgress);
20002
20003 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
20004 if (enableSchedulerTracing) {
20005 markSpawnedWork(Never);
20006 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
20007
20008
20009 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
20010 return null;
20011 }
20012
20013 break;
20014
20015 case ClassComponent:
20016 {
20017 var Component = workInProgress.type;
20018
20019 if (isContextProvider(Component)) {
20020 pushContextProvider(workInProgress);
20021 }
20022
20023 break;
20024 }
20025
20026 case HostPortal:
20027 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
20028 break;
20029
20030 case ContextProvider:
20031 {
20032 var newValue = workInProgress.memoizedProps.value;
20033 pushProvider(workInProgress, newValue);
20034 break;
20035 }
20036
20037 case Profiler:
20038 if (enableProfilerTimer) {
20039 // Profiler should only call onRender when one of its descendants actually rendered.
20040 var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20041
20042 if (hasChildWork) {
20043 workInProgress.effectTag |= Update;
20044 }
20045 }
20046
20047 break;
20048
20049 case SuspenseComponent:
20050 {
20051 var state = workInProgress.memoizedState;
20052
20053 if (state !== null) {
20054 if (enableSuspenseServerRenderer) {
20055 if (state.dehydrated !== null) {
20056 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
20057 // been unsuspended it has committed as a resolved Suspense component.
20058 // If it needs to be retried, it should have work scheduled on it.
20059
20060 workInProgress.effectTag |= DidCapture;
20061 break;
20062 }
20063 } // If this boundary is currently timed out, we need to decide
20064 // whether to retry the primary children, or to skip over it and
20065 // go straight to the fallback. Check the priority of the primary
20066 // child fragment.
20067
20068
20069 var primaryChildFragment = workInProgress.child;
20070 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
20071
20072 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
20073 // The primary children have pending work. Use the normal path
20074 // to attempt to render the primary children again.
20075 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20076 } else {
20077 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
20078 // priority. Bailout.
20079
20080 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20081
20082 if (child !== null) {
20083 // The fallback children have pending work. Skip over the
20084 // primary children and work on the fallback.
20085 return child.sibling;
20086 } else {
20087 return null;
20088 }
20089 }
20090 } else {
20091 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
20092 }
20093
20094 break;
20095 }
20096
20097 case SuspenseListComponent:
20098 {
20099 var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect;
20100
20101 var _hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20102
20103 if (didSuspendBefore) {
20104 if (_hasChildWork) {
20105 // If something was in fallback state last time, and we have all the
20106 // same children then we're still in progressive loading state.
20107 // Something might get unblocked by state updates or retries in the
20108 // tree which will affect the tail. So we need to use the normal
20109 // path to compute the correct tail.
20110 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20111 } // If none of the children had any work, that means that none of
20112 // them got retried so they'll still be blocked in the same way
20113 // as before. We can fast bail out.
20114
20115
20116 workInProgress.effectTag |= DidCapture;
20117 } // If nothing suspended before and we're rendering the same children,
20118 // then the tail doesn't matter. Anything new that suspends will work
20119 // in the "together" mode, so we can continue from the state we had.
20120
20121
20122 var renderState = workInProgress.memoizedState;
20123
20124 if (renderState !== null) {
20125 // Reset to the "together" mode in case we've started a different
20126 // update in the past but didn't complete it.
20127 renderState.rendering = null;
20128 renderState.tail = null;
20129 }
20130
20131 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
20132
20133 if (_hasChildWork) {
20134 break;
20135 } else {
20136 // If none of the children had any work, that means that none of
20137 // them got retried so they'll still be blocked in the same way
20138 // as before. We can fast bail out.
20139 return null;
20140 }
20141 }
20142 }
20143
20144 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20145 } else {
20146 // An update was scheduled on this fiber, but there are no new props
20147 // nor legacy context. Set this to false. If an update queue or context
20148 // consumer produces a changed value, it will set this to true. Otherwise,
20149 // the component will assume the children have not changed and bail out.
20150 didReceiveUpdate = false;
20151 }
20152 } else {
20153 didReceiveUpdate = false;
20154 } // Before entering the begin phase, clear the expiration time.
20155
20156
20157 workInProgress.expirationTime = NoWork;
20158
20159 switch (workInProgress.tag) {
20160 case IndeterminateComponent:
20161 {
20162 return mountIndeterminateComponent(current$$1, workInProgress, workInProgress.type, renderExpirationTime);
20163 }
20164
20165 case LazyComponent:
20166 {
20167 var elementType = workInProgress.elementType;
20168 return mountLazyComponent(current$$1, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
20169 }
20170
20171 case FunctionComponent:
20172 {
20173 var _Component = workInProgress.type;
20174 var unresolvedProps = workInProgress.pendingProps;
20175 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
20176 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
20177 }
20178
20179 case ClassComponent:
20180 {
20181 var _Component2 = workInProgress.type;
20182 var _unresolvedProps = workInProgress.pendingProps;
20183
20184 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
20185
20186 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
20187 }
20188
20189 case HostRoot:
20190 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
20191
20192 case HostComponent:
20193 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
20194
20195 case HostText:
20196 return updateHostText(current$$1, workInProgress);
20197
20198 case SuspenseComponent:
20199 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20200
20201 case HostPortal:
20202 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
20203
20204 case ForwardRef:
20205 {
20206 var type = workInProgress.type;
20207 var _unresolvedProps2 = workInProgress.pendingProps;
20208
20209 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
20210
20211 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
20212 }
20213
20214 case Fragment:
20215 return updateFragment(current$$1, workInProgress, renderExpirationTime);
20216
20217 case Mode:
20218 return updateMode(current$$1, workInProgress, renderExpirationTime);
20219
20220 case Profiler:
20221 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
20222
20223 case ContextProvider:
20224 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
20225
20226 case ContextConsumer:
20227 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
20228
20229 case MemoComponent:
20230 {
20231 var _type2 = workInProgress.type;
20232 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
20233
20234 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
20235
20236 {
20237 if (workInProgress.type !== workInProgress.elementType) {
20238 var outerPropTypes = _type2.propTypes;
20239
20240 if (outerPropTypes) {
20241 checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
20242 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
20243 }
20244 }
20245 }
20246
20247 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
20248 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
20249 }
20250
20251 case SimpleMemoComponent:
20252 {
20253 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
20254 }
20255
20256 case IncompleteClassComponent:
20257 {
20258 var _Component3 = workInProgress.type;
20259 var _unresolvedProps4 = workInProgress.pendingProps;
20260
20261 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
20262
20263 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
20264 }
20265
20266 case SuspenseListComponent:
20267 {
20268 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20269 }
20270
20271 case FundamentalComponent:
20272 {
20273 if (enableFundamentalAPI) {
20274 return updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime);
20275 }
20276
20277 break;
20278 }
20279
20280 case ScopeComponent:
20281 {
20282 if (enableScopeAPI) {
20283 return updateScopeComponent(current$$1, workInProgress, renderExpirationTime);
20284 }
20285
20286 break;
20287 }
20288 }
20289
20290 {
20291 {
20292 throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
20293 }
20294 }
20295}
20296
20297function createFundamentalStateInstance(currentFiber, props, impl, state) {
20298 return {
20299 currentFiber: currentFiber,
20300 impl: impl,
20301 instance: null,
20302 prevProps: null,
20303 props: props,
20304 state: state
20305 };
20306}
20307
20308function isFiberSuspenseAndTimedOut(fiber) {
20309 return fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
20310}
20311
20312function getSuspenseFallbackChild(fiber) {
20313 return fiber.child.sibling.child;
20314}
20315
20316var emptyObject$1 = {};
20317
20318function collectScopedNodes(node, fn, scopedNodes) {
20319 if (enableScopeAPI) {
20320 if (node.tag === HostComponent) {
20321 var _type = node.type,
20322 memoizedProps = node.memoizedProps,
20323 stateNode = node.stateNode;
20324
20325 var _instance = getPublicInstance(stateNode);
20326
20327 if (_instance !== null && fn(_type, memoizedProps || emptyObject$1, _instance) === true) {
20328 scopedNodes.push(_instance);
20329 }
20330 }
20331
20332 var child = node.child;
20333
20334 if (isFiberSuspenseAndTimedOut(node)) {
20335 child = getSuspenseFallbackChild(node);
20336 }
20337
20338 if (child !== null) {
20339 collectScopedNodesFromChildren(child, fn, scopedNodes);
20340 }
20341 }
20342}
20343
20344function collectFirstScopedNode(node, fn) {
20345 if (enableScopeAPI) {
20346 if (node.tag === HostComponent) {
20347 var _type2 = node.type,
20348 memoizedProps = node.memoizedProps,
20349 stateNode = node.stateNode;
20350
20351 var _instance2 = getPublicInstance(stateNode);
20352
20353 if (_instance2 !== null && fn(_type2, memoizedProps, _instance2) === true) {
20354 return _instance2;
20355 }
20356 }
20357
20358 var child = node.child;
20359
20360 if (isFiberSuspenseAndTimedOut(node)) {
20361 child = getSuspenseFallbackChild(node);
20362 }
20363
20364 if (child !== null) {
20365 return collectFirstScopedNodeFromChildren(child, fn);
20366 }
20367 }
20368
20369 return null;
20370}
20371
20372function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) {
20373 var child = startingChild;
20374
20375 while (child !== null) {
20376 collectScopedNodes(child, fn, scopedNodes);
20377 child = child.sibling;
20378 }
20379}
20380
20381function collectFirstScopedNodeFromChildren(startingChild, fn) {
20382 var child = startingChild;
20383
20384 while (child !== null) {
20385 var scopedNode = collectFirstScopedNode(child, fn);
20386
20387 if (scopedNode !== null) {
20388 return scopedNode;
20389 }
20390
20391 child = child.sibling;
20392 }
20393
20394 return null;
20395}
20396
20397function collectNearestScopeMethods(node, scope, childrenScopes) {
20398 if (isValidScopeNode(node, scope)) {
20399 childrenScopes.push(node.stateNode.methods);
20400 } else {
20401 var child = node.child;
20402
20403 if (isFiberSuspenseAndTimedOut(node)) {
20404 child = getSuspenseFallbackChild(node);
20405 }
20406
20407 if (child !== null) {
20408 collectNearestChildScopeMethods(child, scope, childrenScopes);
20409 }
20410 }
20411}
20412
20413function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) {
20414 var child = startingChild;
20415
20416 while (child !== null) {
20417 collectNearestScopeMethods(child, scope, childrenScopes);
20418 child = child.sibling;
20419 }
20420}
20421
20422function isValidScopeNode(node, scope) {
20423 return node.tag === ScopeComponent && node.type === scope && node.stateNode !== null;
20424}
20425
20426function createScopeMethods(scope, instance) {
20427 return {
20428 getChildren: function () {
20429 var currentFiber = instance.fiber;
20430 var child = currentFiber.child;
20431 var childrenScopes = [];
20432
20433 if (child !== null) {
20434 collectNearestChildScopeMethods(child, scope, childrenScopes);
20435 }
20436
20437 return childrenScopes.length === 0 ? null : childrenScopes;
20438 },
20439 getChildrenFromRoot: function () {
20440 var currentFiber = instance.fiber;
20441 var node = currentFiber;
20442
20443 while (node !== null) {
20444 var parent = node.return;
20445
20446 if (parent === null) {
20447 break;
20448 }
20449
20450 node = parent;
20451
20452 if (node.tag === ScopeComponent && node.type === scope) {
20453 break;
20454 }
20455 }
20456
20457 var childrenScopes = [];
20458 collectNearestChildScopeMethods(node.child, scope, childrenScopes);
20459 return childrenScopes.length === 0 ? null : childrenScopes;
20460 },
20461 getParent: function () {
20462 var node = instance.fiber.return;
20463
20464 while (node !== null) {
20465 if (node.tag === ScopeComponent && node.type === scope) {
20466 return node.stateNode.methods;
20467 }
20468
20469 node = node.return;
20470 }
20471
20472 return null;
20473 },
20474 getProps: function () {
20475 var currentFiber = instance.fiber;
20476 return currentFiber.memoizedProps;
20477 },
20478 queryAllNodes: function (fn) {
20479 var currentFiber = instance.fiber;
20480 var child = currentFiber.child;
20481 var scopedNodes = [];
20482
20483 if (child !== null) {
20484 collectScopedNodesFromChildren(child, fn, scopedNodes);
20485 }
20486
20487 return scopedNodes.length === 0 ? null : scopedNodes;
20488 },
20489 queryFirstNode: function (fn) {
20490 var currentFiber = instance.fiber;
20491 var child = currentFiber.child;
20492
20493 if (child !== null) {
20494 return collectFirstScopedNodeFromChildren(child, fn);
20495 }
20496
20497 return null;
20498 },
20499 containsNode: function (node) {
20500 var fiber = getInstanceFromNode$2(node);
20501
20502 while (fiber !== null) {
20503 if (fiber.tag === ScopeComponent && fiber.type === scope && fiber.stateNode === instance) {
20504 return true;
20505 }
20506
20507 fiber = fiber.return;
20508 }
20509
20510 return false;
20511 }
20512 };
20513}
20514
20515function markUpdate(workInProgress) {
20516 // Tag the fiber with an update effect. This turns a Placement into
20517 // a PlacementAndUpdate.
20518 workInProgress.effectTag |= Update;
20519}
20520
20521function markRef$1(workInProgress) {
20522 workInProgress.effectTag |= Ref;
20523}
20524
20525var appendAllChildren;
20526var updateHostContainer;
20527var updateHostComponent$1;
20528var updateHostText$1;
20529
20530if (supportsMutation) {
20531 // Mutation mode
20532 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20533 // We only have the top Fiber that was created but we need recurse down its
20534 // children to find all the terminal nodes.
20535 var node = workInProgress.child;
20536
20537 while (node !== null) {
20538 if (node.tag === HostComponent || node.tag === HostText) {
20539 appendInitialChild(parent, node.stateNode);
20540 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20541 appendInitialChild(parent, node.stateNode.instance);
20542 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20543 // down its children. Instead, we'll get insertions from each child in
20544 // the portal directly.
20545 } else if (node.child !== null) {
20546 node.child.return = node;
20547 node = node.child;
20548 continue;
20549 }
20550
20551 if (node === workInProgress) {
20552 return;
20553 }
20554
20555 while (node.sibling === null) {
20556 if (node.return === null || node.return === workInProgress) {
20557 return;
20558 }
20559
20560 node = node.return;
20561 }
20562
20563 node.sibling.return = node.return;
20564 node = node.sibling;
20565 }
20566 };
20567
20568 updateHostContainer = function (workInProgress) {// Noop
20569 };
20570
20571 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20572 // If we have an alternate, that means this is an update and we need to
20573 // schedule a side-effect to do the updates.
20574 var oldProps = current.memoizedProps;
20575
20576 if (oldProps === newProps) {
20577 // In mutation mode, this is sufficient for a bailout because
20578 // we won't touch this node even if children changed.
20579 return;
20580 } // If we get updated because one of our children updated, we don't
20581 // have newProps so we'll have to reuse them.
20582 // TODO: Split the update API as separate for the props vs. children.
20583 // Even better would be if children weren't special cased at all tho.
20584
20585
20586 var instance = workInProgress.stateNode;
20587 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
20588 // component is hitting the resume path. Figure out why. Possibly
20589 // related to `hidden`.
20590
20591 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
20592
20593 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
20594 // is a new ref we mark this as an update. All the work is done in commitWork.
20595
20596 if (updatePayload) {
20597 markUpdate(workInProgress);
20598 }
20599 };
20600
20601 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20602 // If the text differs, mark it as an update. All the work in done in commitWork.
20603 if (oldText !== newText) {
20604 markUpdate(workInProgress);
20605 }
20606 };
20607} else if (supportsPersistence) {
20608 // Persistent host tree mode
20609 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20610 // We only have the top Fiber that was created but we need recurse down its
20611 // children to find all the terminal nodes.
20612 var node = workInProgress.child;
20613
20614 while (node !== null) {
20615 // eslint-disable-next-line no-labels
20616 branches: if (node.tag === HostComponent) {
20617 var instance = node.stateNode;
20618
20619 if (needsVisibilityToggle && isHidden) {
20620 // This child is inside a timed out tree. Hide it.
20621 var props = node.memoizedProps;
20622 var type = node.type;
20623 instance = cloneHiddenInstance(instance, type, props, node);
20624 }
20625
20626 appendInitialChild(parent, instance);
20627 } else if (node.tag === HostText) {
20628 var _instance = node.stateNode;
20629
20630 if (needsVisibilityToggle && isHidden) {
20631 // This child is inside a timed out tree. Hide it.
20632 var text = node.memoizedProps;
20633 _instance = cloneHiddenTextInstance(_instance, text, node);
20634 }
20635
20636 appendInitialChild(parent, _instance);
20637 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20638 var _instance2 = node.stateNode.instance;
20639
20640 if (needsVisibilityToggle && isHidden) {
20641 // This child is inside a timed out tree. Hide it.
20642 var _props = node.memoizedProps;
20643 var _type = node.type;
20644 _instance2 = cloneHiddenInstance(_instance2, _type, _props, node);
20645 }
20646
20647 appendInitialChild(parent, _instance2);
20648 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20649 // down its children. Instead, we'll get insertions from each child in
20650 // the portal directly.
20651 } else if (node.tag === SuspenseComponent) {
20652 if ((node.effectTag & Update) !== NoEffect) {
20653 // Need to toggle the visibility of the primary children.
20654 var newIsHidden = node.memoizedState !== null;
20655
20656 if (newIsHidden) {
20657 var primaryChildParent = node.child;
20658
20659 if (primaryChildParent !== null) {
20660 if (primaryChildParent.child !== null) {
20661 primaryChildParent.child.return = primaryChildParent;
20662 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
20663 }
20664
20665 var fallbackChildParent = primaryChildParent.sibling;
20666
20667 if (fallbackChildParent !== null) {
20668 fallbackChildParent.return = node;
20669 node = fallbackChildParent;
20670 continue;
20671 }
20672 }
20673 }
20674 }
20675
20676 if (node.child !== null) {
20677 // Continue traversing like normal
20678 node.child.return = node;
20679 node = node.child;
20680 continue;
20681 }
20682 } else if (node.child !== null) {
20683 node.child.return = node;
20684 node = node.child;
20685 continue;
20686 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20687
20688
20689 node = node;
20690
20691 if (node === workInProgress) {
20692 return;
20693 }
20694
20695 while (node.sibling === null) {
20696 if (node.return === null || node.return === workInProgress) {
20697 return;
20698 }
20699
20700 node = node.return;
20701 }
20702
20703 node.sibling.return = node.return;
20704 node = node.sibling;
20705 }
20706 }; // An unfortunate fork of appendAllChildren because we have two different parent types.
20707
20708
20709 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
20710 // We only have the top Fiber that was created but we need recurse down its
20711 // children to find all the terminal nodes.
20712 var node = workInProgress.child;
20713
20714 while (node !== null) {
20715 // eslint-disable-next-line no-labels
20716 branches: if (node.tag === HostComponent) {
20717 var instance = node.stateNode;
20718
20719 if (needsVisibilityToggle && isHidden) {
20720 // This child is inside a timed out tree. Hide it.
20721 var props = node.memoizedProps;
20722 var type = node.type;
20723 instance = cloneHiddenInstance(instance, type, props, node);
20724 }
20725
20726 appendChildToContainerChildSet(containerChildSet, instance);
20727 } else if (node.tag === HostText) {
20728 var _instance3 = node.stateNode;
20729
20730 if (needsVisibilityToggle && isHidden) {
20731 // This child is inside a timed out tree. Hide it.
20732 var text = node.memoizedProps;
20733 _instance3 = cloneHiddenTextInstance(_instance3, text, node);
20734 }
20735
20736 appendChildToContainerChildSet(containerChildSet, _instance3);
20737 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20738 var _instance4 = node.stateNode.instance;
20739
20740 if (needsVisibilityToggle && isHidden) {
20741 // This child is inside a timed out tree. Hide it.
20742 var _props2 = node.memoizedProps;
20743 var _type2 = node.type;
20744 _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node);
20745 }
20746
20747 appendChildToContainerChildSet(containerChildSet, _instance4);
20748 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20749 // down its children. Instead, we'll get insertions from each child in
20750 // the portal directly.
20751 } else if (node.tag === SuspenseComponent) {
20752 if ((node.effectTag & Update) !== NoEffect) {
20753 // Need to toggle the visibility of the primary children.
20754 var newIsHidden = node.memoizedState !== null;
20755
20756 if (newIsHidden) {
20757 var primaryChildParent = node.child;
20758
20759 if (primaryChildParent !== null) {
20760 if (primaryChildParent.child !== null) {
20761 primaryChildParent.child.return = primaryChildParent;
20762 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
20763 }
20764
20765 var fallbackChildParent = primaryChildParent.sibling;
20766
20767 if (fallbackChildParent !== null) {
20768 fallbackChildParent.return = node;
20769 node = fallbackChildParent;
20770 continue;
20771 }
20772 }
20773 }
20774 }
20775
20776 if (node.child !== null) {
20777 // Continue traversing like normal
20778 node.child.return = node;
20779 node = node.child;
20780 continue;
20781 }
20782 } else if (node.child !== null) {
20783 node.child.return = node;
20784 node = node.child;
20785 continue;
20786 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20787
20788
20789 node = node;
20790
20791 if (node === workInProgress) {
20792 return;
20793 }
20794
20795 while (node.sibling === null) {
20796 if (node.return === null || node.return === workInProgress) {
20797 return;
20798 }
20799
20800 node = node.return;
20801 }
20802
20803 node.sibling.return = node.return;
20804 node = node.sibling;
20805 }
20806 };
20807
20808 updateHostContainer = function (workInProgress) {
20809 var portalOrRoot = workInProgress.stateNode;
20810 var childrenUnchanged = workInProgress.firstEffect === null;
20811
20812 if (childrenUnchanged) {// No changes, just reuse the existing instance.
20813 } else {
20814 var container = portalOrRoot.containerInfo;
20815 var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set.
20816
20817 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
20818 portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container.
20819
20820 markUpdate(workInProgress);
20821 finalizeContainerChildren(container, newChildSet);
20822 }
20823 };
20824
20825 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20826 var currentInstance = current.stateNode;
20827 var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates.
20828 // This guarantees that we can reuse all of them.
20829
20830 var childrenUnchanged = workInProgress.firstEffect === null;
20831
20832 if (childrenUnchanged && oldProps === newProps) {
20833 // No changes, just reuse the existing instance.
20834 // Note that this might release a previous clone.
20835 workInProgress.stateNode = currentInstance;
20836 return;
20837 }
20838
20839 var recyclableInstance = workInProgress.stateNode;
20840 var currentHostContext = getHostContext();
20841 var updatePayload = null;
20842
20843 if (oldProps !== newProps) {
20844 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
20845 }
20846
20847 if (childrenUnchanged && updatePayload === null) {
20848 // No changes, just reuse the existing instance.
20849 // Note that this might release a previous clone.
20850 workInProgress.stateNode = currentInstance;
20851 return;
20852 }
20853
20854 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
20855
20856 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
20857 markUpdate(workInProgress);
20858 }
20859
20860 workInProgress.stateNode = newInstance;
20861
20862 if (childrenUnchanged) {
20863 // If there are no other effects in this tree, we need to flag this node as having one.
20864 // Even though we're not going to use it for anything.
20865 // Otherwise parents won't know that there are new children to propagate upwards.
20866 markUpdate(workInProgress);
20867 } else {
20868 // If children might have changed, we have to add them all to the set.
20869 appendAllChildren(newInstance, workInProgress, false, false);
20870 }
20871 };
20872
20873 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20874 if (oldText !== newText) {
20875 // If the text content differs, we'll create a new text instance for it.
20876 var rootContainerInstance = getRootHostContainer();
20877 var currentHostContext = getHostContext();
20878 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.
20879 // This lets the parents know that at least one of their children has changed.
20880
20881 markUpdate(workInProgress);
20882 }
20883 };
20884} else {
20885 // No host operations
20886 updateHostContainer = function (workInProgress) {// Noop
20887 };
20888
20889 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop
20890 };
20891
20892 updateHostText$1 = function (current, workInProgress, oldText, newText) {// Noop
20893 };
20894}
20895
20896function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
20897 switch (renderState.tailMode) {
20898 case 'hidden':
20899 {
20900 // Any insertions at the end of the tail list after this point
20901 // should be invisible. If there are already mounted boundaries
20902 // anything before them are not considered for collapsing.
20903 // Therefore we need to go through the whole tail to find if
20904 // there are any.
20905 var tailNode = renderState.tail;
20906 var lastTailNode = null;
20907
20908 while (tailNode !== null) {
20909 if (tailNode.alternate !== null) {
20910 lastTailNode = tailNode;
20911 }
20912
20913 tailNode = tailNode.sibling;
20914 } // Next we're simply going to delete all insertions after the
20915 // last rendered item.
20916
20917
20918 if (lastTailNode === null) {
20919 // All remaining items in the tail are insertions.
20920 renderState.tail = null;
20921 } else {
20922 // Detach the insertion after the last node that was already
20923 // inserted.
20924 lastTailNode.sibling = null;
20925 }
20926
20927 break;
20928 }
20929
20930 case 'collapsed':
20931 {
20932 // Any insertions at the end of the tail list after this point
20933 // should be invisible. If there are already mounted boundaries
20934 // anything before them are not considered for collapsing.
20935 // Therefore we need to go through the whole tail to find if
20936 // there are any.
20937 var _tailNode = renderState.tail;
20938 var _lastTailNode = null;
20939
20940 while (_tailNode !== null) {
20941 if (_tailNode.alternate !== null) {
20942 _lastTailNode = _tailNode;
20943 }
20944
20945 _tailNode = _tailNode.sibling;
20946 } // Next we're simply going to delete all insertions after the
20947 // last rendered item.
20948
20949
20950 if (_lastTailNode === null) {
20951 // All remaining items in the tail are insertions.
20952 if (!hasRenderedATailFallback && renderState.tail !== null) {
20953 // We suspended during the head. We want to show at least one
20954 // row at the tail. So we'll keep on and cut off the rest.
20955 renderState.tail.sibling = null;
20956 } else {
20957 renderState.tail = null;
20958 }
20959 } else {
20960 // Detach the insertion after the last node that was already
20961 // inserted.
20962 _lastTailNode.sibling = null;
20963 }
20964
20965 break;
20966 }
20967 }
20968}
20969
20970function completeWork(current, workInProgress, renderExpirationTime) {
20971 var newProps = workInProgress.pendingProps;
20972
20973 switch (workInProgress.tag) {
20974 case IndeterminateComponent:
20975 break;
20976
20977 case LazyComponent:
20978 break;
20979
20980 case SimpleMemoComponent:
20981 case FunctionComponent:
20982 break;
20983
20984 case ClassComponent:
20985 {
20986 var Component = workInProgress.type;
20987
20988 if (isContextProvider(Component)) {
20989 popContext(workInProgress);
20990 }
20991
20992 break;
20993 }
20994
20995 case HostRoot:
20996 {
20997 popHostContainer(workInProgress);
20998 popTopLevelContextObject(workInProgress);
20999 var fiberRoot = workInProgress.stateNode;
21000
21001 if (fiberRoot.pendingContext) {
21002 fiberRoot.context = fiberRoot.pendingContext;
21003 fiberRoot.pendingContext = null;
21004 }
21005
21006 if (current === null || current.child === null) {
21007 // If we hydrated, pop so that we can delete any remaining children
21008 // that weren't hydrated.
21009 var wasHydrated = popHydrationState(workInProgress);
21010
21011 if (wasHydrated) {
21012 // If we hydrated, then we'll need to schedule an update for
21013 // the commit side-effects on the root.
21014 markUpdate(workInProgress);
21015 }
21016 }
21017
21018 updateHostContainer(workInProgress);
21019 break;
21020 }
21021
21022 case HostComponent:
21023 {
21024 popHostContext(workInProgress);
21025 var rootContainerInstance = getRootHostContainer();
21026 var type = workInProgress.type;
21027
21028 if (current !== null && workInProgress.stateNode != null) {
21029 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
21030
21031 if (enableFlareAPI) {
21032 var prevListeners = current.memoizedProps.listeners;
21033 var nextListeners = newProps.listeners;
21034
21035 if (prevListeners !== nextListeners) {
21036 markUpdate(workInProgress);
21037 }
21038 }
21039
21040 if (current.ref !== workInProgress.ref) {
21041 markRef$1(workInProgress);
21042 }
21043 } else {
21044 if (!newProps) {
21045 if (!(workInProgress.stateNode !== null)) {
21046 {
21047 throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
21048 }
21049 } // This can happen when we abort work.
21050
21051
21052 break;
21053 }
21054
21055 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
21056 // "stack" as the parent. Then append children as we go in beginWork
21057 // or completeWork depending on we want to add then top->down or
21058 // bottom->up. Top->down is faster in IE11.
21059
21060 var _wasHydrated = popHydrationState(workInProgress);
21061
21062 if (_wasHydrated) {
21063 // TODO: Move this and createInstance step into the beginPhase
21064 // to consolidate.
21065 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
21066 // If changes to the hydrated node needs to be applied at the
21067 // commit-phase we mark this as such.
21068 markUpdate(workInProgress);
21069 }
21070
21071 if (enableFlareAPI) {
21072 var listeners = newProps.listeners;
21073
21074 if (listeners != null) {
21075 updateEventListeners(listeners, workInProgress, rootContainerInstance);
21076 }
21077 }
21078 } else {
21079 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
21080 appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
21081
21082 workInProgress.stateNode = instance;
21083
21084 if (enableFlareAPI) {
21085 var _listeners = newProps.listeners;
21086
21087 if (_listeners != null) {
21088 updateEventListeners(_listeners, workInProgress, rootContainerInstance);
21089 }
21090 } // Certain renderers require commit-time effects for initial mount.
21091 // (eg DOM renderer supports auto-focus for certain elements).
21092 // Make sure such renderers get scheduled for later work.
21093
21094
21095 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
21096 markUpdate(workInProgress);
21097 }
21098 }
21099
21100 if (workInProgress.ref !== null) {
21101 // If there is a ref on a host node we need to schedule a callback
21102 markRef$1(workInProgress);
21103 }
21104 }
21105
21106 break;
21107 }
21108
21109 case HostText:
21110 {
21111 var newText = newProps;
21112
21113 if (current && workInProgress.stateNode != null) {
21114 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
21115 // to schedule a side-effect to do the updates.
21116
21117 updateHostText$1(current, workInProgress, oldText, newText);
21118 } else {
21119 if (typeof newText !== 'string') {
21120 if (!(workInProgress.stateNode !== null)) {
21121 {
21122 throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
21123 }
21124 } // This can happen when we abort work.
21125
21126 }
21127
21128 var _rootContainerInstance = getRootHostContainer();
21129
21130 var _currentHostContext = getHostContext();
21131
21132 var _wasHydrated2 = popHydrationState(workInProgress);
21133
21134 if (_wasHydrated2) {
21135 if (prepareToHydrateHostTextInstance(workInProgress)) {
21136 markUpdate(workInProgress);
21137 }
21138 } else {
21139 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
21140 }
21141 }
21142
21143 break;
21144 }
21145
21146 case ForwardRef:
21147 break;
21148
21149 case SuspenseComponent:
21150 {
21151 popSuspenseContext(workInProgress);
21152 var nextState = workInProgress.memoizedState;
21153
21154 if (enableSuspenseServerRenderer) {
21155 if (nextState !== null && nextState.dehydrated !== null) {
21156 if (current === null) {
21157 var _wasHydrated3 = popHydrationState(workInProgress);
21158
21159 if (!_wasHydrated3) {
21160 {
21161 throw Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.");
21162 }
21163 }
21164
21165 prepareToHydrateHostSuspenseInstance(workInProgress);
21166
21167 if (enableSchedulerTracing) {
21168 markSpawnedWork(Never);
21169 }
21170
21171 return null;
21172 } else {
21173 // We should never have been in a hydration state if we didn't have a current.
21174 // However, in some of those paths, we might have reentered a hydration state
21175 // and then we might be inside a hydration state. In that case, we'll need to
21176 // exit out of it.
21177 resetHydrationState();
21178
21179 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
21180 // This boundary did not suspend so it's now hydrated and unsuspended.
21181 workInProgress.memoizedState = null;
21182 } // If nothing suspended, we need to schedule an effect to mark this boundary
21183 // as having hydrated so events know that they're free be invoked.
21184 // It's also a signal to replay events and the suspense callback.
21185 // If something suspended, schedule an effect to attach retry listeners.
21186 // So we might as well always mark this.
21187
21188
21189 workInProgress.effectTag |= Update;
21190 return null;
21191 }
21192 }
21193 }
21194
21195 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
21196 // Something suspended. Re-render with the fallback children.
21197 workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
21198
21199 return workInProgress;
21200 }
21201
21202 var nextDidTimeout = nextState !== null;
21203 var prevDidTimeout = false;
21204
21205 if (current === null) {
21206 if (workInProgress.memoizedProps.fallback !== undefined) {
21207 popHydrationState(workInProgress);
21208 }
21209 } else {
21210 var prevState = current.memoizedState;
21211 prevDidTimeout = prevState !== null;
21212
21213 if (!nextDidTimeout && prevState !== null) {
21214 // We just switched from the fallback to the normal children.
21215 // Delete the fallback.
21216 // TODO: Would it be better to store the fallback fragment on
21217 // the stateNode during the begin phase?
21218 var currentFallbackChild = current.child.sibling;
21219
21220 if (currentFallbackChild !== null) {
21221 // Deletions go at the beginning of the return fiber's effect list
21222 var first = workInProgress.firstEffect;
21223
21224 if (first !== null) {
21225 workInProgress.firstEffect = currentFallbackChild;
21226 currentFallbackChild.nextEffect = first;
21227 } else {
21228 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
21229 currentFallbackChild.nextEffect = null;
21230 }
21231
21232 currentFallbackChild.effectTag = Deletion;
21233 }
21234 }
21235 }
21236
21237 if (nextDidTimeout && !prevDidTimeout) {
21238 // If this subtreee is running in blocking mode we can suspend,
21239 // otherwise we won't suspend.
21240 // TODO: This will still suspend a synchronous tree if anything
21241 // in the concurrent tree already suspended during this render.
21242 // This is a known bug.
21243 if ((workInProgress.mode & BlockingMode) !== NoMode) {
21244 // TODO: Move this back to throwException because this is too late
21245 // if this is a large tree which is common for initial loads. We
21246 // don't know if we should restart a render or not until we get
21247 // this marker, and this is too late.
21248 // If this render already had a ping or lower pri updates,
21249 // and this is the first time we know we're going to suspend we
21250 // should be able to immediately restart from within throwException.
21251 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
21252
21253 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
21254 // If this was in an invisible tree or a new render, then showing
21255 // this boundary is ok.
21256 renderDidSuspend();
21257 } else {
21258 // Otherwise, we're going to have to hide content so we should
21259 // suspend for longer if possible.
21260 renderDidSuspendDelayIfPossible();
21261 }
21262 }
21263 }
21264
21265 if (supportsPersistence) {
21266 // TODO: Only schedule updates if not prevDidTimeout.
21267 if (nextDidTimeout) {
21268 // If this boundary just timed out, schedule an effect to attach a
21269 // retry listener to the proimse. This flag is also used to hide the
21270 // primary children.
21271 workInProgress.effectTag |= Update;
21272 }
21273 }
21274
21275 if (supportsMutation) {
21276 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
21277 if (nextDidTimeout || prevDidTimeout) {
21278 // If this boundary just timed out, schedule an effect to attach a
21279 // retry listener to the proimse. This flag is also used to hide the
21280 // primary children. In mutation mode, we also need the flag to
21281 // *unhide* children that were previously hidden, so check if the
21282 // is currently timed out, too.
21283 workInProgress.effectTag |= Update;
21284 }
21285 }
21286
21287 if (enableSuspenseCallback && workInProgress.updateQueue !== null && workInProgress.memoizedProps.suspenseCallback != null) {
21288 // Always notify the callback
21289 workInProgress.effectTag |= Update;
21290 }
21291
21292 break;
21293 }
21294
21295 case Fragment:
21296 break;
21297
21298 case Mode:
21299 break;
21300
21301 case Profiler:
21302 break;
21303
21304 case HostPortal:
21305 popHostContainer(workInProgress);
21306 updateHostContainer(workInProgress);
21307 break;
21308
21309 case ContextProvider:
21310 // Pop provider fiber
21311 popProvider(workInProgress);
21312 break;
21313
21314 case ContextConsumer:
21315 break;
21316
21317 case MemoComponent:
21318 break;
21319
21320 case IncompleteClassComponent:
21321 {
21322 // Same as class component case. I put it down here so that the tags are
21323 // sequential to ensure this switch is compiled to a jump table.
21324 var _Component = workInProgress.type;
21325
21326 if (isContextProvider(_Component)) {
21327 popContext(workInProgress);
21328 }
21329
21330 break;
21331 }
21332
21333 case SuspenseListComponent:
21334 {
21335 popSuspenseContext(workInProgress);
21336 var renderState = workInProgress.memoizedState;
21337
21338 if (renderState === null) {
21339 // We're running in the default, "independent" mode. We don't do anything
21340 // in this mode.
21341 break;
21342 }
21343
21344 var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
21345 var renderedTail = renderState.rendering;
21346
21347 if (renderedTail === null) {
21348 // We just rendered the head.
21349 if (!didSuspendAlready) {
21350 // This is the first pass. We need to figure out if anything is still
21351 // suspended in the rendered set.
21352 // If new content unsuspended, but there's still some content that
21353 // didn't. Then we need to do a second pass that forces everything
21354 // to keep showing their fallbacks.
21355 // We might be suspended if something in this render pass suspended, or
21356 // something in the previous committed pass suspended. Otherwise,
21357 // there's no chance so we can skip the expensive call to
21358 // findFirstSuspended.
21359 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
21360
21361 if (!cannotBeSuspended) {
21362 var row = workInProgress.child;
21363
21364 while (row !== null) {
21365 var suspended = findFirstSuspended(row);
21366
21367 if (suspended !== null) {
21368 didSuspendAlready = true;
21369 workInProgress.effectTag |= DidCapture;
21370 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
21371 // part of the second pass. In that case nothing will subscribe to
21372 // its thennables. Instead, we'll transfer its thennables to the
21373 // SuspenseList so that it can retry if they resolve.
21374 // There might be multiple of these in the list but since we're
21375 // going to wait for all of them anyway, it doesn't really matter
21376 // which ones gets to ping. In theory we could get clever and keep
21377 // track of how many dependencies remain but it gets tricky because
21378 // in the meantime, we can add/remove/change items and dependencies.
21379 // We might bail out of the loop before finding any but that
21380 // doesn't matter since that means that the other boundaries that
21381 // we did find already has their listeners attached.
21382
21383 var newThennables = suspended.updateQueue;
21384
21385 if (newThennables !== null) {
21386 workInProgress.updateQueue = newThennables;
21387 workInProgress.effectTag |= Update;
21388 } // Rerender the whole list, but this time, we'll force fallbacks
21389 // to stay in place.
21390 // Reset the effect list before doing the second pass since that's now invalid.
21391
21392
21393 if (renderState.lastEffect === null) {
21394 workInProgress.firstEffect = null;
21395 }
21396
21397 workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.
21398
21399 resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
21400 // rerender the children.
21401
21402 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
21403 return workInProgress.child;
21404 }
21405
21406 row = row.sibling;
21407 }
21408 }
21409 } else {
21410 cutOffTailIfNeeded(renderState, false);
21411 } // Next we're going to render the tail.
21412
21413 } else {
21414 // Append the rendered row to the child list.
21415 if (!didSuspendAlready) {
21416 var _suspended = findFirstSuspended(renderedTail);
21417
21418 if (_suspended !== null) {
21419 workInProgress.effectTag |= DidCapture;
21420 didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
21421 // get lost if this row ends up dropped during a second pass.
21422
21423 var _newThennables = _suspended.updateQueue;
21424
21425 if (_newThennables !== null) {
21426 workInProgress.updateQueue = _newThennables;
21427 workInProgress.effectTag |= Update;
21428 }
21429
21430 cutOffTailIfNeeded(renderState, true); // This might have been modified.
21431
21432 if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate) {
21433 // We need to delete the row we just rendered.
21434 // Reset the effect list to what it was before we rendered this
21435 // child. The nested children have already appended themselves.
21436 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
21437
21438 if (lastEffect !== null) {
21439 lastEffect.nextEffect = null;
21440 } // We're done.
21441
21442
21443 return null;
21444 }
21445 } else if (now() > renderState.tailExpiration && renderExpirationTime > Never) {
21446 // We have now passed our CPU deadline and we'll just give up further
21447 // attempts to render the main content and only render fallbacks.
21448 // The assumption is that this is usually faster.
21449 workInProgress.effectTag |= DidCapture;
21450 didSuspendAlready = true;
21451 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
21452 // to get it started back up to attempt the next item. If we can show
21453 // them, then they really have the same priority as this render.
21454 // So we'll pick it back up the very next render pass once we've had
21455 // an opportunity to yield for paint.
21456
21457 var nextPriority = renderExpirationTime - 1;
21458 workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
21459
21460 if (enableSchedulerTracing) {
21461 markSpawnedWork(nextPriority);
21462 }
21463 }
21464 }
21465
21466 if (renderState.isBackwards) {
21467 // The effect list of the backwards tail will have been added
21468 // to the end. This breaks the guarantee that life-cycles fire in
21469 // sibling order but that isn't a strong guarantee promised by React.
21470 // Especially since these might also just pop in during future commits.
21471 // Append to the beginning of the list.
21472 renderedTail.sibling = workInProgress.child;
21473 workInProgress.child = renderedTail;
21474 } else {
21475 var previousSibling = renderState.last;
21476
21477 if (previousSibling !== null) {
21478 previousSibling.sibling = renderedTail;
21479 } else {
21480 workInProgress.child = renderedTail;
21481 }
21482
21483 renderState.last = renderedTail;
21484 }
21485 }
21486
21487 if (renderState.tail !== null) {
21488 // We still have tail rows to render.
21489 if (renderState.tailExpiration === 0) {
21490 // Heuristic for how long we're willing to spend rendering rows
21491 // until we just give up and show what we have so far.
21492 var TAIL_EXPIRATION_TIMEOUT_MS = 500;
21493 renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
21494 } // Pop a row.
21495
21496
21497 var next = renderState.tail;
21498 renderState.rendering = next;
21499 renderState.tail = next.sibling;
21500 renderState.lastEffect = workInProgress.lastEffect;
21501 next.sibling = null; // Restore the context.
21502 // TODO: We can probably just avoid popping it instead and only
21503 // setting it the first time we go from not suspended to suspended.
21504
21505 var suspenseContext = suspenseStackCursor.current;
21506
21507 if (didSuspendAlready) {
21508 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21509 } else {
21510 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21511 }
21512
21513 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
21514
21515 return next;
21516 }
21517
21518 break;
21519 }
21520
21521 case FundamentalComponent:
21522 {
21523 if (enableFundamentalAPI) {
21524 var fundamentalImpl = workInProgress.type.impl;
21525 var fundamentalInstance = workInProgress.stateNode;
21526
21527 if (fundamentalInstance === null) {
21528 var getInitialState = fundamentalImpl.getInitialState;
21529 var fundamentalState;
21530
21531 if (getInitialState !== undefined) {
21532 fundamentalState = getInitialState(newProps);
21533 }
21534
21535 fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(workInProgress, newProps, fundamentalImpl, fundamentalState || {});
21536
21537 var _instance5 = getFundamentalComponentInstance(fundamentalInstance);
21538
21539 fundamentalInstance.instance = _instance5;
21540
21541 if (fundamentalImpl.reconcileChildren === false) {
21542 return null;
21543 }
21544
21545 appendAllChildren(_instance5, workInProgress, false, false);
21546 mountFundamentalComponent(fundamentalInstance);
21547 } else {
21548 // We fire update in commit phase
21549 var prevProps = fundamentalInstance.props;
21550 fundamentalInstance.prevProps = prevProps;
21551 fundamentalInstance.props = newProps;
21552 fundamentalInstance.currentFiber = workInProgress;
21553
21554 if (supportsPersistence) {
21555 var _instance6 = cloneFundamentalInstance(fundamentalInstance);
21556
21557 fundamentalInstance.instance = _instance6;
21558 appendAllChildren(_instance6, workInProgress, false, false);
21559 }
21560
21561 var shouldUpdate = shouldUpdateFundamentalComponent(fundamentalInstance);
21562
21563 if (shouldUpdate) {
21564 markUpdate(workInProgress);
21565 }
21566 }
21567 }
21568
21569 break;
21570 }
21571
21572 case ScopeComponent:
21573 {
21574 if (enableScopeAPI) {
21575 if (current === null) {
21576 var _type3 = workInProgress.type;
21577 var scopeInstance = {
21578 fiber: workInProgress,
21579 methods: null
21580 };
21581 workInProgress.stateNode = scopeInstance;
21582 scopeInstance.methods = createScopeMethods(_type3, scopeInstance);
21583
21584 if (enableFlareAPI) {
21585 var _listeners2 = newProps.listeners;
21586
21587 if (_listeners2 != null) {
21588 var _rootContainerInstance2 = getRootHostContainer();
21589
21590 updateEventListeners(_listeners2, workInProgress, _rootContainerInstance2);
21591 }
21592 }
21593
21594 if (workInProgress.ref !== null) {
21595 markRef$1(workInProgress);
21596 markUpdate(workInProgress);
21597 }
21598 } else {
21599 if (enableFlareAPI) {
21600 var _prevListeners = current.memoizedProps.listeners;
21601 var _nextListeners = newProps.listeners;
21602
21603 if (_prevListeners !== _nextListeners || workInProgress.ref !== null) {
21604 markUpdate(workInProgress);
21605 }
21606 } else {
21607 if (workInProgress.ref !== null) {
21608 markUpdate(workInProgress);
21609 }
21610 }
21611
21612 if (current.ref !== workInProgress.ref) {
21613 markRef$1(workInProgress);
21614 }
21615 }
21616 }
21617
21618 break;
21619 }
21620
21621 default:
21622 {
21623 {
21624 throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
21625 }
21626 }
21627
21628 }
21629
21630 return null;
21631}
21632
21633function unwindWork(workInProgress, renderExpirationTime) {
21634 switch (workInProgress.tag) {
21635 case ClassComponent:
21636 {
21637 var Component = workInProgress.type;
21638
21639 if (isContextProvider(Component)) {
21640 popContext(workInProgress);
21641 }
21642
21643 var effectTag = workInProgress.effectTag;
21644
21645 if (effectTag & ShouldCapture) {
21646 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
21647 return workInProgress;
21648 }
21649
21650 return null;
21651 }
21652
21653 case HostRoot:
21654 {
21655 popHostContainer(workInProgress);
21656 popTopLevelContextObject(workInProgress);
21657 var _effectTag = workInProgress.effectTag;
21658
21659 if (!((_effectTag & DidCapture) === NoEffect)) {
21660 {
21661 throw Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue.");
21662 }
21663 }
21664
21665 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
21666 return workInProgress;
21667 }
21668
21669 case HostComponent:
21670 {
21671 // TODO: popHydrationState
21672 popHostContext(workInProgress);
21673 return null;
21674 }
21675
21676 case SuspenseComponent:
21677 {
21678 popSuspenseContext(workInProgress);
21679
21680 if (enableSuspenseServerRenderer) {
21681 var suspenseState = workInProgress.memoizedState;
21682
21683 if (suspenseState !== null && suspenseState.dehydrated !== null) {
21684 if (!(workInProgress.alternate !== null)) {
21685 {
21686 throw Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue.");
21687 }
21688 }
21689
21690 resetHydrationState();
21691 }
21692 }
21693
21694 var _effectTag2 = workInProgress.effectTag;
21695
21696 if (_effectTag2 & ShouldCapture) {
21697 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
21698
21699 return workInProgress;
21700 }
21701
21702 return null;
21703 }
21704
21705 case SuspenseListComponent:
21706 {
21707 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
21708 // caught by a nested boundary. If not, it should bubble through.
21709
21710 return null;
21711 }
21712
21713 case HostPortal:
21714 popHostContainer(workInProgress);
21715 return null;
21716
21717 case ContextProvider:
21718 popProvider(workInProgress);
21719 return null;
21720
21721 default:
21722 return null;
21723 }
21724}
21725
21726function unwindInterruptedWork(interruptedWork) {
21727 switch (interruptedWork.tag) {
21728 case ClassComponent:
21729 {
21730 var childContextTypes = interruptedWork.type.childContextTypes;
21731
21732 if (childContextTypes !== null && childContextTypes !== undefined) {
21733 popContext(interruptedWork);
21734 }
21735
21736 break;
21737 }
21738
21739 case HostRoot:
21740 {
21741 popHostContainer(interruptedWork);
21742 popTopLevelContextObject(interruptedWork);
21743 break;
21744 }
21745
21746 case HostComponent:
21747 {
21748 popHostContext(interruptedWork);
21749 break;
21750 }
21751
21752 case HostPortal:
21753 popHostContainer(interruptedWork);
21754 break;
21755
21756 case SuspenseComponent:
21757 popSuspenseContext(interruptedWork);
21758 break;
21759
21760 case SuspenseListComponent:
21761 popSuspenseContext(interruptedWork);
21762 break;
21763
21764 case ContextProvider:
21765 popProvider(interruptedWork);
21766 break;
21767
21768 default:
21769 break;
21770 }
21771}
21772
21773function createCapturedValue(value, source) {
21774 // If the value is an error, call this function immediately after it is thrown
21775 // so the stack is accurate.
21776 return {
21777 value: value,
21778 source: source,
21779 stack: getStackByFiberInDevAndProd(source)
21780 };
21781}
21782
21783// This module is forked in different environments.
21784// By default, return `true` to log errors to the console.
21785// Forks can return `false` if this isn't desirable.
21786function showErrorDialog(capturedError) {
21787 return true;
21788}
21789
21790function logCapturedError(capturedError) {
21791 var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging.
21792 // This enables renderers like ReactNative to better manage redbox behavior.
21793
21794 if (logError === false) {
21795 return;
21796 }
21797
21798 var error = capturedError.error;
21799
21800 {
21801 var componentName = capturedError.componentName,
21802 componentStack = capturedError.componentStack,
21803 errorBoundaryName = capturedError.errorBoundaryName,
21804 errorBoundaryFound = capturedError.errorBoundaryFound,
21805 willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
21806 // `preventDefault()` in window `error` handler.
21807 // We record this information as an expando on the error.
21808
21809 if (error != null && error._suppressLogging) {
21810 if (errorBoundaryFound && willRetry) {
21811 // The error is recoverable and was silenced.
21812 // Ignore it and don't print the stack addendum.
21813 // This is handy for testing error boundaries without noise.
21814 return;
21815 } // The error is fatal. Since the silencing might have
21816 // been accidental, we'll surface it anyway.
21817 // However, the browser would have silenced the original error
21818 // so we'll print it first, and then print the stack addendum.
21819
21820
21821 console.error(error); // For a more detailed description of this block, see:
21822 // https://github.com/facebook/react/pull/13384
21823 }
21824
21825 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
21826 var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
21827
21828 if (errorBoundaryFound && errorBoundaryName) {
21829 if (willRetry) {
21830 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
21831 } else {
21832 errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
21833 }
21834 } else {
21835 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.';
21836 }
21837
21838 var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
21839 // We don't include the original error message and JS stack because the browser
21840 // has already printed it. Even if the application swallows the error, it is still
21841 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
21842
21843 console.error(combinedMessage);
21844 }
21845}
21846
21847var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
21848
21849{
21850 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
21851}
21852
21853var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
21854function logError(boundary, errorInfo) {
21855 var source = errorInfo.source;
21856 var stack = errorInfo.stack;
21857
21858 if (stack === null && source !== null) {
21859 stack = getStackByFiberInDevAndProd(source);
21860 }
21861
21862 var capturedError = {
21863 componentName: source !== null ? getComponentName(source.type) : null,
21864 componentStack: stack !== null ? stack : '',
21865 error: errorInfo.value,
21866 errorBoundary: null,
21867 errorBoundaryName: null,
21868 errorBoundaryFound: false,
21869 willRetry: false
21870 };
21871
21872 if (boundary !== null && boundary.tag === ClassComponent) {
21873 capturedError.errorBoundary = boundary.stateNode;
21874 capturedError.errorBoundaryName = getComponentName(boundary.type);
21875 capturedError.errorBoundaryFound = true;
21876 capturedError.willRetry = true;
21877 }
21878
21879 try {
21880 logCapturedError(capturedError);
21881 } catch (e) {
21882 // This method must not throw, or React internal state will get messed up.
21883 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
21884 // we want to report this error outside of the normal stack as a last resort.
21885 // https://github.com/facebook/react/issues/13188
21886 setTimeout(function () {
21887 throw e;
21888 });
21889 }
21890}
21891
21892var callComponentWillUnmountWithTimer = function (current$$1, instance) {
21893 startPhaseTimer(current$$1, 'componentWillUnmount');
21894 instance.props = current$$1.memoizedProps;
21895 instance.state = current$$1.memoizedState;
21896 instance.componentWillUnmount();
21897 stopPhaseTimer();
21898}; // Capture errors so they don't interrupt unmounting.
21899
21900
21901function safelyCallComponentWillUnmount(current$$1, instance) {
21902 {
21903 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
21904
21905 if (hasCaughtError()) {
21906 var unmountError = clearCaughtError();
21907 captureCommitPhaseError(current$$1, unmountError);
21908 }
21909 }
21910}
21911
21912function safelyDetachRef(current$$1) {
21913 var ref = current$$1.ref;
21914
21915 if (ref !== null) {
21916 if (typeof ref === 'function') {
21917 {
21918 invokeGuardedCallback(null, ref, null, null);
21919
21920 if (hasCaughtError()) {
21921 var refError = clearCaughtError();
21922 captureCommitPhaseError(current$$1, refError);
21923 }
21924 }
21925 } else {
21926 ref.current = null;
21927 }
21928 }
21929}
21930
21931function safelyCallDestroy(current$$1, destroy) {
21932 {
21933 invokeGuardedCallback(null, destroy, null);
21934
21935 if (hasCaughtError()) {
21936 var error = clearCaughtError();
21937 captureCommitPhaseError(current$$1, error);
21938 }
21939 }
21940}
21941
21942function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
21943 switch (finishedWork.tag) {
21944 case FunctionComponent:
21945 case ForwardRef:
21946 case SimpleMemoComponent:
21947 {
21948 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
21949 return;
21950 }
21951
21952 case ClassComponent:
21953 {
21954 if (finishedWork.effectTag & Snapshot) {
21955 if (current$$1 !== null) {
21956 var prevProps = current$$1.memoizedProps;
21957 var prevState = current$$1.memoizedState;
21958 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
21959 var instance = finishedWork.stateNode; // We could update instance props and state here,
21960 // but instead we rely on them being set during last render.
21961 // TODO: revisit this when we implement resuming.
21962
21963 {
21964 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
21965 !(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;
21966 !(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;
21967 }
21968 }
21969
21970 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
21971
21972 {
21973 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
21974
21975 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
21976 didWarnSet.add(finishedWork.type);
21977 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
21978 }
21979 }
21980
21981 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
21982 stopPhaseTimer();
21983 }
21984 }
21985
21986 return;
21987 }
21988
21989 case HostRoot:
21990 case HostComponent:
21991 case HostText:
21992 case HostPortal:
21993 case IncompleteClassComponent:
21994 // Nothing to do for these component types
21995 return;
21996
21997 default:
21998 {
21999 {
22000 {
22001 throw 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.");
22002 }
22003 }
22004 }
22005 }
22006}
22007
22008function commitHookEffectList(unmountTag, mountTag, finishedWork) {
22009 var updateQueue = finishedWork.updateQueue;
22010 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
22011
22012 if (lastEffect !== null) {
22013 var firstEffect = lastEffect.next;
22014 var effect = firstEffect;
22015
22016 do {
22017 if ((effect.tag & unmountTag) !== NoEffect$1) {
22018 // Unmount
22019 var destroy = effect.destroy;
22020 effect.destroy = undefined;
22021
22022 if (destroy !== undefined) {
22023 destroy();
22024 }
22025 }
22026
22027 if ((effect.tag & mountTag) !== NoEffect$1) {
22028 // Mount
22029 var create = effect.create;
22030 effect.destroy = create();
22031
22032 {
22033 var _destroy = effect.destroy;
22034
22035 if (_destroy !== undefined && typeof _destroy !== 'function') {
22036 var addendum = void 0;
22037
22038 if (_destroy === null) {
22039 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
22040 } else if (typeof _destroy.then === 'function') {
22041 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';
22042 } else {
22043 addendum = ' You returned: ' + _destroy;
22044 }
22045
22046 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
22047 }
22048 }
22049 }
22050
22051 effect = effect.next;
22052 } while (effect !== firstEffect);
22053 }
22054}
22055
22056function commitPassiveHookEffects(finishedWork) {
22057 if ((finishedWork.effectTag & Passive) !== NoEffect) {
22058 switch (finishedWork.tag) {
22059 case FunctionComponent:
22060 case ForwardRef:
22061 case SimpleMemoComponent:
22062 {
22063 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
22064 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
22065 break;
22066 }
22067
22068 default:
22069 break;
22070 }
22071 }
22072}
22073
22074function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
22075 switch (finishedWork.tag) {
22076 case FunctionComponent:
22077 case ForwardRef:
22078 case SimpleMemoComponent:
22079 {
22080 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
22081 break;
22082 }
22083
22084 case ClassComponent:
22085 {
22086 var instance = finishedWork.stateNode;
22087
22088 if (finishedWork.effectTag & Update) {
22089 if (current$$1 === null) {
22090 startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
22091 // but instead we rely on them being set during last render.
22092 // TODO: revisit this when we implement resuming.
22093
22094 {
22095 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22096 !(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;
22097 !(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;
22098 }
22099 }
22100
22101 instance.componentDidMount();
22102 stopPhaseTimer();
22103 } else {
22104 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
22105 var prevState = current$$1.memoizedState;
22106 startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
22107 // but instead we rely on them being set during last render.
22108 // TODO: revisit this when we implement resuming.
22109
22110 {
22111 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22112 !(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;
22113 !(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;
22114 }
22115 }
22116
22117 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
22118 stopPhaseTimer();
22119 }
22120 }
22121
22122 var updateQueue = finishedWork.updateQueue;
22123
22124 if (updateQueue !== null) {
22125 {
22126 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22127 !(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;
22128 !(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;
22129 }
22130 } // We could update instance props and state here,
22131 // but instead we rely on them being set during last render.
22132 // TODO: revisit this when we implement resuming.
22133
22134
22135 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
22136 }
22137
22138 return;
22139 }
22140
22141 case HostRoot:
22142 {
22143 var _updateQueue = finishedWork.updateQueue;
22144
22145 if (_updateQueue !== null) {
22146 var _instance = null;
22147
22148 if (finishedWork.child !== null) {
22149 switch (finishedWork.child.tag) {
22150 case HostComponent:
22151 _instance = getPublicInstance(finishedWork.child.stateNode);
22152 break;
22153
22154 case ClassComponent:
22155 _instance = finishedWork.child.stateNode;
22156 break;
22157 }
22158 }
22159
22160 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
22161 }
22162
22163 return;
22164 }
22165
22166 case HostComponent:
22167 {
22168 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
22169 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
22170 // These effects should only be committed when components are first mounted,
22171 // aka when there is no current/alternate.
22172
22173 if (current$$1 === null && finishedWork.effectTag & Update) {
22174 var type = finishedWork.type;
22175 var props = finishedWork.memoizedProps;
22176 commitMount(_instance2, type, props, finishedWork);
22177 }
22178
22179 return;
22180 }
22181
22182 case HostText:
22183 {
22184 // We have no life-cycles associated with text.
22185 return;
22186 }
22187
22188 case HostPortal:
22189 {
22190 // We have no life-cycles associated with portals.
22191 return;
22192 }
22193
22194 case Profiler:
22195 {
22196 if (enableProfilerTimer) {
22197 var onRender = finishedWork.memoizedProps.onRender;
22198
22199 if (typeof onRender === 'function') {
22200 if (enableSchedulerTracing) {
22201 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
22202 } else {
22203 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
22204 }
22205 }
22206 }
22207
22208 return;
22209 }
22210
22211 case SuspenseComponent:
22212 {
22213 commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
22214 return;
22215 }
22216
22217 case SuspenseListComponent:
22218 case IncompleteClassComponent:
22219 case FundamentalComponent:
22220 case ScopeComponent:
22221 return;
22222
22223 default:
22224 {
22225 {
22226 {
22227 throw 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.");
22228 }
22229 }
22230 }
22231 }
22232}
22233
22234function hideOrUnhideAllChildren(finishedWork, isHidden) {
22235 if (supportsMutation) {
22236 // We only have the top Fiber that was inserted but we need to recurse down its
22237 // children to find all the terminal nodes.
22238 var node = finishedWork;
22239
22240 while (true) {
22241 if (node.tag === HostComponent) {
22242 var instance = node.stateNode;
22243
22244 if (isHidden) {
22245 hideInstance(instance);
22246 } else {
22247 unhideInstance(node.stateNode, node.memoizedProps);
22248 }
22249 } else if (node.tag === HostText) {
22250 var _instance3 = node.stateNode;
22251
22252 if (isHidden) {
22253 hideTextInstance(_instance3);
22254 } else {
22255 unhideTextInstance(_instance3, node.memoizedProps);
22256 }
22257 } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
22258 // Found a nested Suspense component that timed out. Skip over the
22259 // primary child fragment, which should remain hidden.
22260 var fallbackChildFragment = node.child.sibling;
22261 fallbackChildFragment.return = node;
22262 node = fallbackChildFragment;
22263 continue;
22264 } else if (node.child !== null) {
22265 node.child.return = node;
22266 node = node.child;
22267 continue;
22268 }
22269
22270 if (node === finishedWork) {
22271 return;
22272 }
22273
22274 while (node.sibling === null) {
22275 if (node.return === null || node.return === finishedWork) {
22276 return;
22277 }
22278
22279 node = node.return;
22280 }
22281
22282 node.sibling.return = node.return;
22283 node = node.sibling;
22284 }
22285 }
22286}
22287
22288function commitAttachRef(finishedWork) {
22289 var ref = finishedWork.ref;
22290
22291 if (ref !== null) {
22292 var instance = finishedWork.stateNode;
22293 var instanceToUse;
22294
22295 switch (finishedWork.tag) {
22296 case HostComponent:
22297 instanceToUse = getPublicInstance(instance);
22298 break;
22299
22300 default:
22301 instanceToUse = instance;
22302 } // Moved outside to ensure DCE works with this flag
22303
22304
22305 if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
22306 instanceToUse = instance.methods;
22307 }
22308
22309 if (typeof ref === 'function') {
22310 ref(instanceToUse);
22311 } else {
22312 {
22313 if (!ref.hasOwnProperty('current')) {
22314 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
22315 }
22316 }
22317
22318 ref.current = instanceToUse;
22319 }
22320 }
22321}
22322
22323function commitDetachRef(current$$1) {
22324 var currentRef = current$$1.ref;
22325
22326 if (currentRef !== null) {
22327 if (typeof currentRef === 'function') {
22328 currentRef(null);
22329 } else {
22330 currentRef.current = null;
22331 }
22332 }
22333} // User-originating errors (lifecycles and refs) should not interrupt
22334// deletion, so don't let them throw. Host-originating errors should
22335// interrupt deletion, so it's okay
22336
22337
22338function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) {
22339 onCommitUnmount(current$$1);
22340
22341 switch (current$$1.tag) {
22342 case FunctionComponent:
22343 case ForwardRef:
22344 case MemoComponent:
22345 case SimpleMemoComponent:
22346 {
22347 var updateQueue = current$$1.updateQueue;
22348
22349 if (updateQueue !== null) {
22350 var lastEffect = updateQueue.lastEffect;
22351
22352 if (lastEffect !== null) {
22353 var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive
22354 // effect hook is called during the synchronous commit phase. This is
22355 // a concession to implementation complexity. Calling it in the
22356 // passive effect phase (like they usually are, when dependencies
22357 // change during an update) would require either traversing the
22358 // children of the deleted fiber again, or including unmount effects
22359 // as part of the fiber effect list.
22360 //
22361 // Because this is during the sync commit phase, we need to change
22362 // the priority.
22363 //
22364 // TODO: Reconsider this implementation trade off.
22365
22366 var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
22367 runWithPriority$2(priorityLevel, function () {
22368 var effect = firstEffect;
22369
22370 do {
22371 var destroy = effect.destroy;
22372
22373 if (destroy !== undefined) {
22374 safelyCallDestroy(current$$1, destroy);
22375 }
22376
22377 effect = effect.next;
22378 } while (effect !== firstEffect);
22379 });
22380 }
22381 }
22382
22383 break;
22384 }
22385
22386 case ClassComponent:
22387 {
22388 safelyDetachRef(current$$1);
22389 var instance = current$$1.stateNode;
22390
22391 if (typeof instance.componentWillUnmount === 'function') {
22392 safelyCallComponentWillUnmount(current$$1, instance);
22393 }
22394
22395 return;
22396 }
22397
22398 case HostComponent:
22399 {
22400 if (enableFlareAPI) {
22401 var dependencies = current$$1.dependencies;
22402
22403 if (dependencies !== null) {
22404 var respondersMap = dependencies.responders;
22405
22406 if (respondersMap !== null) {
22407 var responderInstances = Array.from(respondersMap.values());
22408
22409 for (var i = 0, length = responderInstances.length; i < length; i++) {
22410 var responderInstance = responderInstances[i];
22411 unmountResponderInstance(responderInstance);
22412 }
22413
22414 dependencies.responders = null;
22415 }
22416 }
22417 }
22418
22419 safelyDetachRef(current$$1);
22420 return;
22421 }
22422
22423 case HostPortal:
22424 {
22425 // TODO: this is recursive.
22426 // We are also not using this parent because
22427 // the portal will get pushed immediately.
22428 if (supportsMutation) {
22429 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22430 } else if (supportsPersistence) {
22431 emptyPortalContainer(current$$1);
22432 }
22433
22434 return;
22435 }
22436
22437 case FundamentalComponent:
22438 {
22439 if (enableFundamentalAPI) {
22440 var fundamentalInstance = current$$1.stateNode;
22441
22442 if (fundamentalInstance !== null) {
22443 unmountFundamentalComponent(fundamentalInstance);
22444 current$$1.stateNode = null;
22445 }
22446 }
22447
22448 return;
22449 }
22450
22451 case DehydratedFragment:
22452 {
22453 if (enableSuspenseCallback) {
22454 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22455
22456 if (hydrationCallbacks !== null) {
22457 var onDeleted = hydrationCallbacks.onDeleted;
22458
22459 if (onDeleted) {
22460 onDeleted(current$$1.stateNode);
22461 }
22462 }
22463 }
22464
22465 return;
22466 }
22467
22468 case ScopeComponent:
22469 {
22470 if (enableScopeAPI) {
22471 safelyDetachRef(current$$1);
22472 }
22473 }
22474 }
22475}
22476
22477function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
22478 // While we're inside a removed host node we don't want to call
22479 // removeChild on the inner nodes because they're removed by the top
22480 // call anyway. We also want to call componentWillUnmount on all
22481 // composites before this host node is removed from the tree. Therefore
22482 // we do an inner loop while we're still inside the host node.
22483 var node = root;
22484
22485 while (true) {
22486 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
22487 // Skip portals because commitUnmount() currently visits them recursively.
22488
22489 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
22490 // If we don't use mutation we drill down into portals here instead.
22491 !supportsMutation || node.tag !== HostPortal)) {
22492 node.child.return = node;
22493 node = node.child;
22494 continue;
22495 }
22496
22497 if (node === root) {
22498 return;
22499 }
22500
22501 while (node.sibling === null) {
22502 if (node.return === null || node.return === root) {
22503 return;
22504 }
22505
22506 node = node.return;
22507 }
22508
22509 node.sibling.return = node.return;
22510 node = node.sibling;
22511 }
22512}
22513
22514function detachFiber(current$$1) {
22515 var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
22516 // should clear the child pointer of the parent alternate to let this
22517 // get GC:ed but we don't know which for sure which parent is the current
22518 // one so we'll settle for GC:ing the subtree of this child. This child
22519 // itself will be GC:ed when the parent updates the next time.
22520
22521 current$$1.return = null;
22522 current$$1.child = null;
22523 current$$1.memoizedState = null;
22524 current$$1.updateQueue = null;
22525 current$$1.dependencies = null;
22526 current$$1.alternate = null;
22527 current$$1.firstEffect = null;
22528 current$$1.lastEffect = null;
22529 current$$1.pendingProps = null;
22530 current$$1.memoizedProps = null;
22531
22532 if (alternate !== null) {
22533 detachFiber(alternate);
22534 }
22535}
22536
22537function emptyPortalContainer(current$$1) {
22538 if (!supportsPersistence) {
22539 return;
22540 }
22541
22542 var portal = current$$1.stateNode;
22543 var containerInfo = portal.containerInfo;
22544 var emptyChildSet = createContainerChildSet(containerInfo);
22545 replaceContainerChildren(containerInfo, emptyChildSet);
22546}
22547
22548function commitContainer(finishedWork) {
22549 if (!supportsPersistence) {
22550 return;
22551 }
22552
22553 switch (finishedWork.tag) {
22554 case ClassComponent:
22555 case HostComponent:
22556 case HostText:
22557 case FundamentalComponent:
22558 {
22559 return;
22560 }
22561
22562 case HostRoot:
22563 case HostPortal:
22564 {
22565 var portalOrRoot = finishedWork.stateNode;
22566 var containerInfo = portalOrRoot.containerInfo,
22567 pendingChildren = portalOrRoot.pendingChildren;
22568 replaceContainerChildren(containerInfo, pendingChildren);
22569 return;
22570 }
22571
22572 default:
22573 {
22574 {
22575 {
22576 throw 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.");
22577 }
22578 }
22579 }
22580 }
22581}
22582
22583function getHostParentFiber(fiber) {
22584 var parent = fiber.return;
22585
22586 while (parent !== null) {
22587 if (isHostParent(parent)) {
22588 return parent;
22589 }
22590
22591 parent = parent.return;
22592 }
22593
22594 {
22595 {
22596 throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
22597 }
22598 }
22599}
22600
22601function isHostParent(fiber) {
22602 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
22603}
22604
22605function getHostSibling(fiber) {
22606 // We're going to search forward into the tree until we find a sibling host
22607 // node. Unfortunately, if multiple insertions are done in a row we have to
22608 // search past them. This leads to exponential search for the next sibling.
22609 // TODO: Find a more efficient way to do this.
22610 var node = fiber;
22611
22612 siblings: while (true) {
22613 // If we didn't find anything, let's try the next sibling.
22614 while (node.sibling === null) {
22615 if (node.return === null || isHostParent(node.return)) {
22616 // If we pop out of the root or hit the parent the fiber we are the
22617 // last sibling.
22618 return null;
22619 }
22620
22621 node = node.return;
22622 }
22623
22624 node.sibling.return = node.return;
22625 node = node.sibling;
22626
22627 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
22628 // If it is not host node and, we might have a host node inside it.
22629 // Try to search down until we find one.
22630 if (node.effectTag & Placement) {
22631 // If we don't have a child, try the siblings instead.
22632 continue siblings;
22633 } // If we don't have a child, try the siblings instead.
22634 // We also skip portals because they are not part of this host tree.
22635
22636
22637 if (node.child === null || node.tag === HostPortal) {
22638 continue siblings;
22639 } else {
22640 node.child.return = node;
22641 node = node.child;
22642 }
22643 } // Check if this host node is stable or about to be placed.
22644
22645
22646 if (!(node.effectTag & Placement)) {
22647 // Found it!
22648 return node.stateNode;
22649 }
22650 }
22651}
22652
22653function commitPlacement(finishedWork) {
22654 if (!supportsMutation) {
22655 return;
22656 } // Recursively insert all host nodes into the parent.
22657
22658
22659 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
22660
22661 var parent;
22662 var isContainer;
22663 var parentStateNode = parentFiber.stateNode;
22664
22665 switch (parentFiber.tag) {
22666 case HostComponent:
22667 parent = parentStateNode;
22668 isContainer = false;
22669 break;
22670
22671 case HostRoot:
22672 parent = parentStateNode.containerInfo;
22673 isContainer = true;
22674 break;
22675
22676 case HostPortal:
22677 parent = parentStateNode.containerInfo;
22678 isContainer = true;
22679 break;
22680
22681 case FundamentalComponent:
22682 if (enableFundamentalAPI) {
22683 parent = parentStateNode.instance;
22684 isContainer = false;
22685 }
22686
22687 // eslint-disable-next-line-no-fallthrough
22688
22689 default:
22690 {
22691 {
22692 throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
22693 }
22694 }
22695
22696 }
22697
22698 if (parentFiber.effectTag & ContentReset) {
22699 // Reset the text content of the parent before doing any insertions
22700 resetTextContent(parent); // Clear ContentReset from the effect tag
22701
22702 parentFiber.effectTag &= ~ContentReset;
22703 }
22704
22705 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
22706 // children to find all the terminal nodes.
22707
22708 var node = finishedWork;
22709
22710 while (true) {
22711 var isHost = node.tag === HostComponent || node.tag === HostText;
22712
22713 if (isHost || enableFundamentalAPI && node.tag === FundamentalComponent) {
22714 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
22715
22716 if (before) {
22717 if (isContainer) {
22718 insertInContainerBefore(parent, stateNode, before);
22719 } else {
22720 insertBefore(parent, stateNode, before);
22721 }
22722 } else {
22723 if (isContainer) {
22724 appendChildToContainer(parent, stateNode);
22725 } else {
22726 appendChild(parent, stateNode);
22727 }
22728 }
22729 } else if (node.tag === HostPortal) {// If the insertion itself is a portal, then we don't want to traverse
22730 // down its children. Instead, we'll get insertions from each child in
22731 // the portal directly.
22732 } else if (node.child !== null) {
22733 node.child.return = node;
22734 node = node.child;
22735 continue;
22736 }
22737
22738 if (node === finishedWork) {
22739 return;
22740 }
22741
22742 while (node.sibling === null) {
22743 if (node.return === null || node.return === finishedWork) {
22744 return;
22745 }
22746
22747 node = node.return;
22748 }
22749
22750 node.sibling.return = node.return;
22751 node = node.sibling;
22752 }
22753}
22754
22755function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) {
22756 // We only have the top Fiber that was deleted but we need to recurse down its
22757 // children to find all the terminal nodes.
22758 var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not
22759 // currentParentIsValid.
22760
22761 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
22762
22763 var currentParent;
22764 var currentParentIsContainer;
22765
22766 while (true) {
22767 if (!currentParentIsValid) {
22768 var parent = node.return;
22769
22770 findParent: while (true) {
22771 if (!(parent !== null)) {
22772 {
22773 throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
22774 }
22775 }
22776
22777 var parentStateNode = parent.stateNode;
22778
22779 switch (parent.tag) {
22780 case HostComponent:
22781 currentParent = parentStateNode;
22782 currentParentIsContainer = false;
22783 break findParent;
22784
22785 case HostRoot:
22786 currentParent = parentStateNode.containerInfo;
22787 currentParentIsContainer = true;
22788 break findParent;
22789
22790 case HostPortal:
22791 currentParent = parentStateNode.containerInfo;
22792 currentParentIsContainer = true;
22793 break findParent;
22794
22795 case FundamentalComponent:
22796 if (enableFundamentalAPI) {
22797 currentParent = parentStateNode.instance;
22798 currentParentIsContainer = false;
22799 }
22800
22801 }
22802
22803 parent = parent.return;
22804 }
22805
22806 currentParentIsValid = true;
22807 }
22808
22809 if (node.tag === HostComponent || node.tag === HostText) {
22810 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22811 // node from the tree.
22812
22813 if (currentParentIsContainer) {
22814 removeChildFromContainer(currentParent, node.stateNode);
22815 } else {
22816 removeChild(currentParent, node.stateNode);
22817 } // Don't visit children because we already visited them.
22818
22819 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
22820 var fundamentalNode = node.stateNode.instance;
22821 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22822 // node from the tree.
22823
22824 if (currentParentIsContainer) {
22825 removeChildFromContainer(currentParent, fundamentalNode);
22826 } else {
22827 removeChild(currentParent, fundamentalNode);
22828 }
22829 } else if (enableSuspenseServerRenderer && node.tag === DehydratedFragment) {
22830 if (enableSuspenseCallback) {
22831 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22832
22833 if (hydrationCallbacks !== null) {
22834 var onDeleted = hydrationCallbacks.onDeleted;
22835
22836 if (onDeleted) {
22837 onDeleted(node.stateNode);
22838 }
22839 }
22840 } // Delete the dehydrated suspense boundary and all of its content.
22841
22842
22843 if (currentParentIsContainer) {
22844 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
22845 } else {
22846 clearSuspenseBoundary(currentParent, node.stateNode);
22847 }
22848 } else if (node.tag === HostPortal) {
22849 if (node.child !== null) {
22850 // When we go into a portal, it becomes the parent to remove from.
22851 // We will reassign it back when we pop the portal on the way up.
22852 currentParent = node.stateNode.containerInfo;
22853 currentParentIsContainer = true; // Visit children because portals might contain host components.
22854
22855 node.child.return = node;
22856 node = node.child;
22857 continue;
22858 }
22859 } else {
22860 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
22861
22862 if (node.child !== null) {
22863 node.child.return = node;
22864 node = node.child;
22865 continue;
22866 }
22867 }
22868
22869 if (node === current$$1) {
22870 return;
22871 }
22872
22873 while (node.sibling === null) {
22874 if (node.return === null || node.return === current$$1) {
22875 return;
22876 }
22877
22878 node = node.return;
22879
22880 if (node.tag === HostPortal) {
22881 // When we go out of the portal, we need to restore the parent.
22882 // Since we don't keep a stack of them, we will search for it.
22883 currentParentIsValid = false;
22884 }
22885 }
22886
22887 node.sibling.return = node.return;
22888 node = node.sibling;
22889 }
22890}
22891
22892function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) {
22893 if (supportsMutation) {
22894 // Recursively delete all host nodes from the parent.
22895 // Detach refs and call componentWillUnmount() on the whole subtree.
22896 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22897 } else {
22898 // Detach refs and call componentWillUnmount() on the whole subtree.
22899 commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel);
22900 }
22901
22902 detachFiber(current$$1);
22903}
22904
22905function commitWork(current$$1, finishedWork) {
22906 if (!supportsMutation) {
22907 switch (finishedWork.tag) {
22908 case FunctionComponent:
22909 case ForwardRef:
22910 case MemoComponent:
22911 case SimpleMemoComponent:
22912 {
22913 // Note: We currently never use MountMutation, but useLayout uses
22914 // UnmountMutation.
22915 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22916 return;
22917 }
22918
22919 case Profiler:
22920 {
22921 return;
22922 }
22923
22924 case SuspenseComponent:
22925 {
22926 commitSuspenseComponent(finishedWork);
22927 attachSuspenseRetryListeners(finishedWork);
22928 return;
22929 }
22930
22931 case SuspenseListComponent:
22932 {
22933 attachSuspenseRetryListeners(finishedWork);
22934 return;
22935 }
22936
22937 case HostRoot:
22938 {
22939 if (supportsHydration) {
22940 var root = finishedWork.stateNode;
22941
22942 if (root.hydrate) {
22943 // We've just hydrated. No need to hydrate again.
22944 root.hydrate = false;
22945 commitHydratedContainer(root.containerInfo);
22946 }
22947 }
22948
22949 break;
22950 }
22951 }
22952
22953 commitContainer(finishedWork);
22954 return;
22955 }
22956
22957 switch (finishedWork.tag) {
22958 case FunctionComponent:
22959 case ForwardRef:
22960 case MemoComponent:
22961 case SimpleMemoComponent:
22962 {
22963 // Note: We currently never use MountMutation, but useLayout uses
22964 // UnmountMutation.
22965 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
22966 return;
22967 }
22968
22969 case ClassComponent:
22970 {
22971 return;
22972 }
22973
22974 case HostComponent:
22975 {
22976 var instance = finishedWork.stateNode;
22977
22978 if (instance != null) {
22979 // Commit the work prepared earlier.
22980 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
22981 // as the newProps. The updatePayload will contain the real change in
22982 // this case.
22983
22984 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
22985 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
22986
22987 var updatePayload = finishedWork.updateQueue;
22988 finishedWork.updateQueue = null;
22989
22990 if (updatePayload !== null) {
22991 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
22992 }
22993
22994 if (enableFlareAPI) {
22995 var prevListeners = oldProps.listeners;
22996 var nextListeners = newProps.listeners;
22997
22998 if (prevListeners !== nextListeners) {
22999 updateEventListeners(nextListeners, finishedWork, null);
23000 }
23001 }
23002 }
23003
23004 return;
23005 }
23006
23007 case HostText:
23008 {
23009 if (!(finishedWork.stateNode !== null)) {
23010 {
23011 throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
23012 }
23013 }
23014
23015 var textInstance = finishedWork.stateNode;
23016 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23017 // as the newProps. The updatePayload will contain the real change in
23018 // this case.
23019
23020 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
23021 commitTextUpdate(textInstance, oldText, newText);
23022 return;
23023 }
23024
23025 case HostRoot:
23026 {
23027 if (supportsHydration) {
23028 var _root = finishedWork.stateNode;
23029
23030 if (_root.hydrate) {
23031 // We've just hydrated. No need to hydrate again.
23032 _root.hydrate = false;
23033 commitHydratedContainer(_root.containerInfo);
23034 }
23035 }
23036
23037 return;
23038 }
23039
23040 case Profiler:
23041 {
23042 return;
23043 }
23044
23045 case SuspenseComponent:
23046 {
23047 commitSuspenseComponent(finishedWork);
23048 attachSuspenseRetryListeners(finishedWork);
23049 return;
23050 }
23051
23052 case SuspenseListComponent:
23053 {
23054 attachSuspenseRetryListeners(finishedWork);
23055 return;
23056 }
23057
23058 case IncompleteClassComponent:
23059 {
23060 return;
23061 }
23062
23063 case FundamentalComponent:
23064 {
23065 if (enableFundamentalAPI) {
23066 var fundamentalInstance = finishedWork.stateNode;
23067 updateFundamentalComponent(fundamentalInstance);
23068 }
23069
23070 return;
23071 }
23072
23073 case ScopeComponent:
23074 {
23075 if (enableScopeAPI) {
23076 var scopeInstance = finishedWork.stateNode;
23077 scopeInstance.fiber = finishedWork;
23078
23079 if (enableFlareAPI) {
23080 var _newProps = finishedWork.memoizedProps;
23081
23082 var _oldProps = current$$1 !== null ? current$$1.memoizedProps : _newProps;
23083
23084 var _prevListeners = _oldProps.listeners;
23085 var _nextListeners = _newProps.listeners;
23086
23087 if (_prevListeners !== _nextListeners) {
23088 updateEventListeners(_nextListeners, finishedWork, null);
23089 }
23090 }
23091 }
23092
23093 return;
23094 }
23095
23096 default:
23097 {
23098 {
23099 {
23100 throw 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.");
23101 }
23102 }
23103 }
23104 }
23105}
23106
23107function commitSuspenseComponent(finishedWork) {
23108 var newState = finishedWork.memoizedState;
23109 var newDidTimeout;
23110 var primaryChildParent = finishedWork;
23111
23112 if (newState === null) {
23113 newDidTimeout = false;
23114 } else {
23115 newDidTimeout = true;
23116 primaryChildParent = finishedWork.child;
23117 markCommitTimeOfFallback();
23118 }
23119
23120 if (supportsMutation && primaryChildParent !== null) {
23121 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
23122 }
23123
23124 if (enableSuspenseCallback && newState !== null) {
23125 var suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
23126
23127 if (typeof suspenseCallback === 'function') {
23128 var thenables = finishedWork.updateQueue;
23129
23130 if (thenables !== null) {
23131 suspenseCallback(new Set(thenables));
23132 }
23133 } else {
23134 if (suspenseCallback !== undefined) {
23135 warning$1(false, 'Unexpected type for suspenseCallback.');
23136 }
23137 }
23138 }
23139}
23140
23141function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
23142 if (!supportsHydration) {
23143 return;
23144 }
23145
23146 var newState = finishedWork.memoizedState;
23147
23148 if (newState === null) {
23149 var current$$1 = finishedWork.alternate;
23150
23151 if (current$$1 !== null) {
23152 var prevState = current$$1.memoizedState;
23153
23154 if (prevState !== null) {
23155 var suspenseInstance = prevState.dehydrated;
23156
23157 if (suspenseInstance !== null) {
23158 commitHydratedSuspenseInstance(suspenseInstance);
23159
23160 if (enableSuspenseCallback) {
23161 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
23162
23163 if (hydrationCallbacks !== null) {
23164 var onHydrated = hydrationCallbacks.onHydrated;
23165
23166 if (onHydrated) {
23167 onHydrated(suspenseInstance);
23168 }
23169 }
23170 }
23171 }
23172 }
23173 }
23174 }
23175}
23176
23177function attachSuspenseRetryListeners(finishedWork) {
23178 // If this boundary just timed out, then it will have a set of thenables.
23179 // For each thenable, attach a listener so that when it resolves, React
23180 // attempts to re-render the boundary in the primary (pre-timeout) state.
23181 var thenables = finishedWork.updateQueue;
23182
23183 if (thenables !== null) {
23184 finishedWork.updateQueue = null;
23185 var retryCache = finishedWork.stateNode;
23186
23187 if (retryCache === null) {
23188 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
23189 }
23190
23191 thenables.forEach(function (thenable) {
23192 // Memoize using the boundary fiber to prevent redundant listeners.
23193 var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
23194
23195 if (!retryCache.has(thenable)) {
23196 if (enableSchedulerTracing) {
23197 if (thenable.__reactDoNotTraceInteractions !== true) {
23198 retry = tracing.unstable_wrap(retry);
23199 }
23200 }
23201
23202 retryCache.add(thenable);
23203 thenable.then(retry, retry);
23204 }
23205 });
23206 }
23207}
23208
23209function commitResetTextContent(current$$1) {
23210 if (!supportsMutation) {
23211 return;
23212 }
23213
23214 resetTextContent(current$$1.stateNode);
23215}
23216
23217var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
23218
23219function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
23220 var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
23221
23222 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
23223 // being called "element".
23224
23225 update.payload = {
23226 element: null
23227 };
23228 var error = errorInfo.value;
23229
23230 update.callback = function () {
23231 onUncaughtError(error);
23232 logError(fiber, errorInfo);
23233 };
23234
23235 return update;
23236}
23237
23238function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
23239 var update = createUpdate(expirationTime, null);
23240 update.tag = CaptureUpdate;
23241 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
23242
23243 if (typeof getDerivedStateFromError === 'function') {
23244 var error = errorInfo.value;
23245
23246 update.payload = function () {
23247 logError(fiber, errorInfo);
23248 return getDerivedStateFromError(error);
23249 };
23250 }
23251
23252 var inst = fiber.stateNode;
23253
23254 if (inst !== null && typeof inst.componentDidCatch === 'function') {
23255 update.callback = function callback() {
23256 {
23257 markFailedErrorBoundaryForHotReloading(fiber);
23258 }
23259
23260 if (typeof getDerivedStateFromError !== 'function') {
23261 // To preserve the preexisting retry behavior of error boundaries,
23262 // we keep track of which ones already failed during this batch.
23263 // This gets reset before we yield back to the browser.
23264 // TODO: Warn in strict mode if getDerivedStateFromError is
23265 // not defined.
23266 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
23267
23268 logError(fiber, errorInfo);
23269 }
23270
23271 var error = errorInfo.value;
23272 var stack = errorInfo.stack;
23273 this.componentDidCatch(error, {
23274 componentStack: stack !== null ? stack : ''
23275 });
23276
23277 {
23278 if (typeof getDerivedStateFromError !== 'function') {
23279 // If componentDidCatch is the only error boundary method defined,
23280 // then it needs to call setState to recover from errors.
23281 // If no state update is scheduled then the boundary will swallow the error.
23282 !(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;
23283 }
23284 }
23285 };
23286 } else {
23287 update.callback = function () {
23288 markFailedErrorBoundaryForHotReloading(fiber);
23289 };
23290 }
23291
23292 return update;
23293}
23294
23295function attachPingListener(root, renderExpirationTime, thenable) {
23296 // Attach a listener to the promise to "ping" the root and retry. But
23297 // only if one does not already exist for the current render expiration
23298 // time (which acts like a "thread ID" here).
23299 var pingCache = root.pingCache;
23300 var threadIDs;
23301
23302 if (pingCache === null) {
23303 pingCache = root.pingCache = new PossiblyWeakMap$1();
23304 threadIDs = new Set();
23305 pingCache.set(thenable, threadIDs);
23306 } else {
23307 threadIDs = pingCache.get(thenable);
23308
23309 if (threadIDs === undefined) {
23310 threadIDs = new Set();
23311 pingCache.set(thenable, threadIDs);
23312 }
23313 }
23314
23315 if (!threadIDs.has(renderExpirationTime)) {
23316 // Memoize using the thread ID to prevent redundant listeners.
23317 threadIDs.add(renderExpirationTime);
23318 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
23319 thenable.then(ping, ping);
23320 }
23321}
23322
23323function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
23324 // The source fiber did not complete.
23325 sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
23326
23327 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
23328
23329 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
23330 // This is a thenable.
23331 var thenable = value;
23332 checkForWrongSuspensePriorityInDEV(sourceFiber);
23333 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
23334
23335 var _workInProgress = returnFiber;
23336
23337 do {
23338 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
23339 // Found the nearest boundary.
23340 // Stash the promise on the boundary fiber. If the boundary times out, we'll
23341 // attach another listener to flip the boundary back to its normal state.
23342 var thenables = _workInProgress.updateQueue;
23343
23344 if (thenables === null) {
23345 var updateQueue = new Set();
23346 updateQueue.add(thenable);
23347 _workInProgress.updateQueue = updateQueue;
23348 } else {
23349 thenables.add(thenable);
23350 } // If the boundary is outside of blocking mode, we should *not*
23351 // suspend the commit. Pretend as if the suspended component rendered
23352 // null and keep rendering. In the commit phase, we'll schedule a
23353 // subsequent synchronous update to re-render the Suspense.
23354 //
23355 // Note: It doesn't matter whether the component that suspended was
23356 // inside a blocking mode tree. If the Suspense is outside of it, we
23357 // should *not* suspend the commit.
23358
23359
23360 if ((_workInProgress.mode & BlockingMode) === NoMode) {
23361 _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
23362 // But we shouldn't call any lifecycle methods or callbacks. Remove
23363 // all lifecycle effect tags.
23364
23365 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
23366
23367 if (sourceFiber.tag === ClassComponent) {
23368 var currentSourceFiber = sourceFiber.alternate;
23369
23370 if (currentSourceFiber === null) {
23371 // This is a new mount. Change the tag so it's not mistaken for a
23372 // completed class component. For example, we should not call
23373 // componentWillUnmount if it is deleted.
23374 sourceFiber.tag = IncompleteClassComponent;
23375 } else {
23376 // When we try rendering again, we should not reuse the current fiber,
23377 // since it's known to be in an inconsistent state. Use a force update to
23378 // prevent a bail out.
23379 var update = createUpdate(Sync, null);
23380 update.tag = ForceUpdate;
23381 enqueueUpdate(sourceFiber, update);
23382 }
23383 } // The source fiber did not complete. Mark it with Sync priority to
23384 // indicate that it still has pending work.
23385
23386
23387 sourceFiber.expirationTime = Sync; // Exit without suspending.
23388
23389 return;
23390 } // Confirmed that the boundary is in a concurrent mode tree. Continue
23391 // with the normal suspend path.
23392 //
23393 // After this we'll use a set of heuristics to determine whether this
23394 // render pass will run to completion or restart or "suspend" the commit.
23395 // The actual logic for this is spread out in different places.
23396 //
23397 // This first principle is that if we're going to suspend when we complete
23398 // a root, then we should also restart if we get an update or ping that
23399 // might unsuspend it, and vice versa. The only reason to suspend is
23400 // because you think you might want to restart before committing. However,
23401 // it doesn't make sense to restart only while in the period we're suspended.
23402 //
23403 // Restarting too aggressively is also not good because it starves out any
23404 // intermediate loading state. So we use heuristics to determine when.
23405 // Suspense Heuristics
23406 //
23407 // If nothing threw a Promise or all the same fallbacks are already showing,
23408 // then don't suspend/restart.
23409 //
23410 // If this is an initial render of a new tree of Suspense boundaries and
23411 // those trigger a fallback, then don't suspend/restart. We want to ensure
23412 // that we can show the initial loading state as quickly as possible.
23413 //
23414 // If we hit a "Delayed" case, such as when we'd switch from content back into
23415 // a fallback, then we should always suspend/restart. SuspenseConfig applies to
23416 // this case. If none is defined, JND is used instead.
23417 //
23418 // If we're already showing a fallback and it gets "retried", allowing us to show
23419 // another level, but there's still an inner boundary that would show a fallback,
23420 // then we suspend/restart for 500ms since the last time we showed a fallback
23421 // anywhere in the tree. This effectively throttles progressive loading into a
23422 // consistent train of commits. This also gives us an opportunity to restart to
23423 // get to the completed state slightly earlier.
23424 //
23425 // If there's ambiguity due to batching it's resolved in preference of:
23426 // 1) "delayed", 2) "initial render", 3) "retry".
23427 //
23428 // We want to ensure that a "busy" state doesn't get force committed. We want to
23429 // ensure that new initial loading states can commit as soon as possible.
23430
23431
23432 attachPingListener(root, renderExpirationTime, thenable);
23433 _workInProgress.effectTag |= ShouldCapture;
23434 _workInProgress.expirationTime = renderExpirationTime;
23435 return;
23436 } // This boundary already captured during this render. Continue to the next
23437 // boundary.
23438
23439
23440 _workInProgress = _workInProgress.return;
23441 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
23442 // TODO: Use invariant so the message is stripped in prod?
23443
23444
23445 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));
23446 } // We didn't find a boundary that could handle this type of exception. Start
23447 // over and traverse parent path again, this time treating the exception
23448 // as an error.
23449
23450
23451 renderDidError();
23452 value = createCapturedValue(value, sourceFiber);
23453 var workInProgress = returnFiber;
23454
23455 do {
23456 switch (workInProgress.tag) {
23457 case HostRoot:
23458 {
23459 var _errorInfo = value;
23460 workInProgress.effectTag |= ShouldCapture;
23461 workInProgress.expirationTime = renderExpirationTime;
23462
23463 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
23464
23465 enqueueCapturedUpdate(workInProgress, _update);
23466 return;
23467 }
23468
23469 case ClassComponent:
23470 // Capture and retry
23471 var errorInfo = value;
23472 var ctor = workInProgress.type;
23473 var instance = workInProgress.stateNode;
23474
23475 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
23476 workInProgress.effectTag |= ShouldCapture;
23477 workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
23478
23479 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
23480
23481 enqueueCapturedUpdate(workInProgress, _update2);
23482 return;
23483 }
23484
23485 break;
23486
23487 default:
23488 break;
23489 }
23490
23491 workInProgress = workInProgress.return;
23492 } while (workInProgress !== null);
23493}
23494
23495var ceil = Math.ceil;
23496var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
23497var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
23498var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
23499var NoContext =
23500/* */
235010;
23502var BatchedContext =
23503/* */
235041;
23505var EventContext =
23506/* */
235072;
23508var DiscreteEventContext =
23509/* */
235104;
23511var LegacyUnbatchedContext =
23512/* */
235138;
23514var RenderContext =
23515/* */
2351616;
23517var CommitContext =
23518/* */
2351932;
23520var RootIncomplete = 0;
23521var RootFatalErrored = 1;
23522var RootErrored = 2;
23523var RootSuspended = 3;
23524var RootSuspendedWithDelay = 4;
23525var RootCompleted = 5;
23526// Describes where we are in the React execution stack
23527var executionContext = NoContext; // The root we're working on
23528
23529var workInProgressRoot = null; // The fiber we're working on
23530
23531var workInProgress = null; // The expiration time we're rendering
23532
23533var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc.
23534
23535var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
23536
23537var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
23538// This is conceptually a time stamp but expressed in terms of an ExpirationTime
23539// because we deal mostly with expiration times in the hot path, so this avoids
23540// the conversion happening in the hot path.
23541
23542var workInProgressRootLatestProcessedExpirationTime = Sync;
23543var workInProgressRootLatestSuspenseTimeout = Sync;
23544var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
23545// includes unprocessed updates, not work in bailed out children.
23546
23547var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
23548// This flag determines if it might be worthwhile to restart if an opportunity
23549// happens latere.
23550
23551var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
23552// model where we don't commit new loading states in too quick succession.
23553
23554var globalMostRecentFallbackTime = 0;
23555var FALLBACK_THROTTLE_MS = 500;
23556var nextEffect = null;
23557var hasUncaughtError = false;
23558var firstUncaughtError = null;
23559var legacyErrorBoundariesThatAlreadyFailed = null;
23560var rootDoesHavePassiveEffects = false;
23561var rootWithPendingPassiveEffects = null;
23562var pendingPassiveEffectsRenderPriority = NoPriority;
23563var pendingPassiveEffectsExpirationTime = NoWork;
23564var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
23565
23566var NESTED_UPDATE_LIMIT = 50;
23567var nestedUpdateCount = 0;
23568var rootWithNestedUpdates = null;
23569var NESTED_PASSIVE_UPDATE_LIMIT = 50;
23570var nestedPassiveUpdateCount = 0;
23571var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
23572// during the commit phase. This enables them to be traced across components
23573// that spawn new work during render. E.g. hidden boundaries, suspended SSR
23574// hydration or SuspenseList.
23575
23576var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
23577// time). However, if two updates are scheduled within the same event, we
23578// should treat their start times as simultaneous, even if the actual clock
23579// time has advanced between the first and second call.
23580// In other words, because expiration times determine how updates are batched,
23581// we want all updates of like priority that occur within the same event to
23582// receive the same expiration time. Otherwise we get tearing.
23583
23584var currentEventTime = NoWork;
23585function requestCurrentTimeForUpdate() {
23586 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
23587 // We're inside React, so it's fine to read the actual time.
23588 return msToExpirationTime(now());
23589 } // We're not inside React, so we may be in the middle of a browser event.
23590
23591
23592 if (currentEventTime !== NoWork) {
23593 // Use the same start time for all updates until we enter React again.
23594 return currentEventTime;
23595 } // This is the first update since React yielded. Compute a new start time.
23596
23597
23598 currentEventTime = msToExpirationTime(now());
23599 return currentEventTime;
23600}
23601function getCurrentTime() {
23602 return msToExpirationTime(now());
23603}
23604function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
23605 var mode = fiber.mode;
23606
23607 if ((mode & BlockingMode) === NoMode) {
23608 return Sync;
23609 }
23610
23611 var priorityLevel = getCurrentPriorityLevel();
23612
23613 if ((mode & ConcurrentMode) === NoMode) {
23614 return priorityLevel === ImmediatePriority ? Sync : Batched;
23615 }
23616
23617 if ((executionContext & RenderContext) !== NoContext) {
23618 // Use whatever time we're already rendering
23619 // TODO: Should there be a way to opt out, like with `runWithPriority`?
23620 return renderExpirationTime;
23621 }
23622
23623 var expirationTime;
23624
23625 if (suspenseConfig !== null) {
23626 // Compute an expiration time based on the Suspense timeout.
23627 expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
23628 } else {
23629 // Compute an expiration time based on the Scheduler priority.
23630 switch (priorityLevel) {
23631 case ImmediatePriority:
23632 expirationTime = Sync;
23633 break;
23634
23635 case UserBlockingPriority$2:
23636 // TODO: Rename this to computeUserBlockingExpiration
23637 expirationTime = computeInteractiveExpiration(currentTime);
23638 break;
23639
23640 case NormalPriority:
23641 case LowPriority:
23642 // TODO: Handle LowPriority
23643 // TODO: Rename this to... something better.
23644 expirationTime = computeAsyncExpiration(currentTime);
23645 break;
23646
23647 case IdlePriority:
23648 expirationTime = Idle;
23649 break;
23650
23651 default:
23652 {
23653 {
23654 throw Error("Expected a valid priority level");
23655 }
23656 }
23657
23658 }
23659 } // If we're in the middle of rendering a tree, do not update at the same
23660 // expiration time that is already rendering.
23661 // TODO: We shouldn't have to do this if the update is on a different root.
23662 // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
23663 // the root when we check for this condition.
23664
23665
23666 if (workInProgressRoot !== null && expirationTime === renderExpirationTime) {
23667 // This is a trick to move this update into a separate batch
23668 expirationTime -= 1;
23669 }
23670
23671 return expirationTime;
23672}
23673function scheduleUpdateOnFiber(fiber, expirationTime) {
23674 checkForNestedUpdates();
23675 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
23676 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
23677
23678 if (root === null) {
23679 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
23680 return;
23681 }
23682
23683 checkForInterruption(fiber, expirationTime);
23684 recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
23685 // priority as an argument to that function and this one.
23686
23687 var priorityLevel = getCurrentPriorityLevel();
23688
23689 if (expirationTime === Sync) {
23690 if ( // Check if we're inside unbatchedUpdates
23691 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
23692 (executionContext & (RenderContext | CommitContext)) === NoContext) {
23693 // Register pending interactions on the root to avoid losing traced interaction data.
23694 schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
23695 // root inside of batchedUpdates should be synchronous, but layout updates
23696 // should be deferred until the end of the batch.
23697
23698 performSyncWorkOnRoot(root);
23699 } else {
23700 ensureRootIsScheduled(root);
23701 schedulePendingInteractions(root, expirationTime);
23702
23703 if (executionContext === NoContext) {
23704 // Flush the synchronous work now, unless we're already working or inside
23705 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
23706 // scheduleCallbackForFiber to preserve the ability to schedule a callback
23707 // without immediately flushing it. We only do this for user-initiated
23708 // updates, to preserve historical behavior of legacy mode.
23709 flushSyncCallbackQueue();
23710 }
23711 }
23712 } else {
23713 ensureRootIsScheduled(root);
23714 schedulePendingInteractions(root, expirationTime);
23715 }
23716
23717 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
23718 // discrete, even inside a discrete event.
23719 priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority)) {
23720 // This is the result of a discrete event. Track the lowest priority
23721 // discrete update per root so we can flush them early, if needed.
23722 if (rootsWithPendingDiscreteUpdates === null) {
23723 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
23724 } else {
23725 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
23726
23727 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
23728 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
23729 }
23730 }
23731 }
23732}
23733var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
23734// work without treating it as a typical update that originates from an event;
23735// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
23736// on a fiber.
23737
23738function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
23739 // Update the source fiber's expiration time
23740 if (fiber.expirationTime < expirationTime) {
23741 fiber.expirationTime = expirationTime;
23742 }
23743
23744 var alternate = fiber.alternate;
23745
23746 if (alternate !== null && alternate.expirationTime < expirationTime) {
23747 alternate.expirationTime = expirationTime;
23748 } // Walk the parent path to the root and update the child expiration time.
23749
23750
23751 var node = fiber.return;
23752 var root = null;
23753
23754 if (node === null && fiber.tag === HostRoot) {
23755 root = fiber.stateNode;
23756 } else {
23757 while (node !== null) {
23758 alternate = node.alternate;
23759
23760 if (node.childExpirationTime < expirationTime) {
23761 node.childExpirationTime = expirationTime;
23762
23763 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23764 alternate.childExpirationTime = expirationTime;
23765 }
23766 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23767 alternate.childExpirationTime = expirationTime;
23768 }
23769
23770 if (node.return === null && node.tag === HostRoot) {
23771 root = node.stateNode;
23772 break;
23773 }
23774
23775 node = node.return;
23776 }
23777 }
23778
23779 if (root !== null) {
23780 if (workInProgressRoot === root) {
23781 // Received an update to a tree that's in the middle of rendering. Mark
23782 // that's unprocessed work on this root.
23783 markUnprocessedUpdateTime(expirationTime);
23784
23785 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
23786 // The root already suspended with a delay, which means this render
23787 // definitely won't finish. Since we have a new update, let's mark it as
23788 // suspended now, right before marking the incoming update. This has the
23789 // effect of interrupting the current render and switching to the update.
23790 // TODO: This happens to work when receiving an update during the render
23791 // phase, because of the trick inside computeExpirationForFiber to
23792 // subtract 1 from `renderExpirationTime` to move it into a
23793 // separate bucket. But we should probably model it with an exception,
23794 // using the same mechanism we use to force hydration of a subtree.
23795 // TODO: This does not account for low pri updates that were already
23796 // scheduled before the root started rendering. Need to track the next
23797 // pending expiration time (perhaps by backtracking the return path) and
23798 // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
23799 markRootSuspendedAtTime(root, renderExpirationTime);
23800 }
23801 } // Mark that the root has a pending update.
23802
23803
23804 markRootUpdatedAtTime(root, expirationTime);
23805 }
23806
23807 return root;
23808}
23809
23810function getNextRootExpirationTimeToWorkOn(root) {
23811 // Determines the next expiration time that the root should render, taking
23812 // into account levels that may be suspended, or levels that may have
23813 // received a ping.
23814 var lastExpiredTime = root.lastExpiredTime;
23815
23816 if (lastExpiredTime !== NoWork) {
23817 return lastExpiredTime;
23818 } // "Pending" refers to any update that hasn't committed yet, including if it
23819 // suspended. The "suspended" range is therefore a subset.
23820
23821
23822 var firstPendingTime = root.firstPendingTime;
23823
23824 if (!isRootSuspendedAtTime(root, firstPendingTime)) {
23825 // The highest priority pending time is not suspended. Let's work on that.
23826 return firstPendingTime;
23827 } // If the first pending time is suspended, check if there's a lower priority
23828 // pending level that we know about. Or check if we received a ping. Work
23829 // on whichever is higher priority.
23830
23831
23832 var lastPingedTime = root.lastPingedTime;
23833 var nextKnownPendingLevel = root.nextKnownPendingLevel;
23834 return lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
23835} // Use this function to schedule a task for a root. There's only one task per
23836// root; if a task was already scheduled, we'll check to make sure the
23837// expiration time of the existing task is the same as the expiration time of
23838// the next level that the root has work on. This function is called on every
23839// update, and right before exiting a task.
23840
23841
23842function ensureRootIsScheduled(root) {
23843 var lastExpiredTime = root.lastExpiredTime;
23844
23845 if (lastExpiredTime !== NoWork) {
23846 // Special case: Expired work should flush synchronously.
23847 root.callbackExpirationTime = Sync;
23848 root.callbackPriority = ImmediatePriority;
23849 root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23850 return;
23851 }
23852
23853 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23854 var existingCallbackNode = root.callbackNode;
23855
23856 if (expirationTime === NoWork) {
23857 // There's nothing to work on.
23858 if (existingCallbackNode !== null) {
23859 root.callbackNode = null;
23860 root.callbackExpirationTime = NoWork;
23861 root.callbackPriority = NoPriority;
23862 }
23863
23864 return;
23865 } // TODO: If this is an update, we already read the current time. Pass the
23866 // time as an argument.
23867
23868
23869 var currentTime = requestCurrentTimeForUpdate();
23870 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
23871 // expiration time. Otherwise, we'll cancel it and schedule a new one.
23872
23873 if (existingCallbackNode !== null) {
23874 var existingCallbackPriority = root.callbackPriority;
23875 var existingCallbackExpirationTime = root.callbackExpirationTime;
23876
23877 if ( // Callback must have the exact same expiration time.
23878 existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
23879 existingCallbackPriority >= priorityLevel) {
23880 // Existing callback is sufficient.
23881 return;
23882 } // Need to schedule a new task.
23883 // TODO: Instead of scheduling a new task, we should be able to change the
23884 // priority of the existing one.
23885
23886
23887 cancelCallback(existingCallbackNode);
23888 }
23889
23890 root.callbackExpirationTime = expirationTime;
23891 root.callbackPriority = priorityLevel;
23892 var callbackNode;
23893
23894 if (expirationTime === Sync) {
23895 // Sync React callbacks are scheduled on a special internal queue
23896 callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23897 } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) {
23898 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root));
23899 } else {
23900 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
23901 // ordering because tasks are processed in timeout order.
23902 {
23903 timeout: expirationTimeToMs(expirationTime) - now()
23904 });
23905 }
23906
23907 root.callbackNode = callbackNode;
23908} // This is the entry point for every concurrent task, i.e. anything that
23909// goes through Scheduler.
23910
23911
23912function performConcurrentWorkOnRoot(root, didTimeout) {
23913 // Since we know we're in a React event, we can clear the current
23914 // event time. The next update will compute a new event time.
23915 currentEventTime = NoWork;
23916
23917 if (didTimeout) {
23918 // The render task took too long to complete. Mark the current time as
23919 // expired to synchronously render all expired work in a single batch.
23920 var currentTime = requestCurrentTimeForUpdate();
23921 markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
23922
23923 ensureRootIsScheduled(root);
23924 return null;
23925 } // Determine the next expiration time to work on, using the fields stored
23926 // on the root.
23927
23928
23929 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23930
23931 if (expirationTime !== NoWork) {
23932 var originalCallbackNode = root.callbackNode;
23933
23934 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
23935 {
23936 throw Error("Should not already be working.");
23937 }
23938 }
23939
23940 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
23941 // and prepare a fresh one. Otherwise we'll continue where we left off.
23942
23943 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
23944 prepareFreshStack(root, expirationTime);
23945 startWorkOnPendingInteractions(root, expirationTime);
23946 } // If we have a work-in-progress fiber, it means there's still work to do
23947 // in this root.
23948
23949
23950 if (workInProgress !== null) {
23951 var prevExecutionContext = executionContext;
23952 executionContext |= RenderContext;
23953 var prevDispatcher = pushDispatcher(root);
23954 var prevInteractions = pushInteractions(root);
23955 startWorkLoopTimer(workInProgress);
23956
23957 do {
23958 try {
23959 workLoopConcurrent();
23960 break;
23961 } catch (thrownValue) {
23962 handleError(root, thrownValue);
23963 }
23964 } while (true);
23965
23966 resetContextDependencies();
23967 executionContext = prevExecutionContext;
23968 popDispatcher(prevDispatcher);
23969
23970 if (enableSchedulerTracing) {
23971 popInteractions(prevInteractions);
23972 }
23973
23974 if (workInProgressRootExitStatus === RootFatalErrored) {
23975 var fatalError = workInProgressRootFatalError;
23976 stopInterruptedWorkLoopTimer();
23977 prepareFreshStack(root, expirationTime);
23978 markRootSuspendedAtTime(root, expirationTime);
23979 ensureRootIsScheduled(root);
23980 throw fatalError;
23981 }
23982
23983 if (workInProgress !== null) {
23984 // There's still work left over. Exit without committing.
23985 stopInterruptedWorkLoopTimer();
23986 } else {
23987 // We now have a consistent tree. The next step is either to commit it,
23988 // or, if something suspended, wait to commit it after a timeout.
23989 stopFinishedWorkLoopTimer();
23990 var finishedWork = root.finishedWork = root.current.alternate;
23991 root.finishedExpirationTime = expirationTime;
23992 finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
23993 }
23994
23995 ensureRootIsScheduled(root);
23996
23997 if (root.callbackNode === originalCallbackNode) {
23998 // The task node scheduled for this root is the same one that's
23999 // currently executed. Need to return a continuation.
24000 return performConcurrentWorkOnRoot.bind(null, root);
24001 }
24002 }
24003 }
24004
24005 return null;
24006}
24007
24008function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
24009 // Set this to null to indicate there's no in-progress render.
24010 workInProgressRoot = null;
24011
24012 switch (exitStatus) {
24013 case RootIncomplete:
24014 case RootFatalErrored:
24015 {
24016 {
24017 {
24018 throw Error("Root did not complete. This is a bug in React.");
24019 }
24020 }
24021 }
24022 // Flow knows about invariant, so it complains if I add a break
24023 // statement, but eslint doesn't know about invariant, so it complains
24024 // if I do. eslint-disable-next-line no-fallthrough
24025
24026 case RootErrored:
24027 {
24028 // If this was an async render, the error may have happened due to
24029 // a mutation in a concurrent event. Try rendering one more time,
24030 // synchronously, to see if the error goes away. If there are
24031 // lower priority updates, let's include those, too, in case they
24032 // fix the inconsistency. Render at Idle to include all updates.
24033 // If it was Idle or Never or some not-yet-invented time, render
24034 // at that time.
24035 markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous
24036 // and therefore not hit this path again.
24037
24038 break;
24039 }
24040
24041 case RootSuspended:
24042 {
24043 markRootSuspendedAtTime(root, expirationTime);
24044 var lastSuspendedTime = root.lastSuspendedTime;
24045
24046 if (expirationTime === lastSuspendedTime) {
24047 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24048 }
24049
24050 flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we
24051 // should immediately commit it or wait a bit.
24052 // If we have processed new updates during this render, we may now
24053 // have a new loading state ready. We want to ensure that we commit
24054 // that as soon as possible.
24055
24056 var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
24057
24058 if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
24059 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24060 // If we have not processed any new updates during this pass, then
24061 // this is either a retry of an existing fallback state or a
24062 // hidden tree. Hidden trees shouldn't be batched with other work
24063 // and after that's fixed it can only be a retry. We're going to
24064 // throttle committing retries so that we don't show too many
24065 // loading states too quickly.
24066 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
24067
24068 if (msUntilTimeout > 10) {
24069 if (workInProgressRootHasPendingPing) {
24070 var lastPingedTime = root.lastPingedTime;
24071
24072 if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
24073 // This render was pinged but we didn't get to restart
24074 // earlier so try restarting now instead.
24075 root.lastPingedTime = expirationTime;
24076 prepareFreshStack(root, expirationTime);
24077 break;
24078 }
24079 }
24080
24081 var nextTime = getNextRootExpirationTimeToWorkOn(root);
24082
24083 if (nextTime !== NoWork && nextTime !== expirationTime) {
24084 // There's additional work on this root.
24085 break;
24086 }
24087
24088 if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
24089 // We should prefer to render the fallback of at the last
24090 // suspended level. Ping the last suspended level to try
24091 // rendering it again.
24092 root.lastPingedTime = lastSuspendedTime;
24093 break;
24094 } // The render is suspended, it hasn't timed out, and there's no
24095 // lower priority work to do. Instead of committing the fallback
24096 // immediately, wait for more data to arrive.
24097
24098
24099 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
24100 break;
24101 }
24102 } // The work expired. Commit immediately.
24103
24104
24105 commitRoot(root);
24106 break;
24107 }
24108
24109 case RootSuspendedWithDelay:
24110 {
24111 markRootSuspendedAtTime(root, expirationTime);
24112 var _lastSuspendedTime = root.lastSuspendedTime;
24113
24114 if (expirationTime === _lastSuspendedTime) {
24115 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24116 }
24117
24118 flushSuspensePriorityWarningInDEV();
24119
24120 if ( // do not delay if we're inside an act() scope
24121 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24122 // We're suspended in a state that should be avoided. We'll try to
24123 // avoid committing it for as long as the timeouts let us.
24124 if (workInProgressRootHasPendingPing) {
24125 var _lastPingedTime = root.lastPingedTime;
24126
24127 if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
24128 // This render was pinged but we didn't get to restart earlier
24129 // so try restarting now instead.
24130 root.lastPingedTime = expirationTime;
24131 prepareFreshStack(root, expirationTime);
24132 break;
24133 }
24134 }
24135
24136 var _nextTime = getNextRootExpirationTimeToWorkOn(root);
24137
24138 if (_nextTime !== NoWork && _nextTime !== expirationTime) {
24139 // There's additional work on this root.
24140 break;
24141 }
24142
24143 if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
24144 // We should prefer to render the fallback of at the last
24145 // suspended level. Ping the last suspended level to try
24146 // rendering it again.
24147 root.lastPingedTime = _lastSuspendedTime;
24148 break;
24149 }
24150
24151 var _msUntilTimeout;
24152
24153 if (workInProgressRootLatestSuspenseTimeout !== Sync) {
24154 // We have processed a suspense config whose expiration time we
24155 // can use as the timeout.
24156 _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
24157 } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
24158 // This should never normally happen because only new updates
24159 // cause delayed states, so we should have processed something.
24160 // However, this could also happen in an offscreen tree.
24161 _msUntilTimeout = 0;
24162 } else {
24163 // If we don't have a suspense config, we're going to use a
24164 // heuristic to determine how long we can suspend.
24165 var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
24166 var currentTimeMs = now();
24167 var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
24168 var timeElapsed = currentTimeMs - eventTimeMs;
24169
24170 if (timeElapsed < 0) {
24171 // We get this wrong some time since we estimate the time.
24172 timeElapsed = 0;
24173 }
24174
24175 _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
24176 // event time is exact instead of inferred from expiration time
24177 // we don't need this.
24178
24179 if (timeUntilExpirationMs < _msUntilTimeout) {
24180 _msUntilTimeout = timeUntilExpirationMs;
24181 }
24182 } // Don't bother with a very short suspense time.
24183
24184
24185 if (_msUntilTimeout > 10) {
24186 // The render is suspended, it hasn't timed out, and there's no
24187 // lower priority work to do. Instead of committing the fallback
24188 // immediately, wait for more data to arrive.
24189 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
24190 break;
24191 }
24192 } // The work expired. Commit immediately.
24193
24194
24195 commitRoot(root);
24196 break;
24197 }
24198
24199 case RootCompleted:
24200 {
24201 // The work completed. Ready to commit.
24202 if ( // do not delay if we're inside an act() scope
24203 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
24204 // If we have exceeded the minimum loading delay, which probably
24205 // means we have shown a spinner already, we might have to suspend
24206 // a bit longer to ensure that the spinner is shown for
24207 // enough time.
24208 var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
24209
24210 if (_msUntilTimeout2 > 10) {
24211 markRootSuspendedAtTime(root, expirationTime);
24212 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
24213 break;
24214 }
24215 }
24216
24217 commitRoot(root);
24218 break;
24219 }
24220
24221 default:
24222 {
24223 {
24224 {
24225 throw Error("Unknown root exit status.");
24226 }
24227 }
24228 }
24229 }
24230} // This is the entry point for synchronous tasks that don't go
24231// through Scheduler
24232
24233
24234function performSyncWorkOnRoot(root) {
24235 // Check if there's expired work on this root. Otherwise, render at Sync.
24236 var lastExpiredTime = root.lastExpiredTime;
24237 var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
24238
24239 if (root.finishedExpirationTime === expirationTime) {
24240 // There's already a pending commit at this expiration time.
24241 // TODO: This is poorly factored. This case only exists for the
24242 // batch.commit() API.
24243 commitRoot(root);
24244 } else {
24245 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24246 {
24247 throw Error("Should not already be working.");
24248 }
24249 }
24250
24251 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24252 // and prepare a fresh one. Otherwise we'll continue where we left off.
24253
24254 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24255 prepareFreshStack(root, expirationTime);
24256 startWorkOnPendingInteractions(root, expirationTime);
24257 } // If we have a work-in-progress fiber, it means there's still work to do
24258 // in this root.
24259
24260
24261 if (workInProgress !== null) {
24262 var prevExecutionContext = executionContext;
24263 executionContext |= RenderContext;
24264 var prevDispatcher = pushDispatcher(root);
24265 var prevInteractions = pushInteractions(root);
24266 startWorkLoopTimer(workInProgress);
24267
24268 do {
24269 try {
24270 workLoopSync();
24271 break;
24272 } catch (thrownValue) {
24273 handleError(root, thrownValue);
24274 }
24275 } while (true);
24276
24277 resetContextDependencies();
24278 executionContext = prevExecutionContext;
24279 popDispatcher(prevDispatcher);
24280
24281 if (enableSchedulerTracing) {
24282 popInteractions(prevInteractions);
24283 }
24284
24285 if (workInProgressRootExitStatus === RootFatalErrored) {
24286 var fatalError = workInProgressRootFatalError;
24287 stopInterruptedWorkLoopTimer();
24288 prepareFreshStack(root, expirationTime);
24289 markRootSuspendedAtTime(root, expirationTime);
24290 ensureRootIsScheduled(root);
24291 throw fatalError;
24292 }
24293
24294 if (workInProgress !== null) {
24295 // This is a sync render, so we should have finished the whole tree.
24296 {
24297 {
24298 throw Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
24299 }
24300 }
24301 } else {
24302 // We now have a consistent tree. Because this is a sync render, we
24303 // will commit it even if something suspended.
24304 stopFinishedWorkLoopTimer();
24305 root.finishedWork = root.current.alternate;
24306 root.finishedExpirationTime = expirationTime;
24307 finishSyncRender(root, workInProgressRootExitStatus, expirationTime);
24308 } // Before exiting, make sure there's a callback scheduled for the next
24309 // pending level.
24310
24311
24312 ensureRootIsScheduled(root);
24313 }
24314 }
24315
24316 return null;
24317}
24318
24319function finishSyncRender(root, exitStatus, expirationTime) {
24320 // Set this to null to indicate there's no in-progress render.
24321 workInProgressRoot = null;
24322
24323 {
24324 if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) {
24325 flushSuspensePriorityWarningInDEV();
24326 }
24327 }
24328
24329 commitRoot(root);
24330}
24331
24332function flushRoot(root, expirationTime) {
24333 markRootExpiredAtTime(root, expirationTime);
24334 ensureRootIsScheduled(root);
24335
24336 if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
24337 flushSyncCallbackQueue();
24338 }
24339}
24340function flushDiscreteUpdates() {
24341 // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
24342 // However, `act` uses `batchedUpdates`, so there's no way to distinguish
24343 // those two cases. Need to fix this before exposing flushDiscreteUpdates
24344 // as a public API.
24345 if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
24346 if (true && (executionContext & RenderContext) !== NoContext) {
24347 warning$1(false, 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
24348 } // We're already rendering, so we can't synchronously flush pending work.
24349 // This is probably a nested event dispatch triggered by a lifecycle/effect,
24350 // like `el.focus()`. Exit.
24351
24352
24353 return;
24354 }
24355
24356 flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
24357 // they fire before the next serial event.
24358
24359 flushPassiveEffects();
24360}
24361
24362function syncUpdates(fn, a, b, c) {
24363 return runWithPriority$2(ImmediatePriority, fn.bind(null, a, b, c));
24364}
24365
24366function flushPendingDiscreteUpdates() {
24367 if (rootsWithPendingDiscreteUpdates !== null) {
24368 // For each root with pending discrete updates, schedule a callback to
24369 // immediately flush them.
24370 var roots = rootsWithPendingDiscreteUpdates;
24371 rootsWithPendingDiscreteUpdates = null;
24372 roots.forEach(function (expirationTime, root) {
24373 markRootExpiredAtTime(root, expirationTime);
24374 ensureRootIsScheduled(root);
24375 }); // Now flush the immediate queue.
24376
24377 flushSyncCallbackQueue();
24378 }
24379}
24380
24381function batchedUpdates$1(fn, a) {
24382 var prevExecutionContext = executionContext;
24383 executionContext |= BatchedContext;
24384
24385 try {
24386 return fn(a);
24387 } finally {
24388 executionContext = prevExecutionContext;
24389
24390 if (executionContext === NoContext) {
24391 // Flush the immediate callbacks that were scheduled during this batch
24392 flushSyncCallbackQueue();
24393 }
24394 }
24395}
24396function batchedEventUpdates$1(fn, a) {
24397 var prevExecutionContext = executionContext;
24398 executionContext |= EventContext;
24399
24400 try {
24401 return fn(a);
24402 } finally {
24403 executionContext = prevExecutionContext;
24404
24405 if (executionContext === NoContext) {
24406 // Flush the immediate callbacks that were scheduled during this batch
24407 flushSyncCallbackQueue();
24408 }
24409 }
24410}
24411function discreteUpdates$1(fn, a, b, c) {
24412 var prevExecutionContext = executionContext;
24413 executionContext |= DiscreteEventContext;
24414
24415 try {
24416 // Should this
24417 return runWithPriority$2(UserBlockingPriority$2, fn.bind(null, a, b, c));
24418 } finally {
24419 executionContext = prevExecutionContext;
24420
24421 if (executionContext === NoContext) {
24422 // Flush the immediate callbacks that were scheduled during this batch
24423 flushSyncCallbackQueue();
24424 }
24425 }
24426}
24427function unbatchedUpdates(fn, a) {
24428 var prevExecutionContext = executionContext;
24429 executionContext &= ~BatchedContext;
24430 executionContext |= LegacyUnbatchedContext;
24431
24432 try {
24433 return fn(a);
24434 } finally {
24435 executionContext = prevExecutionContext;
24436
24437 if (executionContext === NoContext) {
24438 // Flush the immediate callbacks that were scheduled during this batch
24439 flushSyncCallbackQueue();
24440 }
24441 }
24442}
24443function flushSync(fn, a) {
24444 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24445 {
24446 {
24447 throw Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.");
24448 }
24449 }
24450 }
24451
24452 var prevExecutionContext = executionContext;
24453 executionContext |= BatchedContext;
24454
24455 try {
24456 return runWithPriority$2(ImmediatePriority, fn.bind(null, a));
24457 } finally {
24458 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
24459 // Note that this will happen even if batchedUpdates is higher up
24460 // the stack.
24461
24462 flushSyncCallbackQueue();
24463 }
24464}
24465function flushControlled(fn) {
24466 var prevExecutionContext = executionContext;
24467 executionContext |= BatchedContext;
24468
24469 try {
24470 runWithPriority$2(ImmediatePriority, fn);
24471 } finally {
24472 executionContext = prevExecutionContext;
24473
24474 if (executionContext === NoContext) {
24475 // Flush the immediate callbacks that were scheduled during this batch
24476 flushSyncCallbackQueue();
24477 }
24478 }
24479}
24480
24481function prepareFreshStack(root, expirationTime) {
24482 root.finishedWork = null;
24483 root.finishedExpirationTime = NoWork;
24484 var timeoutHandle = root.timeoutHandle;
24485
24486 if (timeoutHandle !== noTimeout) {
24487 // The root previous suspended and scheduled a timeout to commit a fallback
24488 // state. Now that we have additional work, cancel the timeout.
24489 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
24490
24491 cancelTimeout(timeoutHandle);
24492 }
24493
24494 if (workInProgress !== null) {
24495 var interruptedWork = workInProgress.return;
24496
24497 while (interruptedWork !== null) {
24498 unwindInterruptedWork(interruptedWork);
24499 interruptedWork = interruptedWork.return;
24500 }
24501 }
24502
24503 workInProgressRoot = root;
24504 workInProgress = createWorkInProgress(root.current, null, expirationTime);
24505 renderExpirationTime = expirationTime;
24506 workInProgressRootExitStatus = RootIncomplete;
24507 workInProgressRootFatalError = null;
24508 workInProgressRootLatestProcessedExpirationTime = Sync;
24509 workInProgressRootLatestSuspenseTimeout = Sync;
24510 workInProgressRootCanSuspendUsingConfig = null;
24511 workInProgressRootNextUnprocessedUpdateTime = NoWork;
24512 workInProgressRootHasPendingPing = false;
24513
24514 if (enableSchedulerTracing) {
24515 spawnedWorkDuringRender = null;
24516 }
24517
24518 {
24519 ReactStrictModeWarnings.discardPendingWarnings();
24520 componentsThatTriggeredHighPriSuspend = null;
24521 }
24522}
24523
24524function handleError(root, thrownValue) {
24525 do {
24526 try {
24527 // Reset module-level state that was set during the render phase.
24528 resetContextDependencies();
24529 resetHooks();
24530 resetCurrentFiber();
24531
24532 if (workInProgress === null || workInProgress.return === null) {
24533 // Expected to be working on a non-root fiber. This is a fatal error
24534 // because there's no ancestor that can handle it; the root is
24535 // supposed to capture all errors that weren't caught by an error
24536 // boundary.
24537 workInProgressRootExitStatus = RootFatalErrored;
24538 workInProgressRootFatalError = thrownValue;
24539 return null;
24540 }
24541
24542 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
24543 // Record the time spent rendering before an error was thrown. This
24544 // avoids inaccurate Profiler durations in the case of a
24545 // suspended render.
24546 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
24547 }
24548
24549 throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime);
24550 workInProgress = completeUnitOfWork(workInProgress);
24551 } catch (yetAnotherThrownValue) {
24552 // Something in the return path also threw.
24553 thrownValue = yetAnotherThrownValue;
24554 continue;
24555 } // Return to the normal work loop.
24556
24557
24558 return;
24559 } while (true);
24560}
24561
24562function pushDispatcher(root) {
24563 var prevDispatcher = ReactCurrentDispatcher.current;
24564 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
24565
24566 if (prevDispatcher === null) {
24567 // The React isomorphic package does not include a default dispatcher.
24568 // Instead the first renderer will lazily attach one, in order to give
24569 // nicer error messages.
24570 return ContextOnlyDispatcher;
24571 } else {
24572 return prevDispatcher;
24573 }
24574}
24575
24576function popDispatcher(prevDispatcher) {
24577 ReactCurrentDispatcher.current = prevDispatcher;
24578}
24579
24580function pushInteractions(root) {
24581 if (enableSchedulerTracing) {
24582 var prevInteractions = tracing.__interactionsRef.current;
24583 tracing.__interactionsRef.current = root.memoizedInteractions;
24584 return prevInteractions;
24585 }
24586
24587 return null;
24588}
24589
24590function popInteractions(prevInteractions) {
24591 if (enableSchedulerTracing) {
24592 tracing.__interactionsRef.current = prevInteractions;
24593 }
24594}
24595
24596function markCommitTimeOfFallback() {
24597 globalMostRecentFallbackTime = now();
24598}
24599function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
24600 if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
24601 workInProgressRootLatestProcessedExpirationTime = expirationTime;
24602 }
24603
24604 if (suspenseConfig !== null) {
24605 if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
24606 workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
24607
24608 workInProgressRootCanSuspendUsingConfig = suspenseConfig;
24609 }
24610 }
24611}
24612function markUnprocessedUpdateTime(expirationTime) {
24613 if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
24614 workInProgressRootNextUnprocessedUpdateTime = expirationTime;
24615 }
24616}
24617function renderDidSuspend() {
24618 if (workInProgressRootExitStatus === RootIncomplete) {
24619 workInProgressRootExitStatus = RootSuspended;
24620 }
24621}
24622function renderDidSuspendDelayIfPossible() {
24623 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
24624 workInProgressRootExitStatus = RootSuspendedWithDelay;
24625 } // Check if there's a lower priority update somewhere else in the tree.
24626
24627
24628 if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
24629 // Mark the current render as suspended, and then mark that there's a
24630 // pending update.
24631 // TODO: This should immediately interrupt the current render, instead
24632 // of waiting until the next time we yield.
24633 markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
24634 markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
24635 }
24636}
24637function renderDidError() {
24638 if (workInProgressRootExitStatus !== RootCompleted) {
24639 workInProgressRootExitStatus = RootErrored;
24640 }
24641} // Called during render to determine if anything has suspended.
24642// Returns false if we're not sure.
24643
24644function renderHasNotSuspendedYet() {
24645 // If something errored or completed, we can't really be sure,
24646 // so those are false.
24647 return workInProgressRootExitStatus === RootIncomplete;
24648}
24649
24650function inferTimeFromExpirationTime(expirationTime) {
24651 // We don't know exactly when the update was scheduled, but we can infer an
24652 // approximate start time from the expiration time.
24653 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24654 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
24655}
24656
24657function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
24658 // We don't know exactly when the update was scheduled, but we can infer an
24659 // approximate start time from the expiration time by subtracting the timeout
24660 // that was added to the event time.
24661 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24662 return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
24663} // The work loop is an extremely hot path. Tell Closure not to inline it.
24664
24665/** @noinline */
24666
24667
24668function workLoopSync() {
24669 // Already timed out, so perform work without checking if we need to yield.
24670 while (workInProgress !== null) {
24671 workInProgress = performUnitOfWork(workInProgress);
24672 }
24673}
24674/** @noinline */
24675
24676
24677function workLoopConcurrent() {
24678 // Perform work until Scheduler asks us to yield
24679 while (workInProgress !== null && !shouldYield()) {
24680 workInProgress = performUnitOfWork(workInProgress);
24681 }
24682}
24683
24684function performUnitOfWork(unitOfWork) {
24685 // The current, flushed, state of this fiber is the alternate. Ideally
24686 // nothing should rely on this, but relying on it here means that we don't
24687 // need an additional field on the work in progress.
24688 var current$$1 = unitOfWork.alternate;
24689 startWorkTimer(unitOfWork);
24690 setCurrentFiber(unitOfWork);
24691 var next;
24692
24693 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
24694 startProfilerTimer(unitOfWork);
24695 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24696 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
24697 } else {
24698 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24699 }
24700
24701 resetCurrentFiber();
24702 unitOfWork.memoizedProps = unitOfWork.pendingProps;
24703
24704 if (next === null) {
24705 // If this doesn't spawn new work, complete the current work.
24706 next = completeUnitOfWork(unitOfWork);
24707 }
24708
24709 ReactCurrentOwner$2.current = null;
24710 return next;
24711}
24712
24713function completeUnitOfWork(unitOfWork) {
24714 // Attempt to complete the current unit of work, then move to the next
24715 // sibling. If there are no more siblings, return to the parent fiber.
24716 workInProgress = unitOfWork;
24717
24718 do {
24719 // The current, flushed, state of this fiber is the alternate. Ideally
24720 // nothing should rely on this, but relying on it here means that we don't
24721 // need an additional field on the work in progress.
24722 var current$$1 = workInProgress.alternate;
24723 var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
24724
24725 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
24726 setCurrentFiber(workInProgress);
24727 var next = void 0;
24728
24729 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode) {
24730 next = completeWork(current$$1, workInProgress, renderExpirationTime);
24731 } else {
24732 startProfilerTimer(workInProgress);
24733 next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error.
24734
24735 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
24736 }
24737
24738 stopWorkTimer(workInProgress);
24739 resetCurrentFiber();
24740 resetChildExpirationTime(workInProgress);
24741
24742 if (next !== null) {
24743 // Completing this fiber spawned new work. Work on that next.
24744 return next;
24745 }
24746
24747 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
24748 (returnFiber.effectTag & Incomplete) === NoEffect) {
24749 // Append all the effects of the subtree and this fiber onto the effect
24750 // list of the parent. The completion order of the children affects the
24751 // side-effect order.
24752 if (returnFiber.firstEffect === null) {
24753 returnFiber.firstEffect = workInProgress.firstEffect;
24754 }
24755
24756 if (workInProgress.lastEffect !== null) {
24757 if (returnFiber.lastEffect !== null) {
24758 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
24759 }
24760
24761 returnFiber.lastEffect = workInProgress.lastEffect;
24762 } // If this fiber had side-effects, we append it AFTER the children's
24763 // side-effects. We can perform certain side-effects earlier if needed,
24764 // by doing multiple passes over the effect list. We don't want to
24765 // schedule our own side-effect on our own list because if end up
24766 // reusing children we'll schedule this effect onto itself since we're
24767 // at the end.
24768
24769
24770 var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
24771 // list. PerformedWork effect is read by React DevTools but shouldn't be
24772 // committed.
24773
24774 if (effectTag > PerformedWork) {
24775 if (returnFiber.lastEffect !== null) {
24776 returnFiber.lastEffect.nextEffect = workInProgress;
24777 } else {
24778 returnFiber.firstEffect = workInProgress;
24779 }
24780
24781 returnFiber.lastEffect = workInProgress;
24782 }
24783 }
24784 } else {
24785 // This fiber did not complete because something threw. Pop values off
24786 // the stack without entering the complete phase. If this is a boundary,
24787 // capture values if possible.
24788 var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time.
24789
24790
24791 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode) {
24792 // Record the render duration for the fiber that errored.
24793 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
24794
24795 var actualDuration = workInProgress.actualDuration;
24796 var child = workInProgress.child;
24797
24798 while (child !== null) {
24799 actualDuration += child.actualDuration;
24800 child = child.sibling;
24801 }
24802
24803 workInProgress.actualDuration = actualDuration;
24804 }
24805
24806 if (_next !== null) {
24807 // If completing this work spawned new work, do that next. We'll come
24808 // back here again.
24809 // Since we're restarting, remove anything that is not a host effect
24810 // from the effect tag.
24811 // TODO: The name stopFailedWorkTimer is misleading because Suspense
24812 // also captures and restarts.
24813 stopFailedWorkTimer(workInProgress);
24814 _next.effectTag &= HostEffectMask;
24815 return _next;
24816 }
24817
24818 stopWorkTimer(workInProgress);
24819
24820 if (returnFiber !== null) {
24821 // Mark the parent fiber as incomplete and clear its effect list.
24822 returnFiber.firstEffect = returnFiber.lastEffect = null;
24823 returnFiber.effectTag |= Incomplete;
24824 }
24825 }
24826
24827 var siblingFiber = workInProgress.sibling;
24828
24829 if (siblingFiber !== null) {
24830 // If there is more work to do in this returnFiber, do that next.
24831 return siblingFiber;
24832 } // Otherwise, return to the parent
24833
24834
24835 workInProgress = returnFiber;
24836 } while (workInProgress !== null); // We've reached the root.
24837
24838
24839 if (workInProgressRootExitStatus === RootIncomplete) {
24840 workInProgressRootExitStatus = RootCompleted;
24841 }
24842
24843 return null;
24844}
24845
24846function getRemainingExpirationTime(fiber) {
24847 var updateExpirationTime = fiber.expirationTime;
24848 var childExpirationTime = fiber.childExpirationTime;
24849 return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
24850}
24851
24852function resetChildExpirationTime(completedWork) {
24853 if (renderExpirationTime !== Never && completedWork.childExpirationTime === Never) {
24854 // The children of this component are hidden. Don't bubble their
24855 // expiration times.
24856 return;
24857 }
24858
24859 var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
24860
24861 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
24862 // In profiling mode, resetChildExpirationTime is also used to reset
24863 // profiler durations.
24864 var actualDuration = completedWork.actualDuration;
24865 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
24866 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
24867 // When work is done, it should bubble to the parent's actualDuration. If
24868 // the fiber has not been cloned though, (meaning no work was done), then
24869 // this value will reflect the amount of time spent working on a previous
24870 // render. In that case it should not bubble. We determine whether it was
24871 // cloned by comparing the child pointer.
24872
24873 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
24874 var child = completedWork.child;
24875
24876 while (child !== null) {
24877 var childUpdateExpirationTime = child.expirationTime;
24878 var childChildExpirationTime = child.childExpirationTime;
24879
24880 if (childUpdateExpirationTime > newChildExpirationTime) {
24881 newChildExpirationTime = childUpdateExpirationTime;
24882 }
24883
24884 if (childChildExpirationTime > newChildExpirationTime) {
24885 newChildExpirationTime = childChildExpirationTime;
24886 }
24887
24888 if (shouldBubbleActualDurations) {
24889 actualDuration += child.actualDuration;
24890 }
24891
24892 treeBaseDuration += child.treeBaseDuration;
24893 child = child.sibling;
24894 }
24895
24896 completedWork.actualDuration = actualDuration;
24897 completedWork.treeBaseDuration = treeBaseDuration;
24898 } else {
24899 var _child = completedWork.child;
24900
24901 while (_child !== null) {
24902 var _childUpdateExpirationTime = _child.expirationTime;
24903 var _childChildExpirationTime = _child.childExpirationTime;
24904
24905 if (_childUpdateExpirationTime > newChildExpirationTime) {
24906 newChildExpirationTime = _childUpdateExpirationTime;
24907 }
24908
24909 if (_childChildExpirationTime > newChildExpirationTime) {
24910 newChildExpirationTime = _childChildExpirationTime;
24911 }
24912
24913 _child = _child.sibling;
24914 }
24915 }
24916
24917 completedWork.childExpirationTime = newChildExpirationTime;
24918}
24919
24920function commitRoot(root) {
24921 var renderPriorityLevel = getCurrentPriorityLevel();
24922 runWithPriority$2(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
24923 return null;
24924}
24925
24926function commitRootImpl(root, renderPriorityLevel) {
24927 do {
24928 // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
24929 // means `flushPassiveEffects` will sometimes result in additional
24930 // passive effects. So we need to keep flushing in a loop until there are
24931 // no more pending effects.
24932 // TODO: Might be better if `flushPassiveEffects` did not automatically
24933 // flush synchronous work at the end, to avoid factoring hazards like this.
24934 flushPassiveEffects();
24935 } while (rootWithPendingPassiveEffects !== null);
24936
24937 flushRenderPhaseStrictModeWarningsInDEV();
24938
24939 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24940 {
24941 throw Error("Should not already be working.");
24942 }
24943 }
24944
24945 var finishedWork = root.finishedWork;
24946 var expirationTime = root.finishedExpirationTime;
24947
24948 if (finishedWork === null) {
24949 return null;
24950 }
24951
24952 root.finishedWork = null;
24953 root.finishedExpirationTime = NoWork;
24954
24955 if (!(finishedWork !== root.current)) {
24956 {
24957 throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
24958 }
24959 } // commitRoot never returns a continuation; it always finishes synchronously.
24960 // So we can clear these now to allow a new callback to be scheduled.
24961
24962
24963 root.callbackNode = null;
24964 root.callbackExpirationTime = NoWork;
24965 root.callbackPriority = NoPriority;
24966 root.nextKnownPendingLevel = NoWork;
24967 startCommitTimer(); // Update the first and last pending times on this root. The new first
24968 // pending time is whatever is left on the root fiber.
24969
24970 var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
24971 markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
24972
24973 if (root === workInProgressRoot) {
24974 // We can reset these now that they are finished.
24975 workInProgressRoot = null;
24976 workInProgress = null;
24977 renderExpirationTime = NoWork;
24978 } else {} // This indicates that the last root we worked on is not the same one that
24979 // we're committing now. This most commonly happens when a suspended root
24980 // times out.
24981 // Get the list of effects.
24982
24983
24984 var firstEffect;
24985
24986 if (finishedWork.effectTag > PerformedWork) {
24987 // A fiber's effect list consists only of its children, not itself. So if
24988 // the root has an effect, we need to add it to the end of the list. The
24989 // resulting list is the set that would belong to the root's parent, if it
24990 // had one; that is, all the effects in the tree including the root.
24991 if (finishedWork.lastEffect !== null) {
24992 finishedWork.lastEffect.nextEffect = finishedWork;
24993 firstEffect = finishedWork.firstEffect;
24994 } else {
24995 firstEffect = finishedWork;
24996 }
24997 } else {
24998 // There is no effect on the root.
24999 firstEffect = finishedWork.firstEffect;
25000 }
25001
25002 if (firstEffect !== null) {
25003 var prevExecutionContext = executionContext;
25004 executionContext |= CommitContext;
25005 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
25006
25007 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
25008 // of the effect list for each phase: all mutation effects come before all
25009 // layout effects, and so on.
25010 // The first phase a "before mutation" phase. We use this phase to read the
25011 // state of the host tree right before we mutate it. This is where
25012 // getSnapshotBeforeUpdate is called.
25013
25014 startCommitSnapshotEffectsTimer();
25015 prepareForCommit(root.containerInfo);
25016 nextEffect = firstEffect;
25017
25018 do {
25019 {
25020 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
25021
25022 if (hasCaughtError()) {
25023 if (!(nextEffect !== null)) {
25024 {
25025 throw Error("Should be working on an effect.");
25026 }
25027 }
25028
25029 var error = clearCaughtError();
25030 captureCommitPhaseError(nextEffect, error);
25031 nextEffect = nextEffect.nextEffect;
25032 }
25033 }
25034 } while (nextEffect !== null);
25035
25036 stopCommitSnapshotEffectsTimer();
25037
25038 if (enableProfilerTimer) {
25039 // Mark the current commit time to be shared by all Profilers in this
25040 // batch. This enables them to be grouped later.
25041 recordCommitTime();
25042 } // The next phase is the mutation phase, where we mutate the host tree.
25043
25044
25045 startCommitHostEffectsTimer();
25046 nextEffect = firstEffect;
25047
25048 do {
25049 {
25050 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
25051
25052 if (hasCaughtError()) {
25053 if (!(nextEffect !== null)) {
25054 {
25055 throw Error("Should be working on an effect.");
25056 }
25057 }
25058
25059 var _error = clearCaughtError();
25060
25061 captureCommitPhaseError(nextEffect, _error);
25062 nextEffect = nextEffect.nextEffect;
25063 }
25064 }
25065 } while (nextEffect !== null);
25066
25067 stopCommitHostEffectsTimer();
25068 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
25069 // the mutation phase, so that the previous tree is still current during
25070 // componentWillUnmount, but before the layout phase, so that the finished
25071 // work is current during componentDidMount/Update.
25072
25073 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
25074 // the host tree after it's been mutated. The idiomatic use case for this is
25075 // layout, but class component lifecycles also fire here for legacy reasons.
25076
25077 startCommitLifeCyclesTimer();
25078 nextEffect = firstEffect;
25079
25080 do {
25081 {
25082 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
25083
25084 if (hasCaughtError()) {
25085 if (!(nextEffect !== null)) {
25086 {
25087 throw Error("Should be working on an effect.");
25088 }
25089 }
25090
25091 var _error2 = clearCaughtError();
25092
25093 captureCommitPhaseError(nextEffect, _error2);
25094 nextEffect = nextEffect.nextEffect;
25095 }
25096 }
25097 } while (nextEffect !== null);
25098
25099 stopCommitLifeCyclesTimer();
25100 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
25101 // opportunity to paint.
25102
25103 requestPaint();
25104
25105 if (enableSchedulerTracing) {
25106 popInteractions(prevInteractions);
25107 }
25108
25109 executionContext = prevExecutionContext;
25110 } else {
25111 // No effects.
25112 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
25113 // no effects.
25114 // TODO: Maybe there's a better way to report this.
25115
25116 startCommitSnapshotEffectsTimer();
25117 stopCommitSnapshotEffectsTimer();
25118
25119 if (enableProfilerTimer) {
25120 recordCommitTime();
25121 }
25122
25123 startCommitHostEffectsTimer();
25124 stopCommitHostEffectsTimer();
25125 startCommitLifeCyclesTimer();
25126 stopCommitLifeCyclesTimer();
25127 }
25128
25129 stopCommitTimer();
25130 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
25131
25132 if (rootDoesHavePassiveEffects) {
25133 // This commit has passive effects. Stash a reference to them. But don't
25134 // schedule a callback until after flushing layout work.
25135 rootDoesHavePassiveEffects = false;
25136 rootWithPendingPassiveEffects = root;
25137 pendingPassiveEffectsExpirationTime = expirationTime;
25138 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
25139 } else {
25140 // We are done with the effect chain at this point so let's clear the
25141 // nextEffect pointers to assist with GC. If we have passive effects, we'll
25142 // clear this in flushPassiveEffects.
25143 nextEffect = firstEffect;
25144
25145 while (nextEffect !== null) {
25146 var nextNextEffect = nextEffect.nextEffect;
25147 nextEffect.nextEffect = null;
25148 nextEffect = nextNextEffect;
25149 }
25150 } // Check if there's remaining work on this root
25151
25152
25153 var remainingExpirationTime = root.firstPendingTime;
25154
25155 if (remainingExpirationTime !== NoWork) {
25156 if (enableSchedulerTracing) {
25157 if (spawnedWorkDuringRender !== null) {
25158 var expirationTimes = spawnedWorkDuringRender;
25159 spawnedWorkDuringRender = null;
25160
25161 for (var i = 0; i < expirationTimes.length; i++) {
25162 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
25163 }
25164 }
25165
25166 schedulePendingInteractions(root, remainingExpirationTime);
25167 }
25168 } else {
25169 // If there's no remaining work, we can clear the set of already failed
25170 // error boundaries.
25171 legacyErrorBoundariesThatAlreadyFailed = null;
25172 }
25173
25174 if (enableSchedulerTracing) {
25175 if (!rootDidHavePassiveEffects) {
25176 // If there are no passive effects, then we can complete the pending interactions.
25177 // Otherwise, we'll wait until after the passive effects are flushed.
25178 // Wait to do this until after remaining work has been scheduled,
25179 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
25180 finishPendingInteractions(root, expirationTime);
25181 }
25182 }
25183
25184 if (remainingExpirationTime === Sync) {
25185 // Count the number of times the root synchronously re-renders without
25186 // finishing. If there are too many, it indicates an infinite update loop.
25187 if (root === rootWithNestedUpdates) {
25188 nestedUpdateCount++;
25189 } else {
25190 nestedUpdateCount = 0;
25191 rootWithNestedUpdates = root;
25192 }
25193 } else {
25194 nestedUpdateCount = 0;
25195 }
25196
25197 onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
25198 // additional work on this root is scheduled.
25199
25200 ensureRootIsScheduled(root);
25201
25202 if (hasUncaughtError) {
25203 hasUncaughtError = false;
25204 var _error3 = firstUncaughtError;
25205 firstUncaughtError = null;
25206 throw _error3;
25207 }
25208
25209 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
25210 // This is a legacy edge case. We just committed the initial mount of
25211 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
25212 // synchronously, but layout updates should be deferred until the end
25213 // of the batch.
25214 return null;
25215 } // If layout work was scheduled, flush it now.
25216
25217
25218 flushSyncCallbackQueue();
25219 return null;
25220}
25221
25222function commitBeforeMutationEffects() {
25223 while (nextEffect !== null) {
25224 var effectTag = nextEffect.effectTag;
25225
25226 if ((effectTag & Snapshot) !== NoEffect) {
25227 setCurrentFiber(nextEffect);
25228 recordEffect();
25229 var current$$1 = nextEffect.alternate;
25230 commitBeforeMutationLifeCycles(current$$1, nextEffect);
25231 resetCurrentFiber();
25232 }
25233
25234 if ((effectTag & Passive) !== NoEffect) {
25235 // If there are passive effects, schedule a callback to flush at
25236 // the earliest opportunity.
25237 if (!rootDoesHavePassiveEffects) {
25238 rootDoesHavePassiveEffects = true;
25239 scheduleCallback(NormalPriority, function () {
25240 flushPassiveEffects();
25241 return null;
25242 });
25243 }
25244 }
25245
25246 nextEffect = nextEffect.nextEffect;
25247 }
25248}
25249
25250function commitMutationEffects(root, renderPriorityLevel) {
25251 // TODO: Should probably move the bulk of this function to commitWork.
25252 while (nextEffect !== null) {
25253 setCurrentFiber(nextEffect);
25254 var effectTag = nextEffect.effectTag;
25255
25256 if (effectTag & ContentReset) {
25257 commitResetTextContent(nextEffect);
25258 }
25259
25260 if (effectTag & Ref) {
25261 var current$$1 = nextEffect.alternate;
25262
25263 if (current$$1 !== null) {
25264 commitDetachRef(current$$1);
25265 }
25266 } // The following switch statement is only concerned about placement,
25267 // updates, and deletions. To avoid needing to add a case for every possible
25268 // bitmap value, we remove the secondary effects from the effect tag and
25269 // switch on that value.
25270
25271
25272 var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
25273
25274 switch (primaryEffectTag) {
25275 case Placement:
25276 {
25277 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25278 // inserted, before any life-cycles like componentDidMount gets called.
25279 // TODO: findDOMNode doesn't rely on this any more but isMounted does
25280 // and isMounted is deprecated anyway so we should be able to kill this.
25281
25282 nextEffect.effectTag &= ~Placement;
25283 break;
25284 }
25285
25286 case PlacementAndUpdate:
25287 {
25288 // Placement
25289 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25290 // inserted, before any life-cycles like componentDidMount gets called.
25291
25292 nextEffect.effectTag &= ~Placement; // Update
25293
25294 var _current = nextEffect.alternate;
25295 commitWork(_current, nextEffect);
25296 break;
25297 }
25298
25299 case Hydrating:
25300 {
25301 nextEffect.effectTag &= ~Hydrating;
25302 break;
25303 }
25304
25305 case HydratingAndUpdate:
25306 {
25307 nextEffect.effectTag &= ~Hydrating; // Update
25308
25309 var _current2 = nextEffect.alternate;
25310 commitWork(_current2, nextEffect);
25311 break;
25312 }
25313
25314 case Update:
25315 {
25316 var _current3 = nextEffect.alternate;
25317 commitWork(_current3, nextEffect);
25318 break;
25319 }
25320
25321 case Deletion:
25322 {
25323 commitDeletion(root, nextEffect, renderPriorityLevel);
25324 break;
25325 }
25326 } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
25327
25328
25329 recordEffect();
25330 resetCurrentFiber();
25331 nextEffect = nextEffect.nextEffect;
25332 }
25333}
25334
25335function commitLayoutEffects(root, committedExpirationTime) {
25336 // TODO: Should probably move the bulk of this function to commitWork.
25337 while (nextEffect !== null) {
25338 setCurrentFiber(nextEffect);
25339 var effectTag = nextEffect.effectTag;
25340
25341 if (effectTag & (Update | Callback)) {
25342 recordEffect();
25343 var current$$1 = nextEffect.alternate;
25344 commitLifeCycles(root, current$$1, nextEffect, committedExpirationTime);
25345 }
25346
25347 if (effectTag & Ref) {
25348 recordEffect();
25349 commitAttachRef(nextEffect);
25350 }
25351
25352 resetCurrentFiber();
25353 nextEffect = nextEffect.nextEffect;
25354 }
25355}
25356
25357function flushPassiveEffects() {
25358 if (pendingPassiveEffectsRenderPriority !== NoPriority) {
25359 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
25360 pendingPassiveEffectsRenderPriority = NoPriority;
25361 return runWithPriority$2(priorityLevel, flushPassiveEffectsImpl);
25362 }
25363}
25364
25365function flushPassiveEffectsImpl() {
25366 if (rootWithPendingPassiveEffects === null) {
25367 return false;
25368 }
25369
25370 var root = rootWithPendingPassiveEffects;
25371 var expirationTime = pendingPassiveEffectsExpirationTime;
25372 rootWithPendingPassiveEffects = null;
25373 pendingPassiveEffectsExpirationTime = NoWork;
25374
25375 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25376 {
25377 throw Error("Cannot flush passive effects while already rendering.");
25378 }
25379 }
25380
25381 var prevExecutionContext = executionContext;
25382 executionContext |= CommitContext;
25383 var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root
25384 // fiber, because the root is not part of its own effect list. This could
25385 // change in the future.
25386
25387 var effect = root.current.firstEffect;
25388
25389 while (effect !== null) {
25390 {
25391 setCurrentFiber(effect);
25392 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
25393
25394 if (hasCaughtError()) {
25395 if (!(effect !== null)) {
25396 {
25397 throw Error("Should be working on an effect.");
25398 }
25399 }
25400
25401 var error = clearCaughtError();
25402 captureCommitPhaseError(effect, error);
25403 }
25404
25405 resetCurrentFiber();
25406 }
25407
25408 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
25409
25410 effect.nextEffect = null;
25411 effect = nextNextEffect;
25412 }
25413
25414 if (enableSchedulerTracing) {
25415 popInteractions(prevInteractions);
25416 finishPendingInteractions(root, expirationTime);
25417 }
25418
25419 executionContext = prevExecutionContext;
25420 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
25421 // exceeds the limit, we'll fire a warning.
25422
25423 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
25424 return true;
25425}
25426
25427function isAlreadyFailedLegacyErrorBoundary(instance) {
25428 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
25429}
25430function markLegacyErrorBoundaryAsFailed(instance) {
25431 if (legacyErrorBoundariesThatAlreadyFailed === null) {
25432 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
25433 } else {
25434 legacyErrorBoundariesThatAlreadyFailed.add(instance);
25435 }
25436}
25437
25438function prepareToThrowUncaughtError(error) {
25439 if (!hasUncaughtError) {
25440 hasUncaughtError = true;
25441 firstUncaughtError = error;
25442 }
25443}
25444
25445var onUncaughtError = prepareToThrowUncaughtError;
25446
25447function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
25448 var errorInfo = createCapturedValue(error, sourceFiber);
25449 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
25450 enqueueUpdate(rootFiber, update);
25451 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
25452
25453 if (root !== null) {
25454 ensureRootIsScheduled(root);
25455 schedulePendingInteractions(root, Sync);
25456 }
25457}
25458
25459function captureCommitPhaseError(sourceFiber, error) {
25460 if (sourceFiber.tag === HostRoot) {
25461 // Error was thrown at the root. There is no parent, so the root
25462 // itself should capture it.
25463 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
25464 return;
25465 }
25466
25467 var fiber = sourceFiber.return;
25468
25469 while (fiber !== null) {
25470 if (fiber.tag === HostRoot) {
25471 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
25472 return;
25473 } else if (fiber.tag === ClassComponent) {
25474 var ctor = fiber.type;
25475 var instance = fiber.stateNode;
25476
25477 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
25478 var errorInfo = createCapturedValue(error, sourceFiber);
25479 var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
25480 Sync);
25481 enqueueUpdate(fiber, update);
25482 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
25483
25484 if (root !== null) {
25485 ensureRootIsScheduled(root);
25486 schedulePendingInteractions(root, Sync);
25487 }
25488
25489 return;
25490 }
25491 }
25492
25493 fiber = fiber.return;
25494 }
25495}
25496function pingSuspendedRoot(root, thenable, suspendedTime) {
25497 var pingCache = root.pingCache;
25498
25499 if (pingCache !== null) {
25500 // The thenable resolved, so we no longer need to memoize, because it will
25501 // never be thrown again.
25502 pingCache.delete(thenable);
25503 }
25504
25505 if (workInProgressRoot === root && renderExpirationTime === suspendedTime) {
25506 // Received a ping at the same priority level at which we're currently
25507 // rendering. We might want to restart this render. This should mirror
25508 // the logic of whether or not a root suspends once it completes.
25509 // TODO: If we're rendering sync either due to Sync, Batched or expired,
25510 // we should probably never restart.
25511 // If we're suspended with delay, we'll always suspend so we can always
25512 // restart. If we're suspended without any updates, it might be a retry.
25513 // If it's early in the retry we can restart. We can't know for sure
25514 // whether we'll eventually process an update during this render pass,
25515 // but it's somewhat unlikely that we get to a ping before that, since
25516 // getting to the root most update is usually very fast.
25517 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
25518 // Restart from the root. Don't need to schedule a ping because
25519 // we're already working on this tree.
25520 prepareFreshStack(root, renderExpirationTime);
25521 } else {
25522 // Even though we can't restart right now, we might get an
25523 // opportunity later. So we mark this render as having a ping.
25524 workInProgressRootHasPendingPing = true;
25525 }
25526
25527 return;
25528 }
25529
25530 if (!isRootSuspendedAtTime(root, suspendedTime)) {
25531 // The root is no longer suspended at this time.
25532 return;
25533 }
25534
25535 var lastPingedTime = root.lastPingedTime;
25536
25537 if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
25538 // There's already a lower priority ping scheduled.
25539 return;
25540 } // Mark the time at which this ping was scheduled.
25541
25542
25543 root.lastPingedTime = suspendedTime;
25544
25545 if (root.finishedExpirationTime === suspendedTime) {
25546 // If there's a pending fallback waiting to commit, throw it away.
25547 root.finishedExpirationTime = NoWork;
25548 root.finishedWork = null;
25549 }
25550
25551 ensureRootIsScheduled(root);
25552 schedulePendingInteractions(root, suspendedTime);
25553}
25554
25555function retryTimedOutBoundary(boundaryFiber, retryTime) {
25556 // The boundary fiber (a Suspense component or SuspenseList component)
25557 // previously was rendered in its fallback state. One of the promises that
25558 // suspended it has resolved, which means at least part of the tree was
25559 // likely unblocked. Try rendering again, at a new expiration time.
25560 if (retryTime === NoWork) {
25561 var suspenseConfig = null; // Retries don't carry over the already committed update.
25562
25563 var currentTime = requestCurrentTimeForUpdate();
25564 retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
25565 } // TODO: Special case idle priority?
25566
25567
25568 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
25569
25570 if (root !== null) {
25571 ensureRootIsScheduled(root);
25572 schedulePendingInteractions(root, retryTime);
25573 }
25574}
25575
25576function retryDehydratedSuspenseBoundary(boundaryFiber) {
25577 var suspenseState = boundaryFiber.memoizedState;
25578 var retryTime = NoWork;
25579
25580 if (suspenseState !== null) {
25581 retryTime = suspenseState.retryTime;
25582 }
25583
25584 retryTimedOutBoundary(boundaryFiber, retryTime);
25585}
25586function resolveRetryThenable(boundaryFiber, thenable) {
25587 var retryTime = NoWork; // Default
25588
25589 var retryCache;
25590
25591 if (enableSuspenseServerRenderer) {
25592 switch (boundaryFiber.tag) {
25593 case SuspenseComponent:
25594 retryCache = boundaryFiber.stateNode;
25595 var suspenseState = boundaryFiber.memoizedState;
25596
25597 if (suspenseState !== null) {
25598 retryTime = suspenseState.retryTime;
25599 }
25600
25601 break;
25602
25603 case SuspenseListComponent:
25604 retryCache = boundaryFiber.stateNode;
25605 break;
25606
25607 default:
25608 {
25609 {
25610 throw Error("Pinged unknown suspense boundary type. This is probably a bug in React.");
25611 }
25612 }
25613
25614 }
25615 } else {
25616 retryCache = boundaryFiber.stateNode;
25617 }
25618
25619 if (retryCache !== null) {
25620 // The thenable resolved, so we no longer need to memoize, because it will
25621 // never be thrown again.
25622 retryCache.delete(thenable);
25623 }
25624
25625 retryTimedOutBoundary(boundaryFiber, retryTime);
25626} // Computes the next Just Noticeable Difference (JND) boundary.
25627// The theory is that a person can't tell the difference between small differences in time.
25628// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
25629// difference in the experience. However, waiting for longer might mean that we can avoid
25630// showing an intermediate loading state. The longer we have already waited, the harder it
25631// is to tell small differences in time. Therefore, the longer we've already waited,
25632// the longer we can wait additionally. At some point we have to give up though.
25633// We pick a train model where the next boundary commits at a consistent schedule.
25634// These particular numbers are vague estimates. We expect to adjust them based on research.
25635
25636function jnd(timeElapsed) {
25637 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
25638}
25639
25640function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
25641 var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
25642
25643 if (busyMinDurationMs <= 0) {
25644 return 0;
25645 }
25646
25647 var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
25648
25649 var currentTimeMs = now();
25650 var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
25651 var timeElapsed = currentTimeMs - eventTimeMs;
25652
25653 if (timeElapsed <= busyDelayMs) {
25654 // If we haven't yet waited longer than the initial delay, we don't
25655 // have to wait any additional time.
25656 return 0;
25657 }
25658
25659 var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
25660
25661 return msUntilTimeout;
25662}
25663
25664function checkForNestedUpdates() {
25665 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
25666 nestedUpdateCount = 0;
25667 rootWithNestedUpdates = null;
25668
25669 {
25670 {
25671 throw 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.");
25672 }
25673 }
25674 }
25675
25676 {
25677 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
25678 nestedPassiveUpdateCount = 0;
25679 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.');
25680 }
25681 }
25682}
25683
25684function flushRenderPhaseStrictModeWarningsInDEV() {
25685 {
25686 ReactStrictModeWarnings.flushLegacyContextWarning();
25687
25688 if (warnAboutDeprecatedLifecycles) {
25689 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
25690 }
25691 }
25692}
25693
25694function stopFinishedWorkLoopTimer() {
25695 var didCompleteRoot = true;
25696 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25697 interruptedBy = null;
25698}
25699
25700function stopInterruptedWorkLoopTimer() {
25701 // TODO: Track which fiber caused the interruption.
25702 var didCompleteRoot = false;
25703 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25704 interruptedBy = null;
25705}
25706
25707function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
25708 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime) {
25709 interruptedBy = fiberThatReceivedUpdate;
25710 }
25711}
25712
25713var didWarnStateUpdateForUnmountedComponent = null;
25714
25715function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
25716 {
25717 var tag = fiber.tag;
25718
25719 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
25720 // Only warn for user-defined components, not internal ones like Suspense.
25721 return;
25722 } // We show the whole stack but dedupe on the top component's name because
25723 // the problematic code almost always lies inside that component.
25724
25725
25726 var componentName = getComponentName(fiber.type) || 'ReactComponent';
25727
25728 if (didWarnStateUpdateForUnmountedComponent !== null) {
25729 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
25730 return;
25731 }
25732
25733 didWarnStateUpdateForUnmountedComponent.add(componentName);
25734 } else {
25735 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
25736 }
25737
25738 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));
25739 }
25740}
25741
25742var beginWork$$1;
25743
25744if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
25745 var dummyFiber = null;
25746
25747 beginWork$$1 = function (current$$1, unitOfWork, expirationTime) {
25748 // If a component throws an error, we replay it again in a synchronously
25749 // dispatched event, so that the debugger will treat it as an uncaught
25750 // error See ReactErrorUtils for more information.
25751 // Before entering the begin phase, copy the work-in-progress onto a dummy
25752 // fiber. If beginWork throws, we'll use this to reset the state.
25753 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
25754
25755 try {
25756 return beginWork$1(current$$1, unitOfWork, expirationTime);
25757 } catch (originalError) {
25758 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
25759 // Don't replay promises. Treat everything else like an error.
25760 throw originalError;
25761 } // Keep this code in sync with handleError; any changes here must have
25762 // corresponding changes there.
25763
25764
25765 resetContextDependencies();
25766 resetHooks(); // Don't reset current debug fiber, since we're about to work on the
25767 // same fiber again.
25768 // Unwind the failed stack frame
25769
25770 unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
25771
25772 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
25773
25774 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
25775 // Reset the profiler timer.
25776 startProfilerTimer(unitOfWork);
25777 } // Run beginWork again.
25778
25779
25780 invokeGuardedCallback(null, beginWork$1, null, current$$1, unitOfWork, expirationTime);
25781
25782 if (hasCaughtError()) {
25783 var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
25784 // Rethrow this error instead of the original one.
25785
25786 throw replayError;
25787 } else {
25788 // This branch is reachable if the render phase is impure.
25789 throw originalError;
25790 }
25791 }
25792 };
25793} else {
25794 beginWork$$1 = beginWork$1;
25795}
25796
25797var didWarnAboutUpdateInRender = false;
25798var didWarnAboutUpdateInGetChildContext = false;
25799
25800function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
25801 {
25802 if (fiber.tag === ClassComponent) {
25803 switch (phase) {
25804 case 'getChildContext':
25805 if (didWarnAboutUpdateInGetChildContext) {
25806 return;
25807 }
25808
25809 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
25810 didWarnAboutUpdateInGetChildContext = true;
25811 break;
25812
25813 case 'render':
25814 if (didWarnAboutUpdateInRender) {
25815 return;
25816 }
25817
25818 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.');
25819 didWarnAboutUpdateInRender = true;
25820 break;
25821 }
25822 }
25823 }
25824} // a 'shared' variable that changes when act() opens/closes in tests.
25825
25826
25827var IsThisRendererActing = {
25828 current: false
25829};
25830function warnIfNotScopedWithMatchingAct(fiber) {
25831 {
25832 if (warnsIfNotActing === true && IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
25833 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));
25834 }
25835 }
25836}
25837function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
25838 {
25839 if (warnsIfNotActing === true && (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25840 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));
25841 }
25842 }
25843}
25844
25845function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
25846 {
25847 if (warnsIfNotActing === true && executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25848 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));
25849 }
25850 }
25851}
25852
25853var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
25854
25855var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
25856// scheduler is the actual recommendation. The alternative could be a testing build,
25857// a new lib, or whatever; we dunno just yet. This message is for early adopters
25858// to get their tests right.
25859
25860function warnIfUnmockedScheduler(fiber) {
25861 {
25862 if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === undefined) {
25863 if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
25864 didWarnAboutUnmockedScheduler = true;
25865 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');
25866 } else if (warnAboutUnmockedScheduler === true) {
25867 didWarnAboutUnmockedScheduler = true;
25868 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');
25869 }
25870 }
25871 }
25872}
25873var componentsThatTriggeredHighPriSuspend = null;
25874function checkForWrongSuspensePriorityInDEV(sourceFiber) {
25875 {
25876 var currentPriorityLevel = getCurrentPriorityLevel();
25877
25878 if ((sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$2 || currentPriorityLevel === ImmediatePriority)) {
25879 var workInProgressNode = sourceFiber;
25880
25881 while (workInProgressNode !== null) {
25882 // Add the component that triggered the suspense
25883 var current$$1 = workInProgressNode.alternate;
25884
25885 if (current$$1 !== null) {
25886 // TODO: warn component that triggers the high priority
25887 // suspend is the HostRoot
25888 switch (workInProgressNode.tag) {
25889 case ClassComponent:
25890 // Loop through the component's update queue and see whether the component
25891 // has triggered any high priority updates
25892 var updateQueue = current$$1.updateQueue;
25893
25894 if (updateQueue !== null) {
25895 var update = updateQueue.firstUpdate;
25896
25897 while (update !== null) {
25898 var priorityLevel = update.priority;
25899
25900 if (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority) {
25901 if (componentsThatTriggeredHighPriSuspend === null) {
25902 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
25903 } else {
25904 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
25905 }
25906
25907 break;
25908 }
25909
25910 update = update.next;
25911 }
25912 }
25913
25914 break;
25915
25916 case FunctionComponent:
25917 case ForwardRef:
25918 case SimpleMemoComponent:
25919 if (workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null) {
25920 var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether
25921 // the component has triggered any high pri updates
25922
25923 while (_update !== null) {
25924 var priority = _update.priority;
25925
25926 if (priority === UserBlockingPriority$2 || priority === ImmediatePriority) {
25927 if (componentsThatTriggeredHighPriSuspend === null) {
25928 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
25929 } else {
25930 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
25931 }
25932
25933 break;
25934 }
25935
25936 if (_update.next === workInProgressNode.memoizedState.baseUpdate) {
25937 break;
25938 }
25939
25940 _update = _update.next;
25941 }
25942 }
25943
25944 break;
25945
25946 default:
25947 break;
25948 }
25949 }
25950
25951 workInProgressNode = workInProgressNode.return;
25952 }
25953 }
25954 }
25955}
25956
25957function flushSuspensePriorityWarningInDEV() {
25958 {
25959 if (componentsThatTriggeredHighPriSuspend !== null) {
25960 var componentNames = [];
25961 componentsThatTriggeredHighPriSuspend.forEach(function (name) {
25962 return componentNames.push(name);
25963 });
25964 componentsThatTriggeredHighPriSuspend = null;
25965
25966 if (componentNames.length > 0) {
25967 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 useTransition to learn how ' + 'to implement this pattern.', // TODO: Add link to React docs with more information, once it exists
25968 componentNames.sort().join(', '));
25969 }
25970 }
25971 }
25972}
25973
25974function computeThreadID(root, expirationTime) {
25975 // Interaction threads are unique per root and expiration time.
25976 return expirationTime * 1000 + root.interactionThreadID;
25977}
25978
25979function markSpawnedWork(expirationTime) {
25980 if (!enableSchedulerTracing) {
25981 return;
25982 }
25983
25984 if (spawnedWorkDuringRender === null) {
25985 spawnedWorkDuringRender = [expirationTime];
25986 } else {
25987 spawnedWorkDuringRender.push(expirationTime);
25988 }
25989}
25990
25991function scheduleInteractions(root, expirationTime, interactions) {
25992 if (!enableSchedulerTracing) {
25993 return;
25994 }
25995
25996 if (interactions.size > 0) {
25997 var pendingInteractionMap = root.pendingInteractionMap;
25998 var pendingInteractions = pendingInteractionMap.get(expirationTime);
25999
26000 if (pendingInteractions != null) {
26001 interactions.forEach(function (interaction) {
26002 if (!pendingInteractions.has(interaction)) {
26003 // Update the pending async work count for previously unscheduled interaction.
26004 interaction.__count++;
26005 }
26006
26007 pendingInteractions.add(interaction);
26008 });
26009 } else {
26010 pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
26011
26012 interactions.forEach(function (interaction) {
26013 interaction.__count++;
26014 });
26015 }
26016
26017 var subscriber = tracing.__subscriberRef.current;
26018
26019 if (subscriber !== null) {
26020 var threadID = computeThreadID(root, expirationTime);
26021 subscriber.onWorkScheduled(interactions, threadID);
26022 }
26023 }
26024}
26025
26026function schedulePendingInteractions(root, expirationTime) {
26027 // This is called when work is scheduled on a root.
26028 // It associates the current interactions with the newly-scheduled expiration.
26029 // They will be restored when that expiration is later committed.
26030 if (!enableSchedulerTracing) {
26031 return;
26032 }
26033
26034 scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current);
26035}
26036
26037function startWorkOnPendingInteractions(root, expirationTime) {
26038 // This is called when new work is started on a root.
26039 if (!enableSchedulerTracing) {
26040 return;
26041 } // Determine which interactions this batch of work currently includes, So that
26042 // we can accurately attribute time spent working on it, And so that cascading
26043 // work triggered during the render phase will be associated with it.
26044
26045
26046 var interactions = new Set();
26047 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26048 if (scheduledExpirationTime >= expirationTime) {
26049 scheduledInteractions.forEach(function (interaction) {
26050 return interactions.add(interaction);
26051 });
26052 }
26053 }); // Store the current set of interactions on the FiberRoot for a few reasons:
26054 // We can re-use it in hot functions like performConcurrentWorkOnRoot()
26055 // without having to recalculate it. We will also use it in commitWork() to
26056 // pass to any Profiler onRender() hooks. This also provides DevTools with a
26057 // way to access it when the onCommitRoot() hook is called.
26058
26059 root.memoizedInteractions = interactions;
26060
26061 if (interactions.size > 0) {
26062 var subscriber = tracing.__subscriberRef.current;
26063
26064 if (subscriber !== null) {
26065 var threadID = computeThreadID(root, expirationTime);
26066
26067 try {
26068 subscriber.onWorkStarted(interactions, threadID);
26069 } catch (error) {
26070 // If the subscriber throws, rethrow it in a separate task
26071 scheduleCallback(ImmediatePriority, function () {
26072 throw error;
26073 });
26074 }
26075 }
26076 }
26077}
26078
26079function finishPendingInteractions(root, committedExpirationTime) {
26080 if (!enableSchedulerTracing) {
26081 return;
26082 }
26083
26084 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
26085 var subscriber;
26086
26087 try {
26088 subscriber = tracing.__subscriberRef.current;
26089
26090 if (subscriber !== null && root.memoizedInteractions.size > 0) {
26091 var threadID = computeThreadID(root, committedExpirationTime);
26092 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
26093 }
26094 } catch (error) {
26095 // If the subscriber throws, rethrow it in a separate task
26096 scheduleCallback(ImmediatePriority, function () {
26097 throw error;
26098 });
26099 } finally {
26100 // Clear completed interactions from the pending Map.
26101 // Unless the render was suspended or cascading work was scheduled,
26102 // In which case– leave pending interactions until the subsequent render.
26103 var pendingInteractionMap = root.pendingInteractionMap;
26104 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26105 // Only decrement the pending interaction count if we're done.
26106 // If there's still work at the current priority,
26107 // That indicates that we are waiting for suspense data.
26108 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
26109 pendingInteractionMap.delete(scheduledExpirationTime);
26110 scheduledInteractions.forEach(function (interaction) {
26111 interaction.__count--;
26112
26113 if (subscriber !== null && interaction.__count === 0) {
26114 try {
26115 subscriber.onInteractionScheduledWorkCompleted(interaction);
26116 } catch (error) {
26117 // If the subscriber throws, rethrow it in a separate task
26118 scheduleCallback(ImmediatePriority, function () {
26119 throw error;
26120 });
26121 }
26122 }
26123 });
26124 }
26125 });
26126 }
26127}
26128
26129var onCommitFiberRoot = null;
26130var onCommitFiberUnmount = null;
26131var hasLoggedError = false;
26132var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
26133function injectInternals(internals) {
26134 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
26135 // No DevTools
26136 return false;
26137 }
26138
26139 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
26140
26141 if (hook.isDisabled) {
26142 // This isn't a real property on the hook, but it can be set to opt out
26143 // of DevTools integration and associated warnings and logs.
26144 // https://github.com/facebook/react/issues/3877
26145 return true;
26146 }
26147
26148 if (!hook.supportsFiber) {
26149 {
26150 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');
26151 } // DevTools exists, even though it doesn't support Fiber.
26152
26153
26154 return true;
26155 }
26156
26157 try {
26158 var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
26159
26160 onCommitFiberRoot = function (root, expirationTime) {
26161 try {
26162 var didError = (root.current.effectTag & DidCapture) === DidCapture;
26163
26164 if (enableProfilerTimer) {
26165 var currentTime = getCurrentTime();
26166 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
26167 hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
26168 } else {
26169 hook.onCommitFiberRoot(rendererID, root, undefined, didError);
26170 }
26171 } catch (err) {
26172 if (true && !hasLoggedError) {
26173 hasLoggedError = true;
26174 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26175 }
26176 }
26177 };
26178
26179 onCommitFiberUnmount = function (fiber) {
26180 try {
26181 hook.onCommitFiberUnmount(rendererID, fiber);
26182 } catch (err) {
26183 if (true && !hasLoggedError) {
26184 hasLoggedError = true;
26185 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26186 }
26187 }
26188 };
26189 } catch (err) {
26190 // Catch all errors because it is unsafe to throw during initialization.
26191 {
26192 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
26193 }
26194 } // DevTools exists
26195
26196
26197 return true;
26198}
26199function onCommitRoot(root, expirationTime) {
26200 if (typeof onCommitFiberRoot === 'function') {
26201 onCommitFiberRoot(root, expirationTime);
26202 }
26203}
26204function onCommitUnmount(fiber) {
26205 if (typeof onCommitFiberUnmount === 'function') {
26206 onCommitFiberUnmount(fiber);
26207 }
26208}
26209
26210var hasBadMapPolyfill;
26211
26212{
26213 hasBadMapPolyfill = false;
26214
26215 try {
26216 var nonExtensibleObject = Object.preventExtensions({});
26217 var testMap = new Map([[nonExtensibleObject, null]]);
26218 var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
26219 // https://github.com/rollup/rollup/issues/1771
26220 // TODO: we can remove these if Rollup fixes the bug.
26221
26222 testMap.set(0, 0);
26223 testSet.add(0);
26224 } catch (e) {
26225 // TODO: Consider warning about bad polyfills
26226 hasBadMapPolyfill = true;
26227 }
26228}
26229
26230var debugCounter = 1;
26231
26232function FiberNode(tag, pendingProps, key, mode) {
26233 // Instance
26234 this.tag = tag;
26235 this.key = key;
26236 this.elementType = null;
26237 this.type = null;
26238 this.stateNode = null; // Fiber
26239
26240 this.return = null;
26241 this.child = null;
26242 this.sibling = null;
26243 this.index = 0;
26244 this.ref = null;
26245 this.pendingProps = pendingProps;
26246 this.memoizedProps = null;
26247 this.updateQueue = null;
26248 this.memoizedState = null;
26249 this.dependencies = null;
26250 this.mode = mode; // Effects
26251
26252 this.effectTag = NoEffect;
26253 this.nextEffect = null;
26254 this.firstEffect = null;
26255 this.lastEffect = null;
26256 this.expirationTime = NoWork;
26257 this.childExpirationTime = NoWork;
26258 this.alternate = null;
26259
26260 if (enableProfilerTimer) {
26261 // Note: The following is done to avoid a v8 performance cliff.
26262 //
26263 // Initializing the fields below to smis and later updating them with
26264 // double values will cause Fibers to end up having separate shapes.
26265 // This behavior/bug has something to do with Object.preventExtension().
26266 // Fortunately this only impacts DEV builds.
26267 // Unfortunately it makes React unusably slow for some applications.
26268 // To work around this, initialize the fields below with doubles.
26269 //
26270 // Learn more about this here:
26271 // https://github.com/facebook/react/issues/14365
26272 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
26273 this.actualDuration = Number.NaN;
26274 this.actualStartTime = Number.NaN;
26275 this.selfBaseDuration = Number.NaN;
26276 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
26277 // This won't trigger the performance cliff mentioned above,
26278 // and it simplifies other profiler code (including DevTools).
26279
26280 this.actualDuration = 0;
26281 this.actualStartTime = -1;
26282 this.selfBaseDuration = 0;
26283 this.treeBaseDuration = 0;
26284 } // This is normally DEV-only except www when it adds listeners.
26285 // TODO: remove the User Timing integration in favor of Root Events.
26286
26287
26288 if (enableUserTimingAPI) {
26289 this._debugID = debugCounter++;
26290 this._debugIsCurrentlyTiming = false;
26291 }
26292
26293 {
26294 this._debugSource = null;
26295 this._debugOwner = null;
26296 this._debugNeedsRemount = false;
26297 this._debugHookTypes = null;
26298
26299 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
26300 Object.preventExtensions(this);
26301 }
26302 }
26303} // This is a constructor function, rather than a POJO constructor, still
26304// please ensure we do the following:
26305// 1) Nobody should add any instance methods on this. Instance methods can be
26306// more difficult to predict when they get optimized and they are almost
26307// never inlined properly in static compilers.
26308// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
26309// always know when it is a fiber.
26310// 3) We might want to experiment with using numeric keys since they are easier
26311// to optimize in a non-JIT environment.
26312// 4) We can easily go from a constructor to a createFiber object literal if that
26313// is faster.
26314// 5) It should be easy to port this to a C struct and keep a C implementation
26315// compatible.
26316
26317
26318var createFiber = function (tag, pendingProps, key, mode) {
26319 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
26320 return new FiberNode(tag, pendingProps, key, mode);
26321};
26322
26323function shouldConstruct(Component) {
26324 var prototype = Component.prototype;
26325 return !!(prototype && prototype.isReactComponent);
26326}
26327
26328function isSimpleFunctionComponent(type) {
26329 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
26330}
26331function resolveLazyComponentTag(Component) {
26332 if (typeof Component === 'function') {
26333 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
26334 } else if (Component !== undefined && Component !== null) {
26335 var $$typeof = Component.$$typeof;
26336
26337 if ($$typeof === REACT_FORWARD_REF_TYPE) {
26338 return ForwardRef;
26339 }
26340
26341 if ($$typeof === REACT_MEMO_TYPE) {
26342 return MemoComponent;
26343 }
26344 }
26345
26346 return IndeterminateComponent;
26347} // This is used to create an alternate fiber to do work on.
26348
26349function createWorkInProgress(current, pendingProps, expirationTime) {
26350 var workInProgress = current.alternate;
26351
26352 if (workInProgress === null) {
26353 // We use a double buffering pooling technique because we know that we'll
26354 // only ever need at most two versions of a tree. We pool the "other" unused
26355 // node that we're free to reuse. This is lazily created to avoid allocating
26356 // extra objects for things that are never updated. It also allow us to
26357 // reclaim the extra memory if needed.
26358 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
26359 workInProgress.elementType = current.elementType;
26360 workInProgress.type = current.type;
26361 workInProgress.stateNode = current.stateNode;
26362
26363 {
26364 // DEV-only fields
26365 workInProgress._debugID = current._debugID;
26366 workInProgress._debugSource = current._debugSource;
26367 workInProgress._debugOwner = current._debugOwner;
26368 workInProgress._debugHookTypes = current._debugHookTypes;
26369 }
26370
26371 workInProgress.alternate = current;
26372 current.alternate = workInProgress;
26373 } else {
26374 workInProgress.pendingProps = pendingProps; // We already have an alternate.
26375 // Reset the effect tag.
26376
26377 workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
26378
26379 workInProgress.nextEffect = null;
26380 workInProgress.firstEffect = null;
26381 workInProgress.lastEffect = null;
26382
26383 if (enableProfilerTimer) {
26384 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
26385 // This prevents time from endlessly accumulating in new commits.
26386 // This has the downside of resetting values for different priority renders,
26387 // But works for yielding (the common case) and should support resuming.
26388 workInProgress.actualDuration = 0;
26389 workInProgress.actualStartTime = -1;
26390 }
26391 }
26392
26393 workInProgress.childExpirationTime = current.childExpirationTime;
26394 workInProgress.expirationTime = current.expirationTime;
26395 workInProgress.child = current.child;
26396 workInProgress.memoizedProps = current.memoizedProps;
26397 workInProgress.memoizedState = current.memoizedState;
26398 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26399 // it cannot be shared with the current fiber.
26400
26401 var currentDependencies = current.dependencies;
26402 workInProgress.dependencies = currentDependencies === null ? null : {
26403 expirationTime: currentDependencies.expirationTime,
26404 firstContext: currentDependencies.firstContext,
26405 responders: currentDependencies.responders
26406 }; // These will be overridden during the parent's reconciliation
26407
26408 workInProgress.sibling = current.sibling;
26409 workInProgress.index = current.index;
26410 workInProgress.ref = current.ref;
26411
26412 if (enableProfilerTimer) {
26413 workInProgress.selfBaseDuration = current.selfBaseDuration;
26414 workInProgress.treeBaseDuration = current.treeBaseDuration;
26415 }
26416
26417 {
26418 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
26419
26420 switch (workInProgress.tag) {
26421 case IndeterminateComponent:
26422 case FunctionComponent:
26423 case SimpleMemoComponent:
26424 workInProgress.type = resolveFunctionForHotReloading(current.type);
26425 break;
26426
26427 case ClassComponent:
26428 workInProgress.type = resolveClassForHotReloading(current.type);
26429 break;
26430
26431 case ForwardRef:
26432 workInProgress.type = resolveForwardRefForHotReloading(current.type);
26433 break;
26434
26435 default:
26436 break;
26437 }
26438 }
26439
26440 return workInProgress;
26441} // Used to reuse a Fiber for a second pass.
26442
26443function resetWorkInProgress(workInProgress, renderExpirationTime) {
26444 // This resets the Fiber to what createFiber or createWorkInProgress would
26445 // have set the values to before during the first pass. Ideally this wouldn't
26446 // be necessary but unfortunately many code paths reads from the workInProgress
26447 // when they should be reading from current and writing to workInProgress.
26448 // We assume pendingProps, index, key, ref, return are still untouched to
26449 // avoid doing another reconciliation.
26450 // Reset the effect tag but keep any Placement tags, since that's something
26451 // that child fiber is setting, not the reconciliation.
26452 workInProgress.effectTag &= Placement; // The effect list is no longer valid.
26453
26454 workInProgress.nextEffect = null;
26455 workInProgress.firstEffect = null;
26456 workInProgress.lastEffect = null;
26457 var current = workInProgress.alternate;
26458
26459 if (current === null) {
26460 // Reset to createFiber's initial values.
26461 workInProgress.childExpirationTime = NoWork;
26462 workInProgress.expirationTime = renderExpirationTime;
26463 workInProgress.child = null;
26464 workInProgress.memoizedProps = null;
26465 workInProgress.memoizedState = null;
26466 workInProgress.updateQueue = null;
26467 workInProgress.dependencies = null;
26468
26469 if (enableProfilerTimer) {
26470 // Note: We don't reset the actualTime counts. It's useful to accumulate
26471 // actual time across multiple render passes.
26472 workInProgress.selfBaseDuration = 0;
26473 workInProgress.treeBaseDuration = 0;
26474 }
26475 } else {
26476 // Reset to the cloned values that createWorkInProgress would've.
26477 workInProgress.childExpirationTime = current.childExpirationTime;
26478 workInProgress.expirationTime = current.expirationTime;
26479 workInProgress.child = current.child;
26480 workInProgress.memoizedProps = current.memoizedProps;
26481 workInProgress.memoizedState = current.memoizedState;
26482 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26483 // it cannot be shared with the current fiber.
26484
26485 var currentDependencies = current.dependencies;
26486 workInProgress.dependencies = currentDependencies === null ? null : {
26487 expirationTime: currentDependencies.expirationTime,
26488 firstContext: currentDependencies.firstContext,
26489 responders: currentDependencies.responders
26490 };
26491
26492 if (enableProfilerTimer) {
26493 // Note: We don't reset the actualTime counts. It's useful to accumulate
26494 // actual time across multiple render passes.
26495 workInProgress.selfBaseDuration = current.selfBaseDuration;
26496 workInProgress.treeBaseDuration = current.treeBaseDuration;
26497 }
26498 }
26499
26500 return workInProgress;
26501}
26502function createHostRootFiber(tag) {
26503 var mode;
26504
26505 if (tag === ConcurrentRoot) {
26506 mode = ConcurrentMode | BlockingMode | StrictMode;
26507 } else if (tag === BlockingRoot) {
26508 mode = BlockingMode | StrictMode;
26509 } else {
26510 mode = NoMode;
26511 }
26512
26513 if (enableProfilerTimer && isDevToolsPresent) {
26514 // Always collect profile timings when DevTools are present.
26515 // This enables DevTools to start capturing timing at any point–
26516 // Without some nodes in the tree having empty base times.
26517 mode |= ProfileMode;
26518 }
26519
26520 return createFiber(HostRoot, null, null, mode);
26521}
26522function createFiberFromTypeAndProps(type, // React$ElementType
26523key, pendingProps, owner, mode, expirationTime) {
26524 var fiber;
26525 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
26526
26527 var resolvedType = type;
26528
26529 if (typeof type === 'function') {
26530 if (shouldConstruct(type)) {
26531 fiberTag = ClassComponent;
26532
26533 {
26534 resolvedType = resolveClassForHotReloading(resolvedType);
26535 }
26536 } else {
26537 {
26538 resolvedType = resolveFunctionForHotReloading(resolvedType);
26539 }
26540 }
26541 } else if (typeof type === 'string') {
26542 fiberTag = HostComponent;
26543 } else {
26544 getTag: switch (type) {
26545 case REACT_FRAGMENT_TYPE:
26546 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
26547
26548 case REACT_CONCURRENT_MODE_TYPE:
26549 fiberTag = Mode;
26550 mode |= ConcurrentMode | BlockingMode | StrictMode;
26551 break;
26552
26553 case REACT_STRICT_MODE_TYPE:
26554 fiberTag = Mode;
26555 mode |= StrictMode;
26556 break;
26557
26558 case REACT_PROFILER_TYPE:
26559 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
26560
26561 case REACT_SUSPENSE_TYPE:
26562 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
26563
26564 case REACT_SUSPENSE_LIST_TYPE:
26565 return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
26566
26567 default:
26568 {
26569 if (typeof type === 'object' && type !== null) {
26570 switch (type.$$typeof) {
26571 case REACT_PROVIDER_TYPE:
26572 fiberTag = ContextProvider;
26573 break getTag;
26574
26575 case REACT_CONTEXT_TYPE:
26576 // This is a consumer
26577 fiberTag = ContextConsumer;
26578 break getTag;
26579
26580 case REACT_FORWARD_REF_TYPE:
26581 fiberTag = ForwardRef;
26582
26583 {
26584 resolvedType = resolveForwardRefForHotReloading(resolvedType);
26585 }
26586
26587 break getTag;
26588
26589 case REACT_MEMO_TYPE:
26590 fiberTag = MemoComponent;
26591 break getTag;
26592
26593 case REACT_LAZY_TYPE:
26594 fiberTag = LazyComponent;
26595 resolvedType = null;
26596 break getTag;
26597
26598 case REACT_FUNDAMENTAL_TYPE:
26599 if (enableFundamentalAPI) {
26600 return createFiberFromFundamental(type, pendingProps, mode, expirationTime, key);
26601 }
26602
26603 break;
26604
26605 case REACT_SCOPE_TYPE:
26606 if (enableScopeAPI) {
26607 return createFiberFromScope(type, pendingProps, mode, expirationTime, key);
26608 }
26609
26610 }
26611 }
26612
26613 var info = '';
26614
26615 {
26616 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
26617 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.';
26618 }
26619
26620 var ownerName = owner ? getComponentName(owner.type) : null;
26621
26622 if (ownerName) {
26623 info += '\n\nCheck the render method of `' + ownerName + '`.';
26624 }
26625 }
26626
26627 {
26628 {
26629 throw 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);
26630 }
26631 }
26632 }
26633 }
26634 }
26635
26636 fiber = createFiber(fiberTag, pendingProps, key, mode);
26637 fiber.elementType = type;
26638 fiber.type = resolvedType;
26639 fiber.expirationTime = expirationTime;
26640 return fiber;
26641}
26642function createFiberFromElement(element, mode, expirationTime) {
26643 var owner = null;
26644
26645 {
26646 owner = element._owner;
26647 }
26648
26649 var type = element.type;
26650 var key = element.key;
26651 var pendingProps = element.props;
26652 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
26653
26654 {
26655 fiber._debugSource = element._source;
26656 fiber._debugOwner = element._owner;
26657 }
26658
26659 return fiber;
26660}
26661function createFiberFromFragment(elements, mode, expirationTime, key) {
26662 var fiber = createFiber(Fragment, elements, key, mode);
26663 fiber.expirationTime = expirationTime;
26664 return fiber;
26665}
26666function createFiberFromFundamental(fundamentalComponent, pendingProps, mode, expirationTime, key) {
26667 var fiber = createFiber(FundamentalComponent, pendingProps, key, mode);
26668 fiber.elementType = fundamentalComponent;
26669 fiber.type = fundamentalComponent;
26670 fiber.expirationTime = expirationTime;
26671 return fiber;
26672}
26673
26674function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) {
26675 var fiber = createFiber(ScopeComponent, pendingProps, key, mode);
26676 fiber.type = scope;
26677 fiber.elementType = scope;
26678 fiber.expirationTime = expirationTime;
26679 return fiber;
26680}
26681
26682function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
26683 {
26684 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
26685 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
26686 }
26687 }
26688
26689 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
26690
26691 fiber.elementType = REACT_PROFILER_TYPE;
26692 fiber.type = REACT_PROFILER_TYPE;
26693 fiber.expirationTime = expirationTime;
26694 return fiber;
26695}
26696
26697function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
26698 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
26699 // This needs to be fixed in getComponentName so that it relies on the tag
26700 // instead.
26701
26702 fiber.type = REACT_SUSPENSE_TYPE;
26703 fiber.elementType = REACT_SUSPENSE_TYPE;
26704 fiber.expirationTime = expirationTime;
26705 return fiber;
26706}
26707function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
26708 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
26709
26710 {
26711 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
26712 // This needs to be fixed in getComponentName so that it relies on the tag
26713 // instead.
26714 fiber.type = REACT_SUSPENSE_LIST_TYPE;
26715 }
26716
26717 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
26718 fiber.expirationTime = expirationTime;
26719 return fiber;
26720}
26721function createFiberFromText(content, mode, expirationTime) {
26722 var fiber = createFiber(HostText, content, null, mode);
26723 fiber.expirationTime = expirationTime;
26724 return fiber;
26725}
26726function createFiberFromHostInstanceForDeletion() {
26727 var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
26728
26729 fiber.elementType = 'DELETED';
26730 fiber.type = 'DELETED';
26731 return fiber;
26732}
26733function createFiberFromDehydratedFragment(dehydratedNode) {
26734 var fiber = createFiber(DehydratedFragment, null, null, NoMode);
26735 fiber.stateNode = dehydratedNode;
26736 return fiber;
26737}
26738function createFiberFromPortal(portal, mode, expirationTime) {
26739 var pendingProps = portal.children !== null ? portal.children : [];
26740 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
26741 fiber.expirationTime = expirationTime;
26742 fiber.stateNode = {
26743 containerInfo: portal.containerInfo,
26744 pendingChildren: null,
26745 // Used by persistent updates
26746 implementation: portal.implementation
26747 };
26748 return fiber;
26749} // Used for stashing WIP properties to replay failed work in DEV.
26750
26751function assignFiberPropertiesInDEV(target, source) {
26752 if (target === null) {
26753 // This Fiber's initial properties will always be overwritten.
26754 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
26755 target = createFiber(IndeterminateComponent, null, null, NoMode);
26756 } // This is intentionally written as a list of all properties.
26757 // We tried to use Object.assign() instead but this is called in
26758 // the hottest path, and Object.assign() was too slow:
26759 // https://github.com/facebook/react/issues/12502
26760 // This code is DEV-only so size is not a concern.
26761
26762
26763 target.tag = source.tag;
26764 target.key = source.key;
26765 target.elementType = source.elementType;
26766 target.type = source.type;
26767 target.stateNode = source.stateNode;
26768 target.return = source.return;
26769 target.child = source.child;
26770 target.sibling = source.sibling;
26771 target.index = source.index;
26772 target.ref = source.ref;
26773 target.pendingProps = source.pendingProps;
26774 target.memoizedProps = source.memoizedProps;
26775 target.updateQueue = source.updateQueue;
26776 target.memoizedState = source.memoizedState;
26777 target.dependencies = source.dependencies;
26778 target.mode = source.mode;
26779 target.effectTag = source.effectTag;
26780 target.nextEffect = source.nextEffect;
26781 target.firstEffect = source.firstEffect;
26782 target.lastEffect = source.lastEffect;
26783 target.expirationTime = source.expirationTime;
26784 target.childExpirationTime = source.childExpirationTime;
26785 target.alternate = source.alternate;
26786
26787 if (enableProfilerTimer) {
26788 target.actualDuration = source.actualDuration;
26789 target.actualStartTime = source.actualStartTime;
26790 target.selfBaseDuration = source.selfBaseDuration;
26791 target.treeBaseDuration = source.treeBaseDuration;
26792 }
26793
26794 target._debugID = source._debugID;
26795 target._debugSource = source._debugSource;
26796 target._debugOwner = source._debugOwner;
26797 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
26798 target._debugNeedsRemount = source._debugNeedsRemount;
26799 target._debugHookTypes = source._debugHookTypes;
26800 return target;
26801}
26802
26803function FiberRootNode(containerInfo, tag, hydrate) {
26804 this.tag = tag;
26805 this.current = null;
26806 this.containerInfo = containerInfo;
26807 this.pendingChildren = null;
26808 this.pingCache = null;
26809 this.finishedExpirationTime = NoWork;
26810 this.finishedWork = null;
26811 this.timeoutHandle = noTimeout;
26812 this.context = null;
26813 this.pendingContext = null;
26814 this.hydrate = hydrate;
26815 this.callbackNode = null;
26816 this.callbackPriority = NoPriority;
26817 this.firstPendingTime = NoWork;
26818 this.firstSuspendedTime = NoWork;
26819 this.lastSuspendedTime = NoWork;
26820 this.nextKnownPendingLevel = NoWork;
26821 this.lastPingedTime = NoWork;
26822 this.lastExpiredTime = NoWork;
26823
26824 if (enableSchedulerTracing) {
26825 this.interactionThreadID = tracing.unstable_getThreadID();
26826 this.memoizedInteractions = new Set();
26827 this.pendingInteractionMap = new Map();
26828 }
26829
26830 if (enableSuspenseCallback) {
26831 this.hydrationCallbacks = null;
26832 }
26833}
26834
26835function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
26836 var root = new FiberRootNode(containerInfo, tag, hydrate);
26837
26838 if (enableSuspenseCallback) {
26839 root.hydrationCallbacks = hydrationCallbacks;
26840 } // Cyclic construction. This cheats the type system right now because
26841 // stateNode is any.
26842
26843
26844 var uninitializedFiber = createHostRootFiber(tag);
26845 root.current = uninitializedFiber;
26846 uninitializedFiber.stateNode = root;
26847 return root;
26848}
26849function isRootSuspendedAtTime(root, expirationTime) {
26850 var firstSuspendedTime = root.firstSuspendedTime;
26851 var lastSuspendedTime = root.lastSuspendedTime;
26852 return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
26853}
26854function markRootSuspendedAtTime(root, expirationTime) {
26855 var firstSuspendedTime = root.firstSuspendedTime;
26856 var lastSuspendedTime = root.lastSuspendedTime;
26857
26858 if (firstSuspendedTime < expirationTime) {
26859 root.firstSuspendedTime = expirationTime;
26860 }
26861
26862 if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
26863 root.lastSuspendedTime = expirationTime;
26864 }
26865
26866 if (expirationTime <= root.lastPingedTime) {
26867 root.lastPingedTime = NoWork;
26868 }
26869
26870 if (expirationTime <= root.lastExpiredTime) {
26871 root.lastExpiredTime = NoWork;
26872 }
26873}
26874function markRootUpdatedAtTime(root, expirationTime) {
26875 // Update the range of pending times
26876 var firstPendingTime = root.firstPendingTime;
26877
26878 if (expirationTime > firstPendingTime) {
26879 root.firstPendingTime = expirationTime;
26880 } // Update the range of suspended times. Treat everything lower priority or
26881 // equal to this update as unsuspended.
26882
26883
26884 var firstSuspendedTime = root.firstSuspendedTime;
26885
26886 if (firstSuspendedTime !== NoWork) {
26887 if (expirationTime >= firstSuspendedTime) {
26888 // The entire suspended range is now unsuspended.
26889 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26890 } else if (expirationTime >= root.lastSuspendedTime) {
26891 root.lastSuspendedTime = expirationTime + 1;
26892 } // This is a pending level. Check if it's higher priority than the next
26893 // known pending level.
26894
26895
26896 if (expirationTime > root.nextKnownPendingLevel) {
26897 root.nextKnownPendingLevel = expirationTime;
26898 }
26899 }
26900}
26901function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
26902 // Update the range of pending times
26903 root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
26904 // equal to this update as unsuspended.
26905
26906 if (finishedExpirationTime <= root.lastSuspendedTime) {
26907 // The entire suspended range is now unsuspended.
26908 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26909 } else if (finishedExpirationTime <= root.firstSuspendedTime) {
26910 // Part of the suspended range is now unsuspended. Narrow the range to
26911 // include everything between the unsuspended time (non-inclusive) and the
26912 // last suspended time.
26913 root.firstSuspendedTime = finishedExpirationTime - 1;
26914 }
26915
26916 if (finishedExpirationTime <= root.lastPingedTime) {
26917 // Clear the pinged time
26918 root.lastPingedTime = NoWork;
26919 }
26920
26921 if (finishedExpirationTime <= root.lastExpiredTime) {
26922 // Clear the expired time
26923 root.lastExpiredTime = NoWork;
26924 }
26925}
26926function markRootExpiredAtTime(root, expirationTime) {
26927 var lastExpiredTime = root.lastExpiredTime;
26928
26929 if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
26930 root.lastExpiredTime = expirationTime;
26931 }
26932}
26933
26934// This lets us hook into Fiber to debug what it's doing.
26935// See https://github.com/facebook/react/pull/8033.
26936// This is not part of the public API, not even for React DevTools.
26937// You may only inject a debugTool if you work on React Fiber itself.
26938var ReactFiberInstrumentation = {
26939 debugTool: null
26940};
26941var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
26942
26943var didWarnAboutNestedUpdates;
26944var didWarnAboutFindNodeInStrictMode;
26945
26946{
26947 didWarnAboutNestedUpdates = false;
26948 didWarnAboutFindNodeInStrictMode = {};
26949}
26950
26951function getContextForSubtree(parentComponent) {
26952 if (!parentComponent) {
26953 return emptyContextObject;
26954 }
26955
26956 var fiber = get(parentComponent);
26957 var parentContext = findCurrentUnmaskedContext(fiber);
26958
26959 if (fiber.tag === ClassComponent) {
26960 var Component = fiber.type;
26961
26962 if (isContextProvider(Component)) {
26963 return processChildContext(fiber, Component, parentContext);
26964 }
26965 }
26966
26967 return parentContext;
26968}
26969
26970function findHostInstance(component) {
26971 var fiber = get(component);
26972
26973 if (fiber === undefined) {
26974 if (typeof component.render === 'function') {
26975 {
26976 {
26977 throw Error("Unable to find node on an unmounted component.");
26978 }
26979 }
26980 } else {
26981 {
26982 {
26983 throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
26984 }
26985 }
26986 }
26987 }
26988
26989 var hostFiber = findCurrentHostFiber(fiber);
26990
26991 if (hostFiber === null) {
26992 return null;
26993 }
26994
26995 return hostFiber.stateNode;
26996}
26997
26998function findHostInstanceWithWarning(component, methodName) {
26999 {
27000 var fiber = get(component);
27001
27002 if (fiber === undefined) {
27003 if (typeof component.render === 'function') {
27004 {
27005 {
27006 throw Error("Unable to find node on an unmounted component.");
27007 }
27008 }
27009 } else {
27010 {
27011 {
27012 throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
27013 }
27014 }
27015 }
27016 }
27017
27018 var hostFiber = findCurrentHostFiber(fiber);
27019
27020 if (hostFiber === null) {
27021 return null;
27022 }
27023
27024 if (hostFiber.mode & StrictMode) {
27025 var componentName = getComponentName(fiber.type) || 'Component';
27026
27027 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
27028 didWarnAboutFindNodeInStrictMode[componentName] = true;
27029
27030 if (fiber.mode & StrictMode) {
27031 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));
27032 } else {
27033 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));
27034 }
27035 }
27036 }
27037
27038 return hostFiber.stateNode;
27039 }
27040
27041 return findHostInstance(component);
27042}
27043
27044function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
27045 return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
27046}
27047function updateContainer(element, container, parentComponent, callback) {
27048 var current$$1 = container.current;
27049 var currentTime = requestCurrentTimeForUpdate();
27050
27051 {
27052 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
27053 if ('undefined' !== typeof jest) {
27054 warnIfUnmockedScheduler(current$$1);
27055 warnIfNotScopedWithMatchingAct(current$$1);
27056 }
27057 }
27058
27059 var suspenseConfig = requestCurrentSuspenseConfig();
27060 var expirationTime = computeExpirationForFiber(currentTime, current$$1, suspenseConfig);
27061
27062 {
27063 if (ReactFiberInstrumentation_1.debugTool) {
27064 if (current$$1.alternate === null) {
27065 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
27066 } else if (element === null) {
27067 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
27068 } else {
27069 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
27070 }
27071 }
27072 }
27073
27074 var context = getContextForSubtree(parentComponent);
27075
27076 if (container.context === null) {
27077 container.context = context;
27078 } else {
27079 container.pendingContext = context;
27080 }
27081
27082 {
27083 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
27084 didWarnAboutNestedUpdates = true;
27085 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');
27086 }
27087 }
27088
27089 var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
27090 // being called "element".
27091
27092 update.payload = {
27093 element: element
27094 };
27095 callback = callback === undefined ? null : callback;
27096
27097 if (callback !== null) {
27098 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
27099 update.callback = callback;
27100 }
27101
27102 enqueueUpdate(current$$1, update);
27103 scheduleWork(current$$1, expirationTime);
27104 return expirationTime;
27105}
27106function getPublicRootInstance(container) {
27107 var containerFiber = container.current;
27108
27109 if (!containerFiber.child) {
27110 return null;
27111 }
27112
27113 switch (containerFiber.child.tag) {
27114 case HostComponent:
27115 return getPublicInstance(containerFiber.child.stateNode);
27116
27117 default:
27118 return containerFiber.child.stateNode;
27119 }
27120}
27121function attemptSynchronousHydration$1(fiber) {
27122 switch (fiber.tag) {
27123 case HostRoot:
27124 var root = fiber.stateNode;
27125
27126 if (root.hydrate) {
27127 // Flush the first scheduled "update".
27128 flushRoot(root, root.firstPendingTime);
27129 }
27130
27131 break;
27132
27133 case SuspenseComponent:
27134 flushSync(function () {
27135 return scheduleWork(fiber, Sync);
27136 }); // If we're still blocked after this, we need to increase
27137 // the priority of any promises resolving within this
27138 // boundary so that they next attempt also has higher pri.
27139
27140 var retryExpTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
27141 markRetryTimeIfNotHydrated(fiber, retryExpTime);
27142 break;
27143 }
27144}
27145
27146function markRetryTimeImpl(fiber, retryTime) {
27147 var suspenseState = fiber.memoizedState;
27148
27149 if (suspenseState !== null && suspenseState.dehydrated !== null) {
27150 if (suspenseState.retryTime < retryTime) {
27151 suspenseState.retryTime = retryTime;
27152 }
27153 }
27154} // Increases the priority of thennables when they resolve within this boundary.
27155
27156
27157function markRetryTimeIfNotHydrated(fiber, retryTime) {
27158 markRetryTimeImpl(fiber, retryTime);
27159 var alternate = fiber.alternate;
27160
27161 if (alternate) {
27162 markRetryTimeImpl(alternate, retryTime);
27163 }
27164}
27165
27166function attemptUserBlockingHydration$1(fiber) {
27167 if (fiber.tag !== SuspenseComponent) {
27168 // We ignore HostRoots here because we can't increase
27169 // their priority and they should not suspend on I/O,
27170 // since you have to wrap anything that might suspend in
27171 // Suspense.
27172 return;
27173 }
27174
27175 var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
27176 scheduleWork(fiber, expTime);
27177 markRetryTimeIfNotHydrated(fiber, expTime);
27178}
27179function attemptContinuousHydration$1(fiber) {
27180 if (fiber.tag !== SuspenseComponent) {
27181 // We ignore HostRoots here because we can't increase
27182 // their priority and they should not suspend on I/O,
27183 // since you have to wrap anything that might suspend in
27184 // Suspense.
27185 return;
27186 }
27187
27188 var expTime = computeContinuousHydrationExpiration(requestCurrentTimeForUpdate());
27189 scheduleWork(fiber, expTime);
27190 markRetryTimeIfNotHydrated(fiber, expTime);
27191}
27192function attemptHydrationAtCurrentPriority$1(fiber) {
27193 if (fiber.tag !== SuspenseComponent) {
27194 // We ignore HostRoots here because we can't increase
27195 // their priority other than synchronously flush it.
27196 return;
27197 }
27198
27199 var currentTime = requestCurrentTimeForUpdate();
27200 var expTime = computeExpirationForFiber(currentTime, fiber, null);
27201 scheduleWork(fiber, expTime);
27202 markRetryTimeIfNotHydrated(fiber, expTime);
27203}
27204function findHostInstanceWithNoPortals(fiber) {
27205 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
27206
27207 if (hostFiber === null) {
27208 return null;
27209 }
27210
27211 if (hostFiber.tag === FundamentalComponent) {
27212 return hostFiber.stateNode.instance;
27213 }
27214
27215 return hostFiber.stateNode;
27216}
27217
27218var shouldSuspendImpl = function (fiber) {
27219 return false;
27220};
27221
27222function shouldSuspend(fiber) {
27223 return shouldSuspendImpl(fiber);
27224}
27225var overrideHookState = null;
27226var overrideProps = null;
27227var scheduleUpdate = null;
27228var setSuspenseHandler = null;
27229
27230{
27231 var copyWithSetImpl = function (obj, path, idx, value) {
27232 if (idx >= path.length) {
27233 return value;
27234 }
27235
27236 var key = path[idx];
27237 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
27238
27239 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
27240 return updated;
27241 };
27242
27243 var copyWithSet = function (obj, path, value) {
27244 return copyWithSetImpl(obj, path, 0, value);
27245 }; // Support DevTools editable values for useState and useReducer.
27246
27247
27248 overrideHookState = function (fiber, id, path, value) {
27249 // For now, the "id" of stateful hooks is just the stateful hook index.
27250 // This may change in the future with e.g. nested hooks.
27251 var currentHook = fiber.memoizedState;
27252
27253 while (currentHook !== null && id > 0) {
27254 currentHook = currentHook.next;
27255 id--;
27256 }
27257
27258 if (currentHook !== null) {
27259 var newState = copyWithSet(currentHook.memoizedState, path, value);
27260 currentHook.memoizedState = newState;
27261 currentHook.baseState = newState; // We aren't actually adding an update to the queue,
27262 // because there is no update we can add for useReducer hooks that won't trigger an error.
27263 // (There's no appropriate action type for DevTools overrides.)
27264 // As a result though, React will see the scheduled update as a noop and bailout.
27265 // Shallow cloning props works as a workaround for now to bypass the bailout check.
27266
27267 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
27268 scheduleWork(fiber, Sync);
27269 }
27270 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
27271
27272
27273 overrideProps = function (fiber, path, value) {
27274 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
27275
27276 if (fiber.alternate) {
27277 fiber.alternate.pendingProps = fiber.pendingProps;
27278 }
27279
27280 scheduleWork(fiber, Sync);
27281 };
27282
27283 scheduleUpdate = function (fiber) {
27284 scheduleWork(fiber, Sync);
27285 };
27286
27287 setSuspenseHandler = function (newShouldSuspendImpl) {
27288 shouldSuspendImpl = newShouldSuspendImpl;
27289 };
27290}
27291
27292function injectIntoDevTools(devToolsConfig) {
27293 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
27294 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
27295 return injectInternals(_assign({}, devToolsConfig, {
27296 overrideHookState: overrideHookState,
27297 overrideProps: overrideProps,
27298 setSuspenseHandler: setSuspenseHandler,
27299 scheduleUpdate: scheduleUpdate,
27300 currentDispatcherRef: ReactCurrentDispatcher,
27301 findHostInstanceByFiber: function (fiber) {
27302 var hostFiber = findCurrentHostFiber(fiber);
27303
27304 if (hostFiber === null) {
27305 return null;
27306 }
27307
27308 return hostFiber.stateNode;
27309 },
27310 findFiberByHostInstance: function (instance) {
27311 if (!findFiberByHostInstance) {
27312 // Might not be implemented by the renderer.
27313 return null;
27314 }
27315
27316 return findFiberByHostInstance(instance);
27317 },
27318 // React Refresh
27319 findHostInstancesForRefresh: findHostInstancesForRefresh,
27320 scheduleRefresh: scheduleRefresh,
27321 scheduleRoot: scheduleRoot,
27322 setRefreshHandler: setRefreshHandler,
27323 // Enables DevTools to append owner stacks to error messages in DEV mode.
27324 getCurrentFiber: function () {
27325 return current;
27326 }
27327 }));
27328}
27329
27330// This file intentionally does *not* have the Flow annotation.
27331// Don't add it. See `./inline-typed.js` for an explanation.
27332
27333// TODO: This type is shared between the reconciler and ReactDOM, but will
27334// eventually be lifted out to the renderer.
27335function ReactDOMRoot(container, options) {
27336 this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
27337}
27338
27339function ReactDOMBlockingRoot(container, tag, options) {
27340 this._internalRoot = createRootImpl(container, tag, options);
27341}
27342
27343ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function (children, callback) {
27344 var root = this._internalRoot;
27345 var cb = callback === undefined ? null : callback;
27346
27347 {
27348 warnOnInvalidCallback(cb, 'render');
27349 }
27350
27351 updateContainer(children, root, null, cb);
27352};
27353
27354ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function (callback) {
27355 var root = this._internalRoot;
27356 var cb = callback === undefined ? null : callback;
27357
27358 {
27359 warnOnInvalidCallback(cb, 'render');
27360 }
27361
27362 var container = root.containerInfo;
27363 updateContainer(null, root, null, function () {
27364 unmarkContainerAsRoot(container);
27365
27366 if (cb !== null) {
27367 cb();
27368 }
27369 });
27370};
27371
27372function createRootImpl(container, tag, options) {
27373 // Tag is either LegacyRoot or Concurrent Root
27374 var hydrate = options != null && options.hydrate === true;
27375 var hydrationCallbacks = options != null && options.hydrationOptions || null;
27376 var root = createContainer(container, tag, hydrate, hydrationCallbacks);
27377 markContainerAsRoot(root.current, container);
27378
27379 if (hydrate && tag !== LegacyRoot) {
27380 var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
27381 eagerlyTrapReplayableEvents(doc);
27382 }
27383
27384 return root;
27385}
27386
27387function createRoot(container, options) {
27388 if (!isValidContainer(container)) {
27389 {
27390 throw Error("createRoot(...): Target container is not a DOM element.");
27391 }
27392 }
27393
27394 warnIfReactDOMContainerInDEV(container);
27395 return new ReactDOMRoot(container, options);
27396}
27397function createBlockingRoot(container, options) {
27398 if (!isValidContainer(container)) {
27399 {
27400 throw Error("createRoot(...): Target container is not a DOM element.");
27401 }
27402 }
27403
27404 warnIfReactDOMContainerInDEV(container);
27405 return new ReactDOMBlockingRoot(container, BlockingRoot, options);
27406}
27407function createLegacyRoot(container, options) {
27408 return new ReactDOMBlockingRoot(container, LegacyRoot, options);
27409}
27410function isValidContainer(node) {
27411 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 '));
27412}
27413function warnOnInvalidCallback(callback, callerName) {
27414 {
27415 !(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;
27416 }
27417}
27418
27419function warnIfReactDOMContainerInDEV(container) {
27420 {
27421 if (isContainerMarkedAsRoot(container)) {
27422 if (container._reactRootContainer) {
27423 warningWithoutStack$1(false, 'You are calling ReactDOM.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.');
27424 } else {
27425 warningWithoutStack$1(false, 'You are calling ReactDOM.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.');
27426 }
27427 }
27428 }
27429}
27430
27431var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
27432var topLevelUpdateWarnings;
27433var warnedAboutHydrateAPI = false;
27434
27435{
27436 topLevelUpdateWarnings = function (container) {
27437 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
27438 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
27439
27440 if (hostInstance) {
27441 !(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;
27442 }
27443 }
27444
27445 var isRootRenderedBySomeReact = !!container._reactRootContainer;
27446 var rootEl = getReactRootElementInContainer(container);
27447 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
27448 !(!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;
27449 !(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;
27450 };
27451}
27452
27453function getReactRootElementInContainer(container) {
27454 if (!container) {
27455 return null;
27456 }
27457
27458 if (container.nodeType === DOCUMENT_NODE) {
27459 return container.documentElement;
27460 } else {
27461 return container.firstChild;
27462 }
27463}
27464
27465function shouldHydrateDueToLegacyHeuristic(container) {
27466 var rootElement = getReactRootElementInContainer(container);
27467 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
27468}
27469
27470function legacyCreateRootFromDOMContainer(container, forceHydrate) {
27471 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
27472
27473 if (!shouldHydrate) {
27474 var warned = false;
27475 var rootSibling;
27476
27477 while (rootSibling = container.lastChild) {
27478 {
27479 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
27480 warned = true;
27481 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.');
27482 }
27483 }
27484
27485 container.removeChild(rootSibling);
27486 }
27487 }
27488
27489 {
27490 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
27491 warnedAboutHydrateAPI = true;
27492 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.');
27493 }
27494 }
27495
27496 return createLegacyRoot(container, shouldHydrate ? {
27497 hydrate: true
27498 } : undefined);
27499}
27500
27501function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
27502 {
27503 topLevelUpdateWarnings(container);
27504 warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
27505 } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
27506 // member of intersection type." Whyyyyyy.
27507
27508
27509 var root = container._reactRootContainer;
27510 var fiberRoot;
27511
27512 if (!root) {
27513 // Initial mount
27514 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
27515 fiberRoot = root._internalRoot;
27516
27517 if (typeof callback === 'function') {
27518 var originalCallback = callback;
27519
27520 callback = function () {
27521 var instance = getPublicRootInstance(fiberRoot);
27522 originalCallback.call(instance);
27523 };
27524 } // Initial mount should not be batched.
27525
27526
27527 unbatchedUpdates(function () {
27528 updateContainer(children, fiberRoot, parentComponent, callback);
27529 });
27530 } else {
27531 fiberRoot = root._internalRoot;
27532
27533 if (typeof callback === 'function') {
27534 var _originalCallback = callback;
27535
27536 callback = function () {
27537 var instance = getPublicRootInstance(fiberRoot);
27538
27539 _originalCallback.call(instance);
27540 };
27541 } // Update
27542
27543
27544 updateContainer(children, fiberRoot, parentComponent, callback);
27545 }
27546
27547 return getPublicRootInstance(fiberRoot);
27548}
27549
27550function findDOMNode(componentOrElement) {
27551 {
27552 var owner = ReactCurrentOwner$1.current;
27553
27554 if (owner !== null && owner.stateNode !== null) {
27555 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
27556 !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;
27557 owner.stateNode._warnedAboutRefsInRender = true;
27558 }
27559 }
27560
27561 if (componentOrElement == null) {
27562 return null;
27563 }
27564
27565 if (componentOrElement.nodeType === ELEMENT_NODE) {
27566 return componentOrElement;
27567 }
27568
27569 {
27570 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
27571 }
27572
27573 return findHostInstance(componentOrElement);
27574}
27575function hydrate(element, container, callback) {
27576 if (!isValidContainer(container)) {
27577 {
27578 throw Error("Target container is not a DOM element.");
27579 }
27580 }
27581
27582 {
27583 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
27584
27585 if (isModernRoot) {
27586 warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');
27587 }
27588 } // TODO: throw or warn if we couldn't hydrate?
27589
27590
27591 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
27592}
27593function render(element, container, callback) {
27594 if (!isValidContainer(container)) {
27595 {
27596 throw Error("Target container is not a DOM element.");
27597 }
27598 }
27599
27600 {
27601 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
27602
27603 if (isModernRoot) {
27604 warningWithoutStack$1(false, 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
27605 }
27606 }
27607
27608 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
27609}
27610function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
27611 if (!isValidContainer(containerNode)) {
27612 {
27613 throw Error("Target container is not a DOM element.");
27614 }
27615 }
27616
27617 if (!(parentComponent != null && has(parentComponent))) {
27618 {
27619 throw Error("parentComponent must be a valid React Component");
27620 }
27621 }
27622
27623 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
27624}
27625function unmountComponentAtNode(container) {
27626 if (!isValidContainer(container)) {
27627 {
27628 throw Error("unmountComponentAtNode(...): Target container is not a DOM element.");
27629 }
27630 }
27631
27632 {
27633 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
27634
27635 if (isModernRoot) {
27636 warningWithoutStack$1(false, 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');
27637 }
27638 }
27639
27640 if (container._reactRootContainer) {
27641 {
27642 var rootEl = getReactRootElementInContainer(container);
27643 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
27644 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
27645 } // Unmount should not be batched.
27646
27647
27648 unbatchedUpdates(function () {
27649 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
27650 container._reactRootContainer = null;
27651 unmarkContainerAsRoot(container);
27652 });
27653 }); // If you call unmountComponentAtNode twice in quick succession, you'll
27654 // get `true` twice. That's probably fine?
27655
27656 return true;
27657 } else {
27658 {
27659 var _rootEl = getReactRootElementInContainer(container);
27660
27661 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
27662
27663 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
27664 !!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;
27665 }
27666
27667 return false;
27668 }
27669}
27670
27671function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
27672implementation) {
27673 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
27674 return {
27675 // This tag allow us to uniquely identify this as a React Portal
27676 $$typeof: REACT_PORTAL_TYPE,
27677 key: key == null ? null : '' + key,
27678 children: children,
27679 containerInfo: containerInfo,
27680 implementation: implementation
27681 };
27682}
27683
27684// TODO: this is special because it gets imported during build.
27685
27686var ReactVersion = '16.12.0';
27687
27688setAttemptSynchronousHydration(attemptSynchronousHydration$1);
27689setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);
27690setAttemptContinuousHydration(attemptContinuousHydration$1);
27691setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
27692var didWarnAboutUnstableCreatePortal = false;
27693
27694{
27695 if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
27696 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
27697 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
27698 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');
27699 }
27700}
27701
27702setRestoreImplementation(restoreControlledState$$1);
27703setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
27704
27705function createPortal$$1(children, container) {
27706 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
27707
27708 if (!isValidContainer(container)) {
27709 {
27710 throw Error("Target container is not a DOM element.");
27711 }
27712 } // TODO: pass ReactDOM portal implementation as third argument
27713
27714
27715 return createPortal$1(children, container, null, key);
27716}
27717
27718var ReactDOM = {
27719 createPortal: createPortal$$1,
27720 // Legacy
27721 findDOMNode: findDOMNode,
27722 hydrate: hydrate,
27723 render: render,
27724 unstable_renderSubtreeIntoContainer: unstable_renderSubtreeIntoContainer,
27725 unmountComponentAtNode: unmountComponentAtNode,
27726 // Temporary alias since we already shipped React 16 RC with it.
27727 // TODO: remove in React 17.
27728 unstable_createPortal: function () {
27729 if (!didWarnAboutUnstableCreatePortal) {
27730 didWarnAboutUnstableCreatePortal = true;
27731 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.');
27732 }
27733
27734 return createPortal$$1.apply(void 0, arguments);
27735 },
27736 unstable_batchedUpdates: batchedUpdates$1,
27737 flushSync: flushSync,
27738 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
27739 // Keep in sync with ReactDOMUnstableNativeDependencies.js
27740 // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
27741 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
27742 }
27743};
27744
27745if (exposeConcurrentModeAPIs) {
27746 ReactDOM.createRoot = createRoot;
27747 ReactDOM.createBlockingRoot = createBlockingRoot;
27748 ReactDOM.unstable_discreteUpdates = discreteUpdates$1;
27749 ReactDOM.unstable_flushDiscreteUpdates = flushDiscreteUpdates;
27750 ReactDOM.unstable_flushControlled = flushControlled;
27751
27752 ReactDOM.unstable_scheduleHydration = function (target) {
27753 if (target) {
27754 queueExplicitHydrationTarget(target);
27755 }
27756 };
27757}
27758
27759var foundDevTools = injectIntoDevTools({
27760 findFiberByHostInstance: getClosestInstanceFromNode,
27761 bundleType: 1,
27762 version: ReactVersion,
27763 rendererPackageName: 'react-dom'
27764});
27765
27766{
27767 if (!foundDevTools && canUseDOM && window.top === window.self) {
27768 // If we're in Chrome or Firefox, provide a download link if not installed.
27769 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
27770 var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
27771
27772 if (/^(https?|file):$/.test(protocol)) {
27773 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');
27774 }
27775 }
27776 }
27777}
27778
27779
27780
27781var ReactDOM$2 = Object.freeze({
27782 default: ReactDOM
27783});
27784
27785var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
27786
27787// TODO: decide on the top-level export form.
27788// This is hacky but makes it work with both Rollup and Jest.
27789
27790
27791var reactDom = ReactDOM$3.default || ReactDOM$3;
27792
27793module.exports = reactDom;
27794 })();
27795}