UNPKG

974 kBJavaScriptView Raw
1/** @license React v16.11.0
2 * react-dom.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactDOM = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18// Do not require this module directly! Use normal `invariant` calls with
19// template literal strings. The messages will be replaced with error codes
20// during build.
21
22/**
23 * Use invariant() to assert state which your program assumes to be true.
24 *
25 * Provide sprintf-style format (only %s is supported) and arguments
26 * to provide information about what broke and what you were
27 * expecting.
28 *
29 * The invariant message will be stripped in production, but the invariant
30 * will remain to ensure logic does not differ in production.
31 */
32
33if (!React) {
34 {
35 throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");
36 }
37}
38
39/**
40 * Injectable ordering of event plugins.
41 */
42var eventPluginOrder = null;
43/**
44 * Injectable mapping from names to event plugin modules.
45 */
46
47var namesToPlugins = {};
48/**
49 * Recomputes the plugin list using the injected plugins and plugin ordering.
50 *
51 * @private
52 */
53
54function recomputePluginOrdering() {
55 if (!eventPluginOrder) {
56 // Wait until an `eventPluginOrder` is injected.
57 return;
58 }
59
60 for (var pluginName in namesToPlugins) {
61 var pluginModule = namesToPlugins[pluginName];
62 var pluginIndex = eventPluginOrder.indexOf(pluginName);
63
64 if (!(pluginIndex > -1)) {
65 {
66 throw Error("EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`.");
67 }
68 }
69
70 if (plugins[pluginIndex]) {
71 continue;
72 }
73
74 if (!pluginModule.extractEvents) {
75 {
76 throw Error("EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not.");
77 }
78 }
79
80 plugins[pluginIndex] = pluginModule;
81 var publishedEvents = pluginModule.eventTypes;
82
83 for (var eventName in publishedEvents) {
84 if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
85 {
86 throw Error("EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`.");
87 }
88 }
89 }
90 }
91}
92/**
93 * Publishes an event so that it can be dispatched by the supplied plugin.
94 *
95 * @param {object} dispatchConfig Dispatch configuration for the event.
96 * @param {object} PluginModule Plugin publishing the event.
97 * @return {boolean} True if the event was successfully published.
98 * @private
99 */
100
101
102function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
103 if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
104 {
105 throw Error("EventPluginHub: More than one plugin attempted to publish the same event name, `" + eventName + "`.");
106 }
107 }
108
109 eventNameDispatchConfigs[eventName] = dispatchConfig;
110 var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
111
112 if (phasedRegistrationNames) {
113 for (var phaseName in phasedRegistrationNames) {
114 if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
115 var phasedRegistrationName = phasedRegistrationNames[phaseName];
116 publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
117 }
118 }
119
120 return true;
121 } else if (dispatchConfig.registrationName) {
122 publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
123 return true;
124 }
125
126 return false;
127}
128/**
129 * Publishes a registration name that is used to identify dispatched events.
130 *
131 * @param {string} registrationName Registration name to add.
132 * @param {object} PluginModule Plugin publishing the event.
133 * @private
134 */
135
136
137function publishRegistrationName(registrationName, pluginModule, eventName) {
138 if (!!registrationNameModules[registrationName]) {
139 {
140 throw Error("EventPluginHub: More than one plugin attempted to publish the same registration name, `" + registrationName + "`.");
141 }
142 }
143
144 registrationNameModules[registrationName] = pluginModule;
145 registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
146
147 {
148 var lowerCasedName = registrationName.toLowerCase();
149 possibleRegistrationNames[lowerCasedName] = registrationName;
150
151 if (registrationName === 'onDoubleClick') {
152 possibleRegistrationNames.ondblclick = registrationName;
153 }
154 }
155}
156/**
157 * Registers plugins so that they can extract and dispatch events.
158 *
159 * @see {EventPluginHub}
160 */
161
162/**
163 * Ordered list of injected plugins.
164 */
165
166
167var plugins = [];
168/**
169 * Mapping from event name to dispatch config
170 */
171
172var eventNameDispatchConfigs = {};
173/**
174 * Mapping from registration name to plugin module
175 */
176
177var registrationNameModules = {};
178/**
179 * Mapping from registration name to event name
180 */
181
182var registrationNameDependencies = {};
183/**
184 * Mapping from lowercase registration names to the properly cased version,
185 * used to warn in the case of missing event handlers. Available
186 * only in true.
187 * @type {Object}
188 */
189
190var possibleRegistrationNames = {}; // Trust the developer to only use possibleRegistrationNames in true
191
192/**
193 * Injects an ordering of plugins (by plugin name). This allows the ordering
194 * to be decoupled from injection of the actual plugins so that ordering is
195 * always deterministic regardless of packaging, on-the-fly injection, etc.
196 *
197 * @param {array} InjectedEventPluginOrder
198 * @internal
199 * @see {EventPluginHub.injection.injectEventPluginOrder}
200 */
201
202function injectEventPluginOrder(injectedEventPluginOrder) {
203 if (!!eventPluginOrder) {
204 {
205 throw Error("EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.");
206 }
207 } // Clone the ordering so it cannot be dynamically mutated.
208
209
210 eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
211 recomputePluginOrdering();
212}
213/**
214 * Injects plugins to be used by `EventPluginHub`. The plugin names must be
215 * in the ordering injected by `injectEventPluginOrder`.
216 *
217 * Plugins can be injected as part of page initialization or on-the-fly.
218 *
219 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
220 * @internal
221 * @see {EventPluginHub.injection.injectEventPluginsByName}
222 */
223
224function injectEventPluginsByName(injectedNamesToPlugins) {
225 var isOrderingDirty = false;
226
227 for (var pluginName in injectedNamesToPlugins) {
228 if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
229 continue;
230 }
231
232 var pluginModule = injectedNamesToPlugins[pluginName];
233
234 if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
235 if (!!namesToPlugins[pluginName]) {
236 {
237 throw Error("EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`.");
238 }
239 }
240
241 namesToPlugins[pluginName] = pluginModule;
242 isOrderingDirty = true;
243 }
244 }
245
246 if (isOrderingDirty) {
247 recomputePluginOrdering();
248 }
249}
250
251var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
252 var funcArgs = Array.prototype.slice.call(arguments, 3);
253
254 try {
255 func.apply(context, funcArgs);
256 } catch (error) {
257 this.onError(error);
258 }
259};
260
261{
262 // In DEV mode, we swap out invokeGuardedCallback for a special version
263 // that plays more nicely with the browser's DevTools. The idea is to preserve
264 // "Pause on exceptions" behavior. Because React wraps all user-provided
265 // functions in invokeGuardedCallback, and the production version of
266 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
267 // like caught exceptions, and the DevTools won't pause unless the developer
268 // takes the extra step of enabling pause on caught exceptions. This is
269 // unintuitive, though, because even though React has caught the error, from
270 // the developer's perspective, the error is uncaught.
271 //
272 // To preserve the expected "Pause on exceptions" behavior, we don't use a
273 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
274 // DOM node, and call the user-provided callback from inside an event handler
275 // for that fake event. If the callback throws, the error is "captured" using
276 // a global event handler. But because the error happens in a different
277 // event loop context, it does not interrupt the normal program flow.
278 // Effectively, this gives us try-catch behavior without actually using
279 // try-catch. Neat!
280 // Check that the browser supports the APIs we need to implement our special
281 // DEV version of invokeGuardedCallback
282 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
283 var fakeNode = document.createElement('react');
284
285 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
286 // If document doesn't exist we know for sure we will crash in this method
287 // when we call document.createEvent(). However this can cause confusing
288 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
289 // So we preemptively throw with a better message instead.
290 if (!(typeof document !== 'undefined')) {
291 {
292 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.");
293 }
294 }
295
296 var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
297 // set this to true at the beginning, then set it to false right after
298 // calling the function. If the function errors, `didError` will never be
299 // set to false. This strategy works even if the browser is flaky and
300 // fails to call our global error handler, because it doesn't rely on
301 // the error event at all.
302
303 var didError = true; // Keeps track of the value of window.event so that we can reset it
304 // during the callback to let user code access window.event in the
305 // browsers that support it.
306
307 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
308 // dispatching: https://github.com/facebook/react/issues/13688
309
310 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
311 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
312 // call the user-provided callback.
313
314 var funcArgs = Array.prototype.slice.call(arguments, 3);
315
316 function callCallback() {
317 // We immediately remove the callback from event listeners so that
318 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
319 // nested call would trigger the fake event handlers of any call higher
320 // in the stack.
321 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
322 // window.event assignment in both IE <= 10 as they throw an error
323 // "Member not found" in strict mode, and in Firefox which does not
324 // support window.event.
325
326 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
327 window.event = windowEvent;
328 }
329
330 func.apply(context, funcArgs);
331 didError = false;
332 } // Create a global error event handler. We use this to capture the value
333 // that was thrown. It's possible that this error handler will fire more
334 // than once; for example, if non-React code also calls `dispatchEvent`
335 // and a handler for that event throws. We should be resilient to most of
336 // those cases. Even if our error event handler fires more than once, the
337 // last error event is always used. If the callback actually does error,
338 // we know that the last error event is the correct one, because it's not
339 // possible for anything else to have happened in between our callback
340 // erroring and the code that follows the `dispatchEvent` call below. If
341 // the callback doesn't error, but the error event was fired, we know to
342 // ignore it because `didError` will be false, as described above.
343
344
345 var error; // Use this to track whether the error event is ever called.
346
347 var didSetError = false;
348 var isCrossOriginError = false;
349
350 function handleWindowError(event) {
351 error = event.error;
352 didSetError = true;
353
354 if (error === null && event.colno === 0 && event.lineno === 0) {
355 isCrossOriginError = true;
356 }
357
358 if (event.defaultPrevented) {
359 // Some other error handler has prevented default.
360 // Browsers silence the error report if this happens.
361 // We'll remember this to later decide whether to log it or not.
362 if (error != null && typeof error === 'object') {
363 try {
364 error._suppressLogging = true;
365 } catch (inner) {// Ignore.
366 }
367 }
368 }
369 } // Create a fake event type.
370
371
372 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
373
374 window.addEventListener('error', handleWindowError);
375 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
376 // errors, it will trigger our global error handler.
377
378 evt.initEvent(evtType, false, false);
379 fakeNode.dispatchEvent(evt);
380
381 if (windowEventDescriptor) {
382 Object.defineProperty(window, 'event', windowEventDescriptor);
383 }
384
385 if (didError) {
386 if (!didSetError) {
387 // The callback errored, but the error event never fired.
388 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.');
389 } else if (isCrossOriginError) {
390 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.');
391 }
392
393 this.onError(error);
394 } // Remove our event listeners
395
396
397 window.removeEventListener('error', handleWindowError);
398 };
399
400 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
401 }
402}
403
404var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
405
406var hasError = false;
407var caughtError = null; // Used by event system to capture/rethrow the first error.
408
409var hasRethrowError = false;
410var rethrowError = null;
411var reporter = {
412 onError: function (error) {
413 hasError = true;
414 caughtError = error;
415 }
416};
417/**
418 * Call a function while guarding against errors that happens within it.
419 * Returns an error if it throws, otherwise null.
420 *
421 * In production, this is implemented using a try-catch. The reason we don't
422 * use a try-catch directly is so that we can swap out a different
423 * implementation in DEV mode.
424 *
425 * @param {String} name of the guard to use for logging or debugging
426 * @param {Function} func The function to invoke
427 * @param {*} context The context to use when calling the function
428 * @param {...*} args Arguments for function
429 */
430
431function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
432 hasError = false;
433 caughtError = null;
434 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
435}
436/**
437 * Same as invokeGuardedCallback, but instead of returning an error, it stores
438 * it in a global so it can be rethrown by `rethrowCaughtError` later.
439 * TODO: See if caughtError and rethrowError can be unified.
440 *
441 * @param {String} name of the guard to use for logging or debugging
442 * @param {Function} func The function to invoke
443 * @param {*} context The context to use when calling the function
444 * @param {...*} args Arguments for function
445 */
446
447function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
448 invokeGuardedCallback.apply(this, arguments);
449
450 if (hasError) {
451 var error = clearCaughtError();
452
453 if (!hasRethrowError) {
454 hasRethrowError = true;
455 rethrowError = error;
456 }
457 }
458}
459/**
460 * During execution of guarded functions we will capture the first error which
461 * we will rethrow to be handled by the top level error handler.
462 */
463
464function rethrowCaughtError() {
465 if (hasRethrowError) {
466 var error = rethrowError;
467 hasRethrowError = false;
468 rethrowError = null;
469 throw error;
470 }
471}
472function hasCaughtError() {
473 return hasError;
474}
475function clearCaughtError() {
476 if (hasError) {
477 var error = caughtError;
478 hasError = false;
479 caughtError = null;
480 return error;
481 } else {
482 {
483 {
484 throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
485 }
486 }
487 }
488}
489
490/**
491 * Similar to invariant but only logs a warning if the condition is not met.
492 * This can be used to log issues in development environments in critical
493 * paths. Removing the logging code for production environments will keep the
494 * same logic and follow the same code paths.
495 */
496var warningWithoutStack = function () {};
497
498{
499 warningWithoutStack = function (condition, format) {
500 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
501 args[_key - 2] = arguments[_key];
502 }
503
504 if (format === undefined) {
505 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
506 }
507
508 if (args.length > 8) {
509 // Check before the condition to catch violations early.
510 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
511 }
512
513 if (condition) {
514 return;
515 }
516
517 if (typeof console !== 'undefined') {
518 var argsWithFormat = args.map(function (item) {
519 return '' + item;
520 });
521 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
522 // breaks IE9: https://github.com/facebook/react/issues/13610
523
524 Function.prototype.apply.call(console.error, console, argsWithFormat);
525 }
526
527 try {
528 // --- Welcome to debugging React ---
529 // This error was thrown as a convenience so that you can use this stack
530 // to find the callsite that caused this warning to fire.
531 var argIndex = 0;
532 var message = 'Warning: ' + format.replace(/%s/g, function () {
533 return args[argIndex++];
534 });
535 throw new Error(message);
536 } catch (x) {}
537 };
538}
539
540var warningWithoutStack$1 = warningWithoutStack;
541
542var getFiberCurrentPropsFromNode = null;
543var getInstanceFromNode = null;
544var getNodeFromInstance = null;
545function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
546 getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
547 getInstanceFromNode = getInstanceFromNodeImpl;
548 getNodeFromInstance = getNodeFromInstanceImpl;
549
550 {
551 !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
552 }
553}
554var validateEventDispatches;
555
556{
557 validateEventDispatches = function (event) {
558 var dispatchListeners = event._dispatchListeners;
559 var dispatchInstances = event._dispatchInstances;
560 var listenersIsArr = Array.isArray(dispatchListeners);
561 var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
562 var instancesIsArr = Array.isArray(dispatchInstances);
563 var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
564 !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0;
565 };
566}
567/**
568 * Dispatch the event to the listener.
569 * @param {SyntheticEvent} event SyntheticEvent to handle
570 * @param {function} listener Application-level callback
571 * @param {*} inst Internal component instance
572 */
573
574
575function executeDispatch(event, listener, inst) {
576 var type = event.type || 'unknown-event';
577 event.currentTarget = getNodeFromInstance(inst);
578 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
579 event.currentTarget = null;
580}
581/**
582 * Standard/simple iteration through an event's collected dispatches.
583 */
584
585function executeDispatchesInOrder(event) {
586 var dispatchListeners = event._dispatchListeners;
587 var dispatchInstances = event._dispatchInstances;
588
589 {
590 validateEventDispatches(event);
591 }
592
593 if (Array.isArray(dispatchListeners)) {
594 for (var i = 0; i < dispatchListeners.length; i++) {
595 if (event.isPropagationStopped()) {
596 break;
597 } // Listeners and Instances are two parallel arrays that are always in sync.
598
599
600 executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
601 }
602 } else if (dispatchListeners) {
603 executeDispatch(event, dispatchListeners, dispatchInstances);
604 }
605
606 event._dispatchListeners = null;
607 event._dispatchInstances = null;
608}
609/**
610 * @see executeDispatchesInOrderStopAtTrueImpl
611 */
612
613
614
615/**
616 * Execution of a "direct" dispatch - there must be at most one dispatch
617 * accumulated on the event or it is considered an error. It doesn't really make
618 * sense for an event with multiple dispatches (bubbled) to keep track of the
619 * return values at each dispatch execution, but it does tend to make sense when
620 * dealing with "direct" dispatches.
621 *
622 * @return {*} The return value of executing the single dispatch.
623 */
624
625
626/**
627 * @param {SyntheticEvent} event
628 * @return {boolean} True iff number of dispatches accumulated is greater than 0.
629 */
630
631/**
632 * Accumulates items that must not be null or undefined into the first one. This
633 * is used to conserve memory by avoiding array allocations, and thus sacrifices
634 * API cleanness. Since `current` can be null before being passed in and not
635 * null after this function, make sure to assign it back to `current`:
636 *
637 * `a = accumulateInto(a, b);`
638 *
639 * This API should be sparingly used. Try `accumulate` for something cleaner.
640 *
641 * @return {*|array<*>} An accumulation of items.
642 */
643
644function accumulateInto(current, next) {
645 if (!(next != null)) {
646 {
647 throw Error("accumulateInto(...): Accumulated items must not be null or undefined.");
648 }
649 }
650
651 if (current == null) {
652 return next;
653 } // Both are not empty. Warning: Never call x.concat(y) when you are not
654 // certain that x is an Array (x could be a string with concat method).
655
656
657 if (Array.isArray(current)) {
658 if (Array.isArray(next)) {
659 current.push.apply(current, next);
660 return current;
661 }
662
663 current.push(next);
664 return current;
665 }
666
667 if (Array.isArray(next)) {
668 // A bit too dangerous to mutate `next`.
669 return [current].concat(next);
670 }
671
672 return [current, next];
673}
674
675/**
676 * @param {array} arr an "accumulation" of items which is either an Array or
677 * a single item. Useful when paired with the `accumulate` module. This is a
678 * simple utility that allows us to reason about a collection of items, but
679 * handling the case when there is exactly one item (and we do not need to
680 * allocate an array).
681 * @param {function} cb Callback invoked with each element or a collection.
682 * @param {?} [scope] Scope used as `this` in a callback.
683 */
684function forEachAccumulated(arr, cb, scope) {
685 if (Array.isArray(arr)) {
686 arr.forEach(cb, scope);
687 } else if (arr) {
688 cb.call(scope, arr);
689 }
690}
691
692/**
693 * Internal queue of events that have accumulated their dispatches and are
694 * waiting to have their dispatches executed.
695 */
696
697var eventQueue = null;
698/**
699 * Dispatches an event and releases it back into the pool, unless persistent.
700 *
701 * @param {?object} event Synthetic event to be dispatched.
702 * @private
703 */
704
705var executeDispatchesAndRelease = function (event) {
706 if (event) {
707 executeDispatchesInOrder(event);
708
709 if (!event.isPersistent()) {
710 event.constructor.release(event);
711 }
712 }
713};
714
715var executeDispatchesAndReleaseTopLevel = function (e) {
716 return executeDispatchesAndRelease(e);
717};
718
719function runEventsInBatch(events) {
720 if (events !== null) {
721 eventQueue = accumulateInto(eventQueue, events);
722 } // Set `eventQueue` to null before processing it so that we can tell if more
723 // events get enqueued while processing.
724
725
726 var processingEventQueue = eventQueue;
727 eventQueue = null;
728
729 if (!processingEventQueue) {
730 return;
731 }
732
733 forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
734
735 if (!!eventQueue) {
736 {
737 throw Error("processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.");
738 }
739 } // This would be a good time to rethrow if any of the event handlers threw.
740
741
742 rethrowCaughtError();
743}
744
745function isInteractive(tag) {
746 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
747}
748
749function shouldPreventMouseEvent(name, type, props) {
750 switch (name) {
751 case 'onClick':
752 case 'onClickCapture':
753 case 'onDoubleClick':
754 case 'onDoubleClickCapture':
755 case 'onMouseDown':
756 case 'onMouseDownCapture':
757 case 'onMouseMove':
758 case 'onMouseMoveCapture':
759 case 'onMouseUp':
760 case 'onMouseUpCapture':
761 return !!(props.disabled && isInteractive(type));
762
763 default:
764 return false;
765 }
766}
767/**
768 * This is a unified interface for event plugins to be installed and configured.
769 *
770 * Event plugins can implement the following properties:
771 *
772 * `extractEvents` {function(string, DOMEventTarget, string, object): *}
773 * Required. When a top-level event is fired, this method is expected to
774 * extract synthetic events that will in turn be queued and dispatched.
775 *
776 * `eventTypes` {object}
777 * Optional, plugins that fire events must publish a mapping of registration
778 * names that are used to register listeners. Values of this mapping must
779 * be objects that contain `registrationName` or `phasedRegistrationNames`.
780 *
781 * `executeDispatch` {function(object, function, string)}
782 * Optional, allows plugins to override how an event gets dispatched. By
783 * default, the listener is simply invoked.
784 *
785 * Each plugin that is injected into `EventsPluginHub` is immediately operable.
786 *
787 * @public
788 */
789
790/**
791 * Methods for injecting dependencies.
792 */
793
794
795var injection = {
796 /**
797 * @param {array} InjectedEventPluginOrder
798 * @public
799 */
800 injectEventPluginOrder: injectEventPluginOrder,
801
802 /**
803 * @param {object} injectedNamesToPlugins Map from names to plugin modules.
804 */
805 injectEventPluginsByName: injectEventPluginsByName
806};
807/**
808 * @param {object} inst The instance, which is the source of events.
809 * @param {string} registrationName Name of listener (e.g. `onClick`).
810 * @return {?function} The stored callback.
811 */
812
813function getListener(inst, registrationName) {
814 var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
815 // live here; needs to be moved to a better place soon
816
817 var stateNode = inst.stateNode;
818
819 if (!stateNode) {
820 // Work in progress (ex: onload events in incremental mode).
821 return null;
822 }
823
824 var props = getFiberCurrentPropsFromNode(stateNode);
825
826 if (!props) {
827 // Work in progress.
828 return null;
829 }
830
831 listener = props[registrationName];
832
833 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
834 return null;
835 }
836
837 if (!(!listener || typeof listener === 'function')) {
838 {
839 throw Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
840 }
841 }
842
843 return listener;
844}
845/**
846 * Allows registered plugins an opportunity to extract events from top-level
847 * native browser events.
848 *
849 * @return {*} An accumulation of synthetic events.
850 * @internal
851 */
852
853function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
854 var events = null;
855
856 for (var i = 0; i < plugins.length; i++) {
857 // Not every plugin in the ordering may be loaded at runtime.
858 var possiblePlugin = plugins[i];
859
860 if (possiblePlugin) {
861 var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
862
863 if (extractedEvents) {
864 events = accumulateInto(events, extractedEvents);
865 }
866 }
867 }
868
869 return events;
870}
871
872function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
873 var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
874 runEventsInBatch(events);
875}
876
877var FunctionComponent = 0;
878var ClassComponent = 1;
879var IndeterminateComponent = 2; // Before we know whether it is function or class
880
881var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
882
883var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
884
885var HostComponent = 5;
886var HostText = 6;
887var Fragment = 7;
888var Mode = 8;
889var ContextConsumer = 9;
890var ContextProvider = 10;
891var ForwardRef = 11;
892var Profiler = 12;
893var SuspenseComponent = 13;
894var MemoComponent = 14;
895var SimpleMemoComponent = 15;
896var LazyComponent = 16;
897var IncompleteClassComponent = 17;
898var DehydratedFragment = 18;
899var SuspenseListComponent = 19;
900var FundamentalComponent = 20;
901var ScopeComponent = 21;
902
903var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
904// Current owner and dispatcher used to share the same ref,
905// but PR #14548 split them out to better support the react-debug-tools package.
906
907if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
908 ReactSharedInternals.ReactCurrentDispatcher = {
909 current: null
910 };
911}
912
913if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
914 ReactSharedInternals.ReactCurrentBatchConfig = {
915 suspense: null
916 };
917}
918
919var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
920var describeComponentFrame = function (name, source, ownerName) {
921 var sourceInfo = '';
922
923 if (source) {
924 var path = source.fileName;
925 var fileName = path.replace(BEFORE_SLASH_RE, '');
926
927 {
928 // In DEV, include code for a common special case:
929 // prefer "folder/index.js" instead of just "index.js".
930 if (/^index\./.test(fileName)) {
931 var match = path.match(BEFORE_SLASH_RE);
932
933 if (match) {
934 var pathBeforeSlash = match[1];
935
936 if (pathBeforeSlash) {
937 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
938 fileName = folderName + '/' + fileName;
939 }
940 }
941 }
942 }
943
944 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
945 } else if (ownerName) {
946 sourceInfo = ' (created by ' + ownerName + ')';
947 }
948
949 return '\n in ' + (name || 'Unknown') + sourceInfo;
950};
951
952// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
953// nor polyfill, then a plain number is used for performance.
954var hasSymbol = typeof Symbol === 'function' && Symbol.for;
955var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
956var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
957var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
958var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
959var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
960var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
961var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
962// (unstable) APIs that have been removed. Can we remove the symbols?
963
964
965var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
966var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
967var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
968var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
969var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
970var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
971var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
972var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
973var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
974var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
975var FAUX_ITERATOR_SYMBOL = '@@iterator';
976function getIteratorFn(maybeIterable) {
977 if (maybeIterable === null || typeof maybeIterable !== 'object') {
978 return null;
979 }
980
981 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
982
983 if (typeof maybeIterator === 'function') {
984 return maybeIterator;
985 }
986
987 return null;
988}
989
990/**
991 * Similar to invariant but only logs a warning if the condition is not met.
992 * This can be used to log issues in development environments in critical
993 * paths. Removing the logging code for production environments will keep the
994 * same logic and follow the same code paths.
995 */
996
997var warning = warningWithoutStack$1;
998
999{
1000 warning = function (condition, format) {
1001 if (condition) {
1002 return;
1003 }
1004
1005 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1006 var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args
1007
1008 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1009 args[_key - 2] = arguments[_key];
1010 }
1011
1012 warningWithoutStack$1.apply(void 0, [false, format + '%s'].concat(args, [stack]));
1013 };
1014}
1015
1016var warning$1 = warning;
1017
1018var Uninitialized = -1;
1019var Pending = 0;
1020var Resolved = 1;
1021var Rejected = 2;
1022function refineResolvedLazyComponent(lazyComponent) {
1023 return lazyComponent._status === Resolved ? lazyComponent._result : null;
1024}
1025function initializeLazyComponentType(lazyComponent) {
1026 if (lazyComponent._status === Uninitialized) {
1027 lazyComponent._status = Pending;
1028 var ctor = lazyComponent._ctor;
1029 var thenable = ctor();
1030 lazyComponent._result = thenable;
1031 thenable.then(function (moduleObject) {
1032 if (lazyComponent._status === Pending) {
1033 var defaultExport = moduleObject.default;
1034
1035 {
1036 if (defaultExport === undefined) {
1037 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);
1038 }
1039 }
1040
1041 lazyComponent._status = Resolved;
1042 lazyComponent._result = defaultExport;
1043 }
1044 }, function (error) {
1045 if (lazyComponent._status === Pending) {
1046 lazyComponent._status = Rejected;
1047 lazyComponent._result = error;
1048 }
1049 });
1050 }
1051}
1052
1053function getWrappedName(outerType, innerType, wrapperName) {
1054 var functionName = innerType.displayName || innerType.name || '';
1055 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
1056}
1057
1058function getComponentName(type) {
1059 if (type == null) {
1060 // Host root, text node or just invalid type.
1061 return null;
1062 }
1063
1064 {
1065 if (typeof type.tag === 'number') {
1066 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
1067 }
1068 }
1069
1070 if (typeof type === 'function') {
1071 return type.displayName || type.name || null;
1072 }
1073
1074 if (typeof type === 'string') {
1075 return type;
1076 }
1077
1078 switch (type) {
1079 case REACT_FRAGMENT_TYPE:
1080 return 'Fragment';
1081
1082 case REACT_PORTAL_TYPE:
1083 return 'Portal';
1084
1085 case REACT_PROFILER_TYPE:
1086 return "Profiler";
1087
1088 case REACT_STRICT_MODE_TYPE:
1089 return 'StrictMode';
1090
1091 case REACT_SUSPENSE_TYPE:
1092 return 'Suspense';
1093
1094 case REACT_SUSPENSE_LIST_TYPE:
1095 return 'SuspenseList';
1096 }
1097
1098 if (typeof type === 'object') {
1099 switch (type.$$typeof) {
1100 case REACT_CONTEXT_TYPE:
1101 return 'Context.Consumer';
1102
1103 case REACT_PROVIDER_TYPE:
1104 return 'Context.Provider';
1105
1106 case REACT_FORWARD_REF_TYPE:
1107 return getWrappedName(type, type.render, 'ForwardRef');
1108
1109 case REACT_MEMO_TYPE:
1110 return getComponentName(type.type);
1111
1112 case REACT_LAZY_TYPE:
1113 {
1114 var thenable = type;
1115 var resolvedThenable = refineResolvedLazyComponent(thenable);
1116
1117 if (resolvedThenable) {
1118 return getComponentName(resolvedThenable);
1119 }
1120
1121 break;
1122 }
1123 }
1124 }
1125
1126 return null;
1127}
1128
1129var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1130
1131function describeFiber(fiber) {
1132 switch (fiber.tag) {
1133 case HostRoot:
1134 case HostPortal:
1135 case HostText:
1136 case Fragment:
1137 case ContextProvider:
1138 case ContextConsumer:
1139 return '';
1140
1141 default:
1142 var owner = fiber._debugOwner;
1143 var source = fiber._debugSource;
1144 var name = getComponentName(fiber.type);
1145 var ownerName = null;
1146
1147 if (owner) {
1148 ownerName = getComponentName(owner.type);
1149 }
1150
1151 return describeComponentFrame(name, source, ownerName);
1152 }
1153}
1154
1155function getStackByFiberInDevAndProd(workInProgress) {
1156 var info = '';
1157 var node = workInProgress;
1158
1159 do {
1160 info += describeFiber(node);
1161 node = node.return;
1162 } while (node);
1163
1164 return info;
1165}
1166var current = null;
1167var phase = null;
1168function getCurrentFiberOwnerNameInDevOrNull() {
1169 {
1170 if (current === null) {
1171 return null;
1172 }
1173
1174 var owner = current._debugOwner;
1175
1176 if (owner !== null && typeof owner !== 'undefined') {
1177 return getComponentName(owner.type);
1178 }
1179 }
1180
1181 return null;
1182}
1183function getCurrentFiberStackInDev() {
1184 {
1185 if (current === null) {
1186 return '';
1187 } // Safe because if current fiber exists, we are reconciling,
1188 // and it is guaranteed to be the work-in-progress version.
1189
1190
1191 return getStackByFiberInDevAndProd(current);
1192 }
1193
1194 return '';
1195}
1196function resetCurrentFiber() {
1197 {
1198 ReactDebugCurrentFrame.getCurrentStack = null;
1199 current = null;
1200 phase = null;
1201 }
1202}
1203function setCurrentFiber(fiber) {
1204 {
1205 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1206 current = fiber;
1207 phase = null;
1208 }
1209}
1210function setCurrentPhase(lifeCyclePhase) {
1211 {
1212 phase = lifeCyclePhase;
1213 }
1214}
1215
1216var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
1217
1218function endsWith(subject, search) {
1219 var length = subject.length;
1220 return subject.substring(length - search.length, length) === search;
1221}
1222
1223var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1224var _assign = ReactInternals.assign;
1225
1226var PLUGIN_EVENT_SYSTEM = 1;
1227var RESPONDER_EVENT_SYSTEM = 1 << 1;
1228var IS_PASSIVE = 1 << 2;
1229var IS_ACTIVE = 1 << 3;
1230var PASSIVE_NOT_SUPPORTED = 1 << 4;
1231var IS_REPLAYED = 1 << 5;
1232
1233var restoreImpl = null;
1234var restoreTarget = null;
1235var restoreQueue = null;
1236
1237function restoreStateOfTarget(target) {
1238 // We perform this translation at the end of the event loop so that we
1239 // always receive the correct fiber here
1240 var internalInstance = getInstanceFromNode(target);
1241
1242 if (!internalInstance) {
1243 // Unmounted
1244 return;
1245 }
1246
1247 if (!(typeof restoreImpl === 'function')) {
1248 {
1249 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.");
1250 }
1251 }
1252
1253 var props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
1254 restoreImpl(internalInstance.stateNode, internalInstance.type, props);
1255}
1256
1257function setRestoreImplementation(impl) {
1258 restoreImpl = impl;
1259}
1260function enqueueStateRestore(target) {
1261 if (restoreTarget) {
1262 if (restoreQueue) {
1263 restoreQueue.push(target);
1264 } else {
1265 restoreQueue = [target];
1266 }
1267 } else {
1268 restoreTarget = target;
1269 }
1270}
1271function needsStateRestore() {
1272 return restoreTarget !== null || restoreQueue !== null;
1273}
1274function restoreStateIfNeeded() {
1275 if (!restoreTarget) {
1276 return;
1277 }
1278
1279 var target = restoreTarget;
1280 var queuedTargets = restoreQueue;
1281 restoreTarget = null;
1282 restoreQueue = null;
1283 restoreStateOfTarget(target);
1284
1285 if (queuedTargets) {
1286 for (var i = 0; i < queuedTargets.length; i++) {
1287 restoreStateOfTarget(queuedTargets[i]);
1288 }
1289 }
1290}
1291
1292var enableUserTimingAPI = true; // Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
1293
1294var debugRenderPhaseSideEffects = false; // In some cases, StrictMode should also double-render lifecycles.
1295// This can be confusing for tests though,
1296// And it can be bad for performance in production.
1297// This feature flag can be used to control the behavior:
1298
1299var debugRenderPhaseSideEffectsForStrictMode = true; // To preserve the "Pause on caught exceptions" behavior of the debugger, we
1300// replay the begin phase of a failed component inside invokeGuardedCallback.
1301
1302var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
1303
1304var warnAboutDeprecatedLifecycles = true; // Gather advanced timing metrics for Profiler subtrees.
1305
1306var enableProfilerTimer = true; // Trace which interactions trigger each commit.
1307
1308var enableSchedulerTracing = true; // SSR experiments
1309
1310var enableSuspenseServerRenderer = false;
1311var enableSelectiveHydration = false; // Only used in www builds.
1312
1313 // Only used in www builds.
1314
1315 // Disable javascript: URL strings in href for XSS protection.
1316
1317var disableJavaScriptURLs = false; // React Fire: prevent the value and checked attributes from syncing
1318// with their related DOM properties
1319
1320var disableInputAttributeSyncing = false; // These APIs will no longer be "unstable" in the upcoming 16.7 release,
1321// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
1322
1323var exposeConcurrentModeAPIs = false;
1324var warnAboutShorthandPropertyCollision = false; // Experimental React Flare event system and event components support.
1325
1326var enableFlareAPI = false; // Experimental Host Component support.
1327
1328var enableFundamentalAPI = false; // Experimental Scope support.
1329
1330var enableScopeAPI = false; // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
1331
1332 // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
1333// Till then, we warn about the missing mock, but still fallback to a sync mode compatible version
1334
1335var warnAboutUnmockedScheduler = false; // For tests, we flush suspense fallbacks in an act scope;
1336// *except* in some of our own tests, where we test incremental loading states.
1337
1338var flushSuspenseFallbacksInTests = true; // Add a callback property to suspense to notify which promises are currently
1339// in the update queue. This allows reporting and tracing of what is causing
1340// the user to see a loading state.
1341// Also allows hydration callbacks to fire when a dehydrated boundary gets
1342// hydrated or deleted.
1343
1344var enableSuspenseCallback = false; // Part of the simplification of React.createElement so we can eventually move
1345// from React.createElement to React.jsx
1346// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
1347
1348var warnAboutDefaultPropsOnFunctionComponents = false;
1349var warnAboutStringRefs = false;
1350var disableLegacyContext = false;
1351var disableSchedulerTimeoutBasedOnReactExpirationTime = false;
1352var enableTrustedTypesIntegration = false;
1353
1354// the renderer. Such as when we're dispatching events or if third party
1355// libraries need to call batchedUpdates. Eventually, this API will go away when
1356// everything is batched by default. We'll then have a similar API to opt-out of
1357// scheduled work and instead do synchronous work.
1358// Defaults
1359
1360var batchedUpdatesImpl = function (fn, bookkeeping) {
1361 return fn(bookkeeping);
1362};
1363
1364var discreteUpdatesImpl = function (fn, a, b, c) {
1365 return fn(a, b, c);
1366};
1367
1368var flushDiscreteUpdatesImpl = function () {};
1369
1370var batchedEventUpdatesImpl = batchedUpdatesImpl;
1371var isInsideEventHandler = false;
1372var isBatchingEventUpdates = false;
1373
1374function finishEventHandler() {
1375 // Here we wait until all updates have propagated, which is important
1376 // when using controlled components within layers:
1377 // https://github.com/facebook/react/issues/1698
1378 // Then we restore state of any controlled component.
1379 var controlledComponentsHavePendingUpdates = needsStateRestore();
1380
1381 if (controlledComponentsHavePendingUpdates) {
1382 // If a controlled event was fired, we may need to restore the state of
1383 // the DOM node back to the controlled value. This is necessary when React
1384 // bails out of the update without touching the DOM.
1385 flushDiscreteUpdatesImpl();
1386 restoreStateIfNeeded();
1387 }
1388}
1389
1390function batchedUpdates(fn, bookkeeping) {
1391 if (isInsideEventHandler) {
1392 // If we are currently inside another batch, we need to wait until it
1393 // fully completes before restoring state.
1394 return fn(bookkeeping);
1395 }
1396
1397 isInsideEventHandler = true;
1398
1399 try {
1400 return batchedUpdatesImpl(fn, bookkeeping);
1401 } finally {
1402 isInsideEventHandler = false;
1403 finishEventHandler();
1404 }
1405}
1406function batchedEventUpdates(fn, a, b) {
1407 if (isBatchingEventUpdates) {
1408 // If we are currently inside another batch, we need to wait until it
1409 // fully completes before restoring state.
1410 return fn(a, b);
1411 }
1412
1413 isBatchingEventUpdates = true;
1414
1415 try {
1416 return batchedEventUpdatesImpl(fn, a, b);
1417 } finally {
1418 isBatchingEventUpdates = false;
1419 finishEventHandler();
1420 }
1421} // This is for the React Flare event system
1422
1423function executeUserEventHandler(fn, value) {
1424 var previouslyInEventHandler = isInsideEventHandler;
1425
1426 try {
1427 isInsideEventHandler = true;
1428 var type = typeof value === 'object' && value !== null ? value.type : '';
1429 invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value);
1430 } finally {
1431 isInsideEventHandler = previouslyInEventHandler;
1432 }
1433}
1434function discreteUpdates(fn, a, b, c) {
1435 var prevIsInsideEventHandler = isInsideEventHandler;
1436 isInsideEventHandler = true;
1437
1438 try {
1439 return discreteUpdatesImpl(fn, a, b, c);
1440 } finally {
1441 isInsideEventHandler = prevIsInsideEventHandler;
1442
1443 if (!isInsideEventHandler) {
1444 finishEventHandler();
1445 }
1446 }
1447}
1448var lastFlushedEventTimeStamp = 0;
1449function flushDiscreteUpdatesIfNeeded(timeStamp) {
1450 // event.timeStamp isn't overly reliable due to inconsistencies in
1451 // how different browsers have historically provided the time stamp.
1452 // Some browsers provide high-resolution time stamps for all events,
1453 // some provide low-resolution time stamps for all events. FF < 52
1454 // even mixes both time stamps together. Some browsers even report
1455 // negative time stamps or time stamps that are 0 (iOS9) in some cases.
1456 // Given we are only comparing two time stamps with equality (!==),
1457 // we are safe from the resolution differences. If the time stamp is 0
1458 // we bail-out of preventing the flush, which can affect semantics,
1459 // such as if an earlier flush removes or adds event listeners that
1460 // are fired in the subsequent flush. However, this is the same
1461 // behaviour as we had before this change, so the risks are low.
1462 if (!isInsideEventHandler && (!enableFlareAPI || timeStamp === 0 || lastFlushedEventTimeStamp !== timeStamp)) {
1463 lastFlushedEventTimeStamp = timeStamp;
1464 flushDiscreteUpdatesImpl();
1465 }
1466}
1467function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
1468 batchedUpdatesImpl = _batchedUpdatesImpl;
1469 discreteUpdatesImpl = _discreteUpdatesImpl;
1470 flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
1471 batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
1472}
1473
1474var DiscreteEvent = 0;
1475var UserBlockingEvent = 1;
1476var ContinuousEvent = 2;
1477
1478var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1479var _ReactInternals$Sched = ReactInternals$1.Scheduler;
1480var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
1481var unstable_now = _ReactInternals$Sched.unstable_now;
1482var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
1483var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
1484var unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint;
1485var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
1486var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
1487var unstable_next = _ReactInternals$Sched.unstable_next;
1488var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
1489var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
1490var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
1491var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
1492var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
1493var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
1494var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
1495var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
1496var unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate;
1497var unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
1498
1499// CommonJS interop named imports.
1500
1501var UserBlockingPriority = unstable_UserBlockingPriority;
1502var runWithPriority = unstable_runWithPriority;
1503var listenToResponderEventTypesImpl;
1504function setListenToResponderEventTypes(_listenToResponderEventTypesImpl) {
1505 listenToResponderEventTypesImpl = _listenToResponderEventTypesImpl;
1506}
1507var rootEventTypesToEventResponderInstances = new Map();
1508var DoNotPropagateToNextResponder = 0;
1509var PropagateToNextResponder = 1;
1510var currentTimeStamp = 0;
1511var currentInstance = null;
1512var currentDocument = null;
1513var currentPropagationBehavior = DoNotPropagateToNextResponder;
1514var eventResponderContext = {
1515 dispatchEvent: function (eventValue, eventListener, eventPriority) {
1516 validateResponderContext();
1517 validateEventValue(eventValue);
1518
1519 switch (eventPriority) {
1520 case DiscreteEvent:
1521 {
1522 flushDiscreteUpdatesIfNeeded(currentTimeStamp);
1523 discreteUpdates(function () {
1524 return executeUserEventHandler(eventListener, eventValue);
1525 });
1526 break;
1527 }
1528
1529 case UserBlockingEvent:
1530 {
1531 runWithPriority(UserBlockingPriority, function () {
1532 return executeUserEventHandler(eventListener, eventValue);
1533 });
1534 break;
1535 }
1536
1537 case ContinuousEvent:
1538 {
1539 executeUserEventHandler(eventListener, eventValue);
1540 break;
1541 }
1542 }
1543 },
1544 isTargetWithinResponder: function (target) {
1545 validateResponderContext();
1546
1547 if (target != null) {
1548 var fiber = getClosestInstanceFromNode(target);
1549 var responderFiber = currentInstance.fiber;
1550
1551 while (fiber !== null) {
1552 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1553 return true;
1554 }
1555
1556 fiber = fiber.return;
1557 }
1558 }
1559
1560 return false;
1561 },
1562 isTargetWithinResponderScope: function (target) {
1563 validateResponderContext();
1564 var componentInstance = currentInstance;
1565 var responder = componentInstance.responder;
1566
1567 if (target != null) {
1568 var fiber = getClosestInstanceFromNode(target);
1569 var responderFiber = currentInstance.fiber;
1570
1571 while (fiber !== null) {
1572 if (fiber === responderFiber || fiber.alternate === responderFiber) {
1573 return true;
1574 }
1575
1576 if (doesFiberHaveResponder(fiber, responder)) {
1577 return false;
1578 }
1579
1580 fiber = fiber.return;
1581 }
1582 }
1583
1584 return false;
1585 },
1586 isTargetWithinNode: function (childTarget, parentTarget) {
1587 validateResponderContext();
1588 var childFiber = getClosestInstanceFromNode(childTarget);
1589 var parentFiber = getClosestInstanceFromNode(parentTarget);
1590
1591 if (childFiber != null && parentFiber != null) {
1592 var parentAlternateFiber = parentFiber.alternate;
1593 var node = childFiber;
1594
1595 while (node !== null) {
1596 if (node === parentFiber || node === parentAlternateFiber) {
1597 return true;
1598 }
1599
1600 node = node.return;
1601 }
1602
1603 return false;
1604 } // Fallback to DOM APIs
1605
1606
1607 return parentTarget.contains(childTarget);
1608 },
1609 addRootEventTypes: function (rootEventTypes) {
1610 validateResponderContext();
1611 listenToResponderEventTypesImpl(rootEventTypes, currentDocument);
1612
1613 for (var i = 0; i < rootEventTypes.length; i++) {
1614 var rootEventType = rootEventTypes[i];
1615 var eventResponderInstance = currentInstance;
1616 registerRootEventType(rootEventType, eventResponderInstance);
1617 }
1618 },
1619 removeRootEventTypes: function (rootEventTypes) {
1620 validateResponderContext();
1621
1622 for (var i = 0; i < rootEventTypes.length; i++) {
1623 var rootEventType = rootEventTypes[i];
1624 var rootEventResponders = rootEventTypesToEventResponderInstances.get(rootEventType);
1625 var rootEventTypesSet = currentInstance.rootEventTypes;
1626
1627 if (rootEventTypesSet !== null) {
1628 rootEventTypesSet.delete(rootEventType);
1629 }
1630
1631 if (rootEventResponders !== undefined) {
1632 rootEventResponders.delete(currentInstance);
1633 }
1634 }
1635 },
1636 getActiveDocument: getActiveDocument,
1637 objectAssign: _assign,
1638 getTimeStamp: function () {
1639 validateResponderContext();
1640 return currentTimeStamp;
1641 },
1642 isTargetWithinHostComponent: function (target, elementType) {
1643 validateResponderContext();
1644 var fiber = getClosestInstanceFromNode(target);
1645
1646 while (fiber !== null) {
1647 if (fiber.tag === HostComponent && fiber.type === elementType) {
1648 return true;
1649 }
1650
1651 fiber = fiber.return;
1652 }
1653
1654 return false;
1655 },
1656 continuePropagation: function () {
1657 currentPropagationBehavior = PropagateToNextResponder;
1658 },
1659 enqueueStateRestore: enqueueStateRestore,
1660 getResponderNode: function () {
1661 validateResponderContext();
1662 var responderFiber = currentInstance.fiber;
1663
1664 if (responderFiber.tag === ScopeComponent) {
1665 return null;
1666 }
1667
1668 return responderFiber.stateNode;
1669 }
1670};
1671
1672function validateEventValue(eventValue) {
1673 if (typeof eventValue === 'object' && eventValue !== null) {
1674 var target = eventValue.target,
1675 type = eventValue.type,
1676 timeStamp = eventValue.timeStamp;
1677
1678 if (target == null || type == null || timeStamp == null) {
1679 throw new Error('context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.');
1680 }
1681
1682 var showWarning = function (name) {
1683 {
1684 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);
1685 }
1686 };
1687
1688 eventValue.isDefaultPrevented = function () {
1689 {
1690 showWarning('isDefaultPrevented()');
1691 }
1692 };
1693
1694 eventValue.isPropagationStopped = function () {
1695 {
1696 showWarning('isPropagationStopped()');
1697 }
1698 }; // $FlowFixMe: we don't need value, Flow thinks we do
1699
1700
1701 Object.defineProperty(eventValue, 'nativeEvent', {
1702 get: function () {
1703 {
1704 showWarning('nativeEvent');
1705 }
1706 }
1707 });
1708 }
1709}
1710
1711function doesFiberHaveResponder(fiber, responder) {
1712 var tag = fiber.tag;
1713
1714 if (tag === HostComponent || tag === ScopeComponent) {
1715 var dependencies = fiber.dependencies;
1716
1717 if (dependencies !== null) {
1718 var respondersMap = dependencies.responders;
1719
1720 if (respondersMap !== null && respondersMap.has(responder)) {
1721 return true;
1722 }
1723 }
1724 }
1725
1726 return false;
1727}
1728
1729function getActiveDocument() {
1730 return currentDocument;
1731}
1732
1733function createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, passive, passiveSupported) {
1734 var _ref = nativeEvent,
1735 buttons = _ref.buttons,
1736 pointerType = _ref.pointerType;
1737 var eventPointerType = '';
1738
1739 if (pointerType !== undefined) {
1740 eventPointerType = pointerType;
1741 } else if (nativeEvent.key !== undefined) {
1742 eventPointerType = 'keyboard';
1743 } else if (buttons !== undefined) {
1744 eventPointerType = 'mouse';
1745 } else if (nativeEvent.changedTouches !== undefined) {
1746 eventPointerType = 'touch';
1747 }
1748
1749 return {
1750 nativeEvent: nativeEvent,
1751 passive: passive,
1752 passiveSupported: passiveSupported,
1753 pointerType: eventPointerType,
1754 target: nativeEventTarget,
1755 type: topLevelType
1756 };
1757}
1758
1759function responderEventTypesContainType(eventTypes, type) {
1760 for (var i = 0, len = eventTypes.length; i < len; i++) {
1761 if (eventTypes[i] === type) {
1762 return true;
1763 }
1764 }
1765
1766 return false;
1767}
1768
1769function validateResponderTargetEventTypes(eventType, responder) {
1770 var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder
1771
1772 if (targetEventTypes !== null) {
1773 return responderEventTypesContainType(targetEventTypes, eventType);
1774 }
1775
1776 return false;
1777}
1778
1779function traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1780 var isPassiveEvent = (eventSystemFlags & IS_PASSIVE) !== 0;
1781 var isPassiveSupported = (eventSystemFlags & PASSIVE_NOT_SUPPORTED) === 0;
1782 var isPassive = isPassiveEvent || !isPassiveSupported;
1783 var eventType = isPassive ? topLevelType : topLevelType + '_active'; // Trigger event responders in this order:
1784 // - Bubble target responder phase
1785 // - Root responder phase
1786
1787 var visitedResponders = new Set();
1788 var responderEvent = createDOMResponderEvent(topLevelType, nativeEvent, nativeEventTarget, isPassiveEvent, isPassiveSupported);
1789 var node = targetFiber;
1790 var insidePortal = false;
1791
1792 while (node !== null) {
1793 var _node = node,
1794 dependencies = _node.dependencies,
1795 tag = _node.tag;
1796
1797 if (tag === HostPortal) {
1798 insidePortal = true;
1799 } else if ((tag === HostComponent || tag === ScopeComponent) && dependencies !== null) {
1800 var respondersMap = dependencies.responders;
1801
1802 if (respondersMap !== null) {
1803 var responderInstances = Array.from(respondersMap.values());
1804
1805 for (var i = 0, length = responderInstances.length; i < length; i++) {
1806 var responderInstance = responderInstances[i];
1807 var props = responderInstance.props,
1808 responder = responderInstance.responder,
1809 state = responderInstance.state;
1810
1811 if (!visitedResponders.has(responder) && validateResponderTargetEventTypes(eventType, responder) && (!insidePortal || responder.targetPortalPropagation)) {
1812 visitedResponders.add(responder);
1813 var onEvent = responder.onEvent;
1814
1815 if (onEvent !== null) {
1816 currentInstance = responderInstance;
1817 onEvent(responderEvent, eventResponderContext, props, state);
1818
1819 if (currentPropagationBehavior === PropagateToNextResponder) {
1820 visitedResponders.delete(responder);
1821 currentPropagationBehavior = DoNotPropagateToNextResponder;
1822 }
1823 }
1824 }
1825 }
1826 }
1827 }
1828
1829 node = node.return;
1830 } // Root phase
1831
1832
1833 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(eventType);
1834
1835 if (rootEventResponderInstances !== undefined) {
1836 var _responderInstances = Array.from(rootEventResponderInstances);
1837
1838 for (var _i = 0; _i < _responderInstances.length; _i++) {
1839 var _responderInstance = _responderInstances[_i];
1840 var props = _responderInstance.props,
1841 responder = _responderInstance.responder,
1842 state = _responderInstance.state;
1843 var onRootEvent = responder.onRootEvent;
1844
1845 if (onRootEvent !== null) {
1846 currentInstance = _responderInstance;
1847 onRootEvent(responderEvent, eventResponderContext, props, state);
1848 }
1849 }
1850 }
1851}
1852
1853function mountEventResponder(responder, responderInstance, props, state) {
1854 var onMount = responder.onMount;
1855
1856 if (onMount !== null) {
1857 var previousInstance = currentInstance;
1858 currentInstance = responderInstance;
1859
1860 try {
1861 batchedEventUpdates(function () {
1862 onMount(eventResponderContext, props, state);
1863 });
1864 } finally {
1865 currentInstance = previousInstance;
1866 }
1867 }
1868}
1869function unmountEventResponder(responderInstance) {
1870 var responder = responderInstance.responder;
1871 var onUnmount = responder.onUnmount;
1872
1873 if (onUnmount !== null) {
1874 var props = responderInstance.props,
1875 state = responderInstance.state;
1876 var previousInstance = currentInstance;
1877 currentInstance = responderInstance;
1878
1879 try {
1880 batchedEventUpdates(function () {
1881 onUnmount(eventResponderContext, props, state);
1882 });
1883 } finally {
1884 currentInstance = previousInstance;
1885 }
1886 }
1887
1888 var rootEventTypesSet = responderInstance.rootEventTypes;
1889
1890 if (rootEventTypesSet !== null) {
1891 var rootEventTypes = Array.from(rootEventTypesSet);
1892
1893 for (var i = 0; i < rootEventTypes.length; i++) {
1894 var topLevelEventType = rootEventTypes[i];
1895 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(topLevelEventType);
1896
1897 if (rootEventResponderInstances !== undefined) {
1898 rootEventResponderInstances.delete(responderInstance);
1899 }
1900 }
1901 }
1902}
1903
1904function validateResponderContext() {
1905 if (!(currentInstance !== null)) {
1906 {
1907 throw Error("An event responder context was used outside of an event cycle.");
1908 }
1909 }
1910}
1911
1912function dispatchEventForResponderEventSystem(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags) {
1913 if (enableFlareAPI) {
1914 var previousInstance = currentInstance;
1915 var previousTimeStamp = currentTimeStamp;
1916 var previousDocument = currentDocument;
1917 var previousPropagationBehavior = currentPropagationBehavior;
1918 currentPropagationBehavior = DoNotPropagateToNextResponder; // nodeType 9 is DOCUMENT_NODE
1919
1920 currentDocument = nativeEventTarget.nodeType === 9 ? nativeEventTarget : nativeEventTarget.ownerDocument; // We might want to control timeStamp another way here
1921
1922 currentTimeStamp = nativeEvent.timeStamp;
1923
1924 try {
1925 batchedEventUpdates(function () {
1926 traverseAndHandleEventResponderInstances(topLevelType, targetFiber, nativeEvent, nativeEventTarget, eventSystemFlags);
1927 });
1928 } finally {
1929 currentInstance = previousInstance;
1930 currentTimeStamp = previousTimeStamp;
1931 currentDocument = previousDocument;
1932 currentPropagationBehavior = previousPropagationBehavior;
1933 }
1934 }
1935}
1936function addRootEventTypesForResponderInstance(responderInstance, rootEventTypes) {
1937 for (var i = 0; i < rootEventTypes.length; i++) {
1938 var rootEventType = rootEventTypes[i];
1939 registerRootEventType(rootEventType, responderInstance);
1940 }
1941}
1942
1943function registerRootEventType(rootEventType, eventResponderInstance) {
1944 var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get(rootEventType);
1945
1946 if (rootEventResponderInstances === undefined) {
1947 rootEventResponderInstances = new Set();
1948 rootEventTypesToEventResponderInstances.set(rootEventType, rootEventResponderInstances);
1949 }
1950
1951 var rootEventTypesSet = eventResponderInstance.rootEventTypes;
1952
1953 if (rootEventTypesSet === null) {
1954 rootEventTypesSet = eventResponderInstance.rootEventTypes = new Set();
1955 }
1956
1957 if (!!rootEventTypesSet.has(rootEventType)) {
1958 {
1959 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.");
1960 }
1961 }
1962
1963 rootEventTypesSet.add(rootEventType);
1964 rootEventResponderInstances.add(eventResponderInstance);
1965}
1966
1967// A reserved attribute.
1968// It is handled by React separately and shouldn't be written to the DOM.
1969var RESERVED = 0; // A simple string attribute.
1970// Attributes that aren't in the whitelist are presumed to have this type.
1971
1972var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
1973// "enumerated" attributes with "true" and "false" as possible values.
1974// When true, it should be set to a "true" string.
1975// When false, it should be set to a "false" string.
1976
1977var BOOLEANISH_STRING = 2; // A real boolean attribute.
1978// When true, it should be present (set either to an empty string or its name).
1979// When false, it should be omitted.
1980
1981var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
1982// When true, it should be present (set either to an empty string or its name).
1983// When false, it should be omitted.
1984// For any other value, should be present with that value.
1985
1986var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
1987// When falsy, it should be removed.
1988
1989var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
1990// When falsy, it should be removed.
1991
1992var POSITIVE_NUMERIC = 6;
1993
1994/* eslint-disable max-len */
1995var 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";
1996/* eslint-enable max-len */
1997
1998var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
1999
2000var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
2001var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
2002var hasOwnProperty = Object.prototype.hasOwnProperty;
2003var illegalAttributeNameCache = {};
2004var validatedAttributeNameCache = {};
2005function isAttributeNameSafe(attributeName) {
2006 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
2007 return true;
2008 }
2009
2010 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
2011 return false;
2012 }
2013
2014 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
2015 validatedAttributeNameCache[attributeName] = true;
2016 return true;
2017 }
2018
2019 illegalAttributeNameCache[attributeName] = true;
2020
2021 {
2022 warning$1(false, 'Invalid attribute name: `%s`', attributeName);
2023 }
2024
2025 return false;
2026}
2027function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
2028 if (propertyInfo !== null) {
2029 return propertyInfo.type === RESERVED;
2030 }
2031
2032 if (isCustomComponentTag) {
2033 return false;
2034 }
2035
2036 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2037 return true;
2038 }
2039
2040 return false;
2041}
2042function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
2043 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
2044 return false;
2045 }
2046
2047 switch (typeof value) {
2048 case 'function': // $FlowIssue symbol is perfectly valid here
2049
2050 case 'symbol':
2051 // eslint-disable-line
2052 return true;
2053
2054 case 'boolean':
2055 {
2056 if (isCustomComponentTag) {
2057 return false;
2058 }
2059
2060 if (propertyInfo !== null) {
2061 return !propertyInfo.acceptsBooleans;
2062 } else {
2063 var prefix = name.toLowerCase().slice(0, 5);
2064 return prefix !== 'data-' && prefix !== 'aria-';
2065 }
2066 }
2067
2068 default:
2069 return false;
2070 }
2071}
2072function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
2073 if (value === null || typeof value === 'undefined') {
2074 return true;
2075 }
2076
2077 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
2078 return true;
2079 }
2080
2081 if (isCustomComponentTag) {
2082 return false;
2083 }
2084
2085 if (propertyInfo !== null) {
2086 switch (propertyInfo.type) {
2087 case BOOLEAN:
2088 return !value;
2089
2090 case OVERLOADED_BOOLEAN:
2091 return value === false;
2092
2093 case NUMERIC:
2094 return isNaN(value);
2095
2096 case POSITIVE_NUMERIC:
2097 return isNaN(value) || value < 1;
2098 }
2099 }
2100
2101 return false;
2102}
2103function getPropertyInfo(name) {
2104 return properties.hasOwnProperty(name) ? properties[name] : null;
2105}
2106
2107function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
2108 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
2109 this.attributeName = attributeName;
2110 this.attributeNamespace = attributeNamespace;
2111 this.mustUseProperty = mustUseProperty;
2112 this.propertyName = name;
2113 this.type = type;
2114 this.sanitizeURL = sanitizeURL;
2115} // When adding attributes to this list, be sure to also add them to
2116// the `possibleStandardNames` module to ensure casing and incorrect
2117// name warnings.
2118
2119
2120var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
2121
2122['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
2123// elements (not just inputs). Now that ReactDOMInput assigns to the
2124// defaultValue property -- do we need this?
2125'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'].forEach(function (name) {
2126 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
2127 name, // attributeName
2128 null, // attributeNamespace
2129 false);
2130}); // A few React string attributes have a different name.
2131// This is a mapping from React prop names to the attribute names.
2132
2133[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
2134 var name = _ref[0],
2135 attributeName = _ref[1];
2136 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2137 attributeName, // attributeName
2138 null, // attributeNamespace
2139 false);
2140}); // These are "enumerated" HTML attributes that accept "true" and "false".
2141// In React, we let users pass `true` and `false` even though technically
2142// these aren't boolean attributes (they are coerced to strings).
2143
2144['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
2145 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2146 name.toLowerCase(), // attributeName
2147 null, // attributeNamespace
2148 false);
2149}); // These are "enumerated" SVG attributes that accept "true" and "false".
2150// In React, we let users pass `true` and `false` even though technically
2151// these aren't boolean attributes (they are coerced to strings).
2152// Since these are SVG attributes, their attribute names are case-sensitive.
2153
2154['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
2155 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
2156 name, // attributeName
2157 null, // attributeNamespace
2158 false);
2159}); // These are HTML boolean attributes.
2160
2161['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
2162// on the client side because the browsers are inconsistent. Instead we call focus().
2163'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
2164'itemScope'].forEach(function (name) {
2165 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
2166 name.toLowerCase(), // attributeName
2167 null, // attributeNamespace
2168 false);
2169}); // These are the few React props that we set as DOM properties
2170// rather than attributes. These are all booleans.
2171
2172['checked', // Note: `option.selected` is not updated if `select.multiple` is
2173// disabled with `removeAttribute`. We have special logic for handling this.
2174'multiple', 'muted', 'selected'].forEach(function (name) {
2175 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
2176 name, // attributeName
2177 null, // attributeNamespace
2178 false);
2179}); // These are HTML attributes that are "overloaded booleans": they behave like
2180// booleans, but can also accept a string value.
2181
2182['capture', 'download'].forEach(function (name) {
2183 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
2184 name, // attributeName
2185 null, // attributeNamespace
2186 false);
2187}); // These are HTML attributes that must be positive numbers.
2188
2189['cols', 'rows', 'size', 'span'].forEach(function (name) {
2190 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
2191 name, // attributeName
2192 null, // attributeNamespace
2193 false);
2194}); // These are HTML attributes that must be numbers.
2195
2196['rowSpan', 'start'].forEach(function (name) {
2197 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
2198 name.toLowerCase(), // attributeName
2199 null, // attributeNamespace
2200 false);
2201});
2202var CAMELIZE = /[\-\:]([a-z])/g;
2203
2204var capitalize = function (token) {
2205 return token[1].toUpperCase();
2206}; // This is a list of all SVG attributes that need special casing, namespacing,
2207// or boolean value assignment. Regular attributes that just accept strings
2208// and have the same names are omitted, just like in the HTML whitelist.
2209// Some of these attributes can be hard to find. This list was created by
2210// scrapping the MDN documentation.
2211
2212
2213['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) {
2214 var name = attributeName.replace(CAMELIZE, capitalize);
2215 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2216 attributeName, null, // attributeNamespace
2217 false);
2218}); // String SVG attributes with the xlink namespace.
2219
2220['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type'].forEach(function (attributeName) {
2221 var name = attributeName.replace(CAMELIZE, capitalize);
2222 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2223 attributeName, 'http://www.w3.org/1999/xlink', false);
2224}); // String SVG attributes with the xml namespace.
2225
2226['xml:base', 'xml:lang', 'xml:space'].forEach(function (attributeName) {
2227 var name = attributeName.replace(CAMELIZE, capitalize);
2228 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
2229 attributeName, 'http://www.w3.org/XML/1998/namespace', false);
2230}); // These attribute exists both in HTML and SVG.
2231// The attribute name is case-sensitive in SVG so we can't just use
2232// the React name like we do for attributes that exist only in HTML.
2233
2234['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
2235 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2236 attributeName.toLowerCase(), // attributeName
2237 null, // attributeNamespace
2238 false);
2239}); // These attributes accept URLs. These must not allow javascript: URLS.
2240// These will also need to accept Trusted Types object in the future.
2241
2242var xlinkHref = 'xlinkHref';
2243properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
2244'xlink:href', 'http://www.w3.org/1999/xlink', true);
2245['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
2246 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
2247 attributeName.toLowerCase(), // attributeName
2248 null, // attributeNamespace
2249 true);
2250});
2251
2252var ReactDebugCurrentFrame$1 = null;
2253
2254{
2255 ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2256} // A javascript: URL can contain leading C0 control or \u0020 SPACE,
2257// and any newline or tab are filtered out as if they're not part of the URL.
2258// https://url.spec.whatwg.org/#url-parsing
2259// Tab or newline are defined as \r\n\t:
2260// https://infra.spec.whatwg.org/#ascii-tab-or-newline
2261// A C0 control is a code point in the range \u0000 NULL to \u001F
2262// INFORMATION SEPARATOR ONE, inclusive:
2263// https://infra.spec.whatwg.org/#c0-control-or-space
2264
2265/* eslint-disable max-len */
2266
2267
2268var 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;
2269var didWarn = false;
2270
2271function sanitizeURL(url) {
2272 if (disableJavaScriptURLs) {
2273 if (!!isJavaScriptProtocol.test(url)) {
2274 {
2275 throw Error("React has blocked a javascript: URL as a security precaution." + (ReactDebugCurrentFrame$1.getStackAddendum()));
2276 }
2277 }
2278 } else if (true && !didWarn && isJavaScriptProtocol.test(url)) {
2279 didWarn = true;
2280 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));
2281 }
2282}
2283
2284// Flow does not allow string concatenation of most non-string types. To work
2285// around this limitation, we use an opaque type that can only be obtained by
2286// passing the value through getToStringValue first.
2287function toString(value) {
2288 return '' + value;
2289}
2290function getToStringValue(value) {
2291 switch (typeof value) {
2292 case 'boolean':
2293 case 'number':
2294 case 'object':
2295 case 'string':
2296 case 'undefined':
2297 return value;
2298
2299 default:
2300 // function, symbol are assigned as empty strings
2301 return '';
2302 }
2303}
2304/** Trusted value is a wrapper for "safe" values which can be assigned to DOM execution sinks. */
2305
2306/**
2307 * We allow passing objects with toString method as element attributes or in dangerouslySetInnerHTML
2308 * and we do validations that the value is safe. Once we do validation we want to use the validated
2309 * value instead of the object (because object.toString may return something else on next call).
2310 *
2311 * If application uses Trusted Types we don't stringify trusted values, but preserve them as objects.
2312 */
2313var toStringOrTrustedType = toString;
2314
2315if (enableTrustedTypesIntegration && typeof trustedTypes !== 'undefined') {
2316 toStringOrTrustedType = function (value) {
2317 if (typeof value === 'object' && (trustedTypes.isHTML(value) || trustedTypes.isScript(value) || trustedTypes.isScriptURL(value) ||
2318 /* TrustedURLs are deprecated and will be removed soon: https://github.com/WICG/trusted-types/pull/204 */
2319 trustedTypes.isURL && trustedTypes.isURL(value))) {
2320 // Pass Trusted Types through.
2321 return value;
2322 }
2323
2324 return toString(value);
2325 };
2326}
2327
2328/**
2329 * Set attribute for a node. The attribute value can be either string or
2330 * Trusted value (if application uses Trusted Types).
2331 */
2332function setAttribute(node, attributeName, attributeValue) {
2333 node.setAttribute(attributeName, attributeValue);
2334}
2335/**
2336 * Set attribute with namespace for a node. The attribute value can be either string or
2337 * Trusted value (if application uses Trusted Types).
2338 */
2339
2340function setAttributeNS(node, attributeNamespace, attributeName, attributeValue) {
2341 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
2342}
2343
2344/**
2345 * Get the value for a property on a node. Only used in DEV for SSR validation.
2346 * The "expected" argument is used as a hint of what the expected value is.
2347 * Some properties have multiple equivalent values.
2348 */
2349function getValueForProperty(node, name, expected, propertyInfo) {
2350 {
2351 if (propertyInfo.mustUseProperty) {
2352 var propertyName = propertyInfo.propertyName;
2353 return node[propertyName];
2354 } else {
2355 if (!disableJavaScriptURLs && propertyInfo.sanitizeURL) {
2356 // If we haven't fully disabled javascript: URLs, and if
2357 // the hydration is successful of a javascript: URL, we
2358 // still want to warn on the client.
2359 sanitizeURL('' + expected);
2360 }
2361
2362 var attributeName = propertyInfo.attributeName;
2363 var stringValue = null;
2364
2365 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
2366 if (node.hasAttribute(attributeName)) {
2367 var value = node.getAttribute(attributeName);
2368
2369 if (value === '') {
2370 return true;
2371 }
2372
2373 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2374 return value;
2375 }
2376
2377 if (value === '' + expected) {
2378 return expected;
2379 }
2380
2381 return value;
2382 }
2383 } else if (node.hasAttribute(attributeName)) {
2384 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2385 // We had an attribute but shouldn't have had one, so read it
2386 // for the error message.
2387 return node.getAttribute(attributeName);
2388 }
2389
2390 if (propertyInfo.type === BOOLEAN) {
2391 // If this was a boolean, it doesn't matter what the value is
2392 // the fact that we have it is the same as the expected.
2393 return expected;
2394 } // Even if this property uses a namespace we use getAttribute
2395 // because we assume its namespaced name is the same as our config.
2396 // To use getAttributeNS we need the local name which we don't have
2397 // in our config atm.
2398
2399
2400 stringValue = node.getAttribute(attributeName);
2401 }
2402
2403 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
2404 return stringValue === null ? expected : stringValue;
2405 } else if (stringValue === '' + expected) {
2406 return expected;
2407 } else {
2408 return stringValue;
2409 }
2410 }
2411 }
2412}
2413/**
2414 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
2415 * The third argument is used as a hint of what the expected value is. Some
2416 * attributes have multiple equivalent values.
2417 */
2418
2419function getValueForAttribute(node, name, expected) {
2420 {
2421 if (!isAttributeNameSafe(name)) {
2422 return;
2423 }
2424
2425 if (!node.hasAttribute(name)) {
2426 return expected === undefined ? undefined : null;
2427 }
2428
2429 var value = node.getAttribute(name);
2430
2431 if (value === '' + expected) {
2432 return expected;
2433 }
2434
2435 return value;
2436 }
2437}
2438/**
2439 * Sets the value for a property on a node.
2440 *
2441 * @param {DOMElement} node
2442 * @param {string} name
2443 * @param {*} value
2444 */
2445
2446function setValueForProperty(node, name, value, isCustomComponentTag) {
2447 var propertyInfo = getPropertyInfo(name);
2448
2449 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
2450 return;
2451 }
2452
2453 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
2454 value = null;
2455 } // If the prop isn't in the special list, treat it as a simple attribute.
2456
2457
2458 if (isCustomComponentTag || propertyInfo === null) {
2459 if (isAttributeNameSafe(name)) {
2460 var _attributeName = name;
2461
2462 if (value === null) {
2463 node.removeAttribute(_attributeName);
2464 } else {
2465 setAttribute(node, _attributeName, toStringOrTrustedType(value));
2466 }
2467 }
2468
2469 return;
2470 }
2471
2472 var mustUseProperty = propertyInfo.mustUseProperty;
2473
2474 if (mustUseProperty) {
2475 var propertyName = propertyInfo.propertyName;
2476
2477 if (value === null) {
2478 var type = propertyInfo.type;
2479 node[propertyName] = type === BOOLEAN ? false : '';
2480 } else {
2481 // Contrary to `setAttribute`, object properties are properly
2482 // `toString`ed by IE8/9.
2483 node[propertyName] = value;
2484 }
2485
2486 return;
2487 } // The rest are treated as attributes with special cases.
2488
2489
2490 var attributeName = propertyInfo.attributeName,
2491 attributeNamespace = propertyInfo.attributeNamespace;
2492
2493 if (value === null) {
2494 node.removeAttribute(attributeName);
2495 } else {
2496 var _type = propertyInfo.type;
2497 var attributeValue;
2498
2499 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
2500 // If attribute type is boolean, we know for sure it won't be an execution sink
2501 // and we won't require Trusted Type here.
2502 attributeValue = '';
2503 } else {
2504 // `setAttribute` with objects becomes only `[object]` in IE8/9,
2505 // ('' + value) makes it output the correct toString()-value.
2506 attributeValue = toStringOrTrustedType(value);
2507
2508 if (propertyInfo.sanitizeURL) {
2509 sanitizeURL(attributeValue.toString());
2510 }
2511 }
2512
2513 if (attributeNamespace) {
2514 setAttributeNS(node, attributeNamespace, attributeName, attributeValue);
2515 } else {
2516 setAttribute(node, attributeName, attributeValue);
2517 }
2518 }
2519}
2520
2521/**
2522 * Copyright (c) 2013-present, Facebook, Inc.
2523 *
2524 * This source code is licensed under the MIT license found in the
2525 * LICENSE file in the root directory of this source tree.
2526 */
2527
2528
2529
2530var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
2531
2532var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
2533
2534/**
2535 * Copyright (c) 2013-present, Facebook, Inc.
2536 *
2537 * This source code is licensed under the MIT license found in the
2538 * LICENSE file in the root directory of this source tree.
2539 */
2540
2541
2542
2543var printWarning = function() {};
2544
2545{
2546 var ReactPropTypesSecret = ReactPropTypesSecret_1;
2547 var loggedTypeFailures = {};
2548 var has = Function.call.bind(Object.prototype.hasOwnProperty);
2549
2550 printWarning = function(text) {
2551 var message = 'Warning: ' + text;
2552 if (typeof console !== 'undefined') {
2553 console.error(message);
2554 }
2555 try {
2556 // --- Welcome to debugging React ---
2557 // This error was thrown as a convenience so that you can use this stack
2558 // to find the callsite that caused this warning to fire.
2559 throw new Error(message);
2560 } catch (x) {}
2561 };
2562}
2563
2564/**
2565 * Assert that the values match with the type specs.
2566 * Error messages are memorized and will only be shown once.
2567 *
2568 * @param {object} typeSpecs Map of name to a ReactPropType
2569 * @param {object} values Runtime values that need to be type-checked
2570 * @param {string} location e.g. "prop", "context", "child context"
2571 * @param {string} componentName Name of the component for error messages.
2572 * @param {?Function} getStack Returns the component stack.
2573 * @private
2574 */
2575function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
2576 {
2577 for (var typeSpecName in typeSpecs) {
2578 if (has(typeSpecs, typeSpecName)) {
2579 var error;
2580 // Prop type validation may throw. In case they do, we don't want to
2581 // fail the render phase where it didn't fail before. So we log it.
2582 // After these have been cleaned up, we'll let them throw.
2583 try {
2584 // This is intentionally an invariant that gets caught. It's the same
2585 // behavior as without this statement except with a better message.
2586 if (typeof typeSpecs[typeSpecName] !== 'function') {
2587 var err = Error(
2588 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
2589 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
2590 );
2591 err.name = 'Invariant Violation';
2592 throw err;
2593 }
2594 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
2595 } catch (ex) {
2596 error = ex;
2597 }
2598 if (error && !(error instanceof Error)) {
2599 printWarning(
2600 (componentName || 'React class') + ': type specification of ' +
2601 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
2602 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
2603 'You may have forgotten to pass an argument to the type checker ' +
2604 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
2605 'shape all require an argument).'
2606 );
2607 }
2608 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
2609 // Only monitor this failure once because there tends to be a lot of the
2610 // same error.
2611 loggedTypeFailures[error.message] = true;
2612
2613 var stack = getStack ? getStack() : '';
2614
2615 printWarning(
2616 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
2617 );
2618 }
2619 }
2620 }
2621 }
2622}
2623
2624/**
2625 * Resets warning cache when testing.
2626 *
2627 * @private
2628 */
2629checkPropTypes.resetWarningCache = function() {
2630 {
2631 loggedTypeFailures = {};
2632 }
2633};
2634
2635var checkPropTypes_1 = checkPropTypes;
2636
2637var ReactDebugCurrentFrame$2 = null;
2638var ReactControlledValuePropTypes = {
2639 checkPropTypes: null
2640};
2641
2642{
2643 ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
2644 var hasReadOnlyValue = {
2645 button: true,
2646 checkbox: true,
2647 image: true,
2648 hidden: true,
2649 radio: true,
2650 reset: true,
2651 submit: true
2652 };
2653 var propTypes = {
2654 value: function (props, propName, componentName) {
2655 if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2656 return null;
2657 }
2658
2659 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`.');
2660 },
2661 checked: function (props, propName, componentName) {
2662 if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableFlareAPI && props.listeners) {
2663 return null;
2664 }
2665
2666 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`.');
2667 }
2668 };
2669 /**
2670 * Provide a linked `value` attribute for controlled forms. You should not use
2671 * this outside of the ReactDOM controlled form components.
2672 */
2673
2674 ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
2675 checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
2676 };
2677}
2678
2679function isCheckable(elem) {
2680 var type = elem.type;
2681 var nodeName = elem.nodeName;
2682 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
2683}
2684
2685function getTracker(node) {
2686 return node._valueTracker;
2687}
2688
2689function detachTracker(node) {
2690 node._valueTracker = null;
2691}
2692
2693function getValueFromNode(node) {
2694 var value = '';
2695
2696 if (!node) {
2697 return value;
2698 }
2699
2700 if (isCheckable(node)) {
2701 value = node.checked ? 'true' : 'false';
2702 } else {
2703 value = node.value;
2704 }
2705
2706 return value;
2707}
2708
2709function trackValueOnNode(node) {
2710 var valueField = isCheckable(node) ? 'checked' : 'value';
2711 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
2712 var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
2713 // and don't track value will cause over reporting of changes,
2714 // but it's better then a hard failure
2715 // (needed for certain tests that spyOn input values and Safari)
2716
2717 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
2718 return;
2719 }
2720
2721 var get = descriptor.get,
2722 set = descriptor.set;
2723 Object.defineProperty(node, valueField, {
2724 configurable: true,
2725 get: function () {
2726 return get.call(this);
2727 },
2728 set: function (value) {
2729 currentValue = '' + value;
2730 set.call(this, value);
2731 }
2732 }); // We could've passed this the first time
2733 // but it triggers a bug in IE11 and Edge 14/15.
2734 // Calling defineProperty() again should be equivalent.
2735 // https://github.com/facebook/react/issues/11768
2736
2737 Object.defineProperty(node, valueField, {
2738 enumerable: descriptor.enumerable
2739 });
2740 var tracker = {
2741 getValue: function () {
2742 return currentValue;
2743 },
2744 setValue: function (value) {
2745 currentValue = '' + value;
2746 },
2747 stopTracking: function () {
2748 detachTracker(node);
2749 delete node[valueField];
2750 }
2751 };
2752 return tracker;
2753}
2754
2755function track(node) {
2756 if (getTracker(node)) {
2757 return;
2758 } // TODO: Once it's just Fiber we can move this to node._wrapperState
2759
2760
2761 node._valueTracker = trackValueOnNode(node);
2762}
2763function updateValueIfChanged(node) {
2764 if (!node) {
2765 return false;
2766 }
2767
2768 var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
2769 // that trying again will succeed
2770
2771 if (!tracker) {
2772 return true;
2773 }
2774
2775 var lastValue = tracker.getValue();
2776 var nextValue = getValueFromNode(node);
2777
2778 if (nextValue !== lastValue) {
2779 tracker.setValue(nextValue);
2780 return true;
2781 }
2782
2783 return false;
2784}
2785
2786// TODO: direct imports like some-package/src/* are bad. Fix me.
2787var didWarnValueDefaultValue = false;
2788var didWarnCheckedDefaultChecked = false;
2789var didWarnControlledToUncontrolled = false;
2790var didWarnUncontrolledToControlled = false;
2791
2792function isControlled(props) {
2793 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
2794 return usesChecked ? props.checked != null : props.value != null;
2795}
2796/**
2797 * Implements an <input> host component that allows setting these optional
2798 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
2799 *
2800 * If `checked` or `value` are not supplied (or null/undefined), user actions
2801 * that affect the checked state or value will trigger updates to the element.
2802 *
2803 * If they are supplied (and not null/undefined), the rendered element will not
2804 * trigger updates to the element. Instead, the props must change in order for
2805 * the rendered element to be updated.
2806 *
2807 * The rendered element will be initialized as unchecked (or `defaultChecked`)
2808 * with an empty value (or `defaultValue`).
2809 *
2810 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
2811 */
2812
2813
2814function getHostProps(element, props) {
2815 var node = element;
2816 var checked = props.checked;
2817
2818 var hostProps = _assign({}, props, {
2819 defaultChecked: undefined,
2820 defaultValue: undefined,
2821 value: undefined,
2822 checked: checked != null ? checked : node._wrapperState.initialChecked
2823 });
2824
2825 return hostProps;
2826}
2827function initWrapperState(element, props) {
2828 {
2829 ReactControlledValuePropTypes.checkPropTypes('input', props);
2830
2831 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
2832 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);
2833 didWarnCheckedDefaultChecked = true;
2834 }
2835
2836 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
2837 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);
2838 didWarnValueDefaultValue = true;
2839 }
2840 }
2841
2842 var node = element;
2843 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
2844 node._wrapperState = {
2845 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
2846 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
2847 controlled: isControlled(props)
2848 };
2849}
2850function updateChecked(element, props) {
2851 var node = element;
2852 var checked = props.checked;
2853
2854 if (checked != null) {
2855 setValueForProperty(node, 'checked', checked, false);
2856 }
2857}
2858function updateWrapper(element, props) {
2859 var node = element;
2860
2861 {
2862 var controlled = isControlled(props);
2863
2864 if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
2865 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);
2866 didWarnUncontrolledToControlled = true;
2867 }
2868
2869 if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
2870 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);
2871 didWarnControlledToUncontrolled = true;
2872 }
2873 }
2874
2875 updateChecked(element, props);
2876 var value = getToStringValue(props.value);
2877 var type = props.type;
2878
2879 if (value != null) {
2880 if (type === 'number') {
2881 if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
2882 // eslint-disable-next-line
2883 node.value != value) {
2884 node.value = toString(value);
2885 }
2886 } else if (node.value !== toString(value)) {
2887 node.value = toString(value);
2888 }
2889 } else if (type === 'submit' || type === 'reset') {
2890 // Submit/reset inputs need the attribute removed completely to avoid
2891 // blank-text buttons.
2892 node.removeAttribute('value');
2893 return;
2894 }
2895
2896 if (disableInputAttributeSyncing) {
2897 // When not syncing the value attribute, React only assigns a new value
2898 // whenever the defaultValue React prop has changed. When not present,
2899 // React does nothing
2900 if (props.hasOwnProperty('defaultValue')) {
2901 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2902 }
2903 } else {
2904 // When syncing the value attribute, the value comes from a cascade of
2905 // properties:
2906 // 1. The value React property
2907 // 2. The defaultValue React property
2908 // 3. Otherwise there should be no change
2909 if (props.hasOwnProperty('value')) {
2910 setDefaultValue(node, props.type, value);
2911 } else if (props.hasOwnProperty('defaultValue')) {
2912 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
2913 }
2914 }
2915
2916 if (disableInputAttributeSyncing) {
2917 // When not syncing the checked attribute, the attribute is directly
2918 // controllable from the defaultValue React property. It needs to be
2919 // updated as new props come in.
2920 if (props.defaultChecked == null) {
2921 node.removeAttribute('checked');
2922 } else {
2923 node.defaultChecked = !!props.defaultChecked;
2924 }
2925 } else {
2926 // When syncing the checked attribute, it only changes when it needs
2927 // to be removed, such as transitioning from a checkbox into a text input
2928 if (props.checked == null && props.defaultChecked != null) {
2929 node.defaultChecked = !!props.defaultChecked;
2930 }
2931 }
2932}
2933function postMountWrapper(element, props, isHydrating) {
2934 var node = element; // Do not assign value if it is already set. This prevents user text input
2935 // from being lost during SSR hydration.
2936
2937 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
2938 var type = props.type;
2939 var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
2940 // default value provided by the browser. See: #12872
2941
2942 if (isButton && (props.value === undefined || props.value === null)) {
2943 return;
2944 }
2945
2946 var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
2947 // from being lost during SSR hydration.
2948
2949 if (!isHydrating) {
2950 if (disableInputAttributeSyncing) {
2951 var value = getToStringValue(props.value); // When not syncing the value attribute, the value property points
2952 // directly to the React prop. Only assign it if it exists.
2953
2954 if (value != null) {
2955 // Always assign on buttons so that it is possible to assign an
2956 // empty string to clear button text.
2957 //
2958 // Otherwise, do not re-assign the value property if is empty. This
2959 // potentially avoids a DOM write and prevents Firefox (~60.0.1) from
2960 // prematurely marking required inputs as invalid. Equality is compared
2961 // to the current value in case the browser provided value is not an
2962 // empty string.
2963 if (isButton || value !== node.value) {
2964 node.value = toString(value);
2965 }
2966 }
2967 } else {
2968 // When syncing the value attribute, the value property should use
2969 // the wrapperState._initialValue property. This uses:
2970 //
2971 // 1. The value React property when present
2972 // 2. The defaultValue React property when present
2973 // 3. An empty string
2974 if (initialValue !== node.value) {
2975 node.value = initialValue;
2976 }
2977 }
2978 }
2979
2980 if (disableInputAttributeSyncing) {
2981 // When not syncing the value attribute, assign the value attribute
2982 // directly from the defaultValue React property (when present)
2983 var defaultValue = getToStringValue(props.defaultValue);
2984
2985 if (defaultValue != null) {
2986 node.defaultValue = toString(defaultValue);
2987 }
2988 } else {
2989 // Otherwise, the value attribute is synchronized to the property,
2990 // so we assign defaultValue to the same thing as the value property
2991 // assignment step above.
2992 node.defaultValue = initialValue;
2993 }
2994 } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
2995 // this is needed to work around a chrome bug where setting defaultChecked
2996 // will sometimes influence the value of checked (even after detachment).
2997 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
2998 // We need to temporarily unset name to avoid disrupting radio button groups.
2999
3000
3001 var name = node.name;
3002
3003 if (name !== '') {
3004 node.name = '';
3005 }
3006
3007 if (disableInputAttributeSyncing) {
3008 // When not syncing the checked attribute, the checked property
3009 // never gets assigned. It must be manually set. We don't want
3010 // to do this when hydrating so that existing user input isn't
3011 // modified
3012 if (!isHydrating) {
3013 updateChecked(element, props);
3014 } // Only assign the checked attribute if it is defined. This saves
3015 // a DOM write when controlling the checked attribute isn't needed
3016 // (text inputs, submit/reset)
3017
3018
3019 if (props.hasOwnProperty('defaultChecked')) {
3020 node.defaultChecked = !node.defaultChecked;
3021 node.defaultChecked = !!props.defaultChecked;
3022 }
3023 } else {
3024 // When syncing the checked attribute, both the checked property and
3025 // attribute are assigned at the same time using defaultChecked. This uses:
3026 //
3027 // 1. The checked React property when present
3028 // 2. The defaultChecked React property when present
3029 // 3. Otherwise, false
3030 node.defaultChecked = !node.defaultChecked;
3031 node.defaultChecked = !!node._wrapperState.initialChecked;
3032 }
3033
3034 if (name !== '') {
3035 node.name = name;
3036 }
3037}
3038function restoreControlledState$1(element, props) {
3039 var node = element;
3040 updateWrapper(node, props);
3041 updateNamedCousins(node, props);
3042}
3043
3044function updateNamedCousins(rootNode, props) {
3045 var name = props.name;
3046
3047 if (props.type === 'radio' && name != null) {
3048 var queryRoot = rootNode;
3049
3050 while (queryRoot.parentNode) {
3051 queryRoot = queryRoot.parentNode;
3052 } // If `rootNode.form` was non-null, then we could try `form.elements`,
3053 // but that sometimes behaves strangely in IE8. We could also try using
3054 // `form.getElementsByName`, but that will only return direct children
3055 // and won't include inputs that use the HTML5 `form=` attribute. Since
3056 // the input might not even be in a form. It might not even be in the
3057 // document. Let's just use the local `querySelectorAll` to ensure we don't
3058 // miss anything.
3059
3060
3061 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
3062
3063 for (var i = 0; i < group.length; i++) {
3064 var otherNode = group[i];
3065
3066 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
3067 continue;
3068 } // This will throw if radio buttons rendered by different copies of React
3069 // and the same name are rendered into the same form (same as #1939).
3070 // That's probably okay; we don't support it just as we don't support
3071 // mixing React radio buttons with non-React ones.
3072
3073
3074 var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
3075
3076 if (!otherProps) {
3077 {
3078 throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
3079 }
3080 } // We need update the tracked value on the named cousin since the value
3081 // was changed but the input saw no event or value set
3082
3083
3084 updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
3085 // was previously checked to update will cause it to be come re-checked
3086 // as appropriate.
3087
3088 updateWrapper(otherNode, otherProps);
3089 }
3090 }
3091} // In Chrome, assigning defaultValue to certain input types triggers input validation.
3092// For number inputs, the display value loses trailing decimal points. For email inputs,
3093// Chrome raises "The specified value <x> is not a valid email address".
3094//
3095// Here we check to see if the defaultValue has actually changed, avoiding these problems
3096// when the user is inputting text
3097//
3098// https://github.com/facebook/react/issues/7253
3099
3100
3101function setDefaultValue(node, type, value) {
3102 if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
3103 type !== 'number' || node.ownerDocument.activeElement !== node) {
3104 if (value == null) {
3105 node.defaultValue = toString(node._wrapperState.initialValue);
3106 } else if (node.defaultValue !== toString(value)) {
3107 node.defaultValue = toString(value);
3108 }
3109 }
3110}
3111
3112var didWarnSelectedSetOnOption = false;
3113var didWarnInvalidChild = false;
3114
3115function flattenChildren(children) {
3116 var content = ''; // Flatten children. We'll warn if they are invalid
3117 // during validateProps() which runs for hydration too.
3118 // Note that this would throw on non-element objects.
3119 // Elements are stringified (which is normally irrelevant
3120 // but matters for <fbt>).
3121
3122 React.Children.forEach(children, function (child) {
3123 if (child == null) {
3124 return;
3125 }
3126
3127 content += child; // Note: we don't warn about invalid children here.
3128 // Instead, this is done separately below so that
3129 // it happens during the hydration codepath too.
3130 });
3131 return content;
3132}
3133/**
3134 * Implements an <option> host component that warns when `selected` is set.
3135 */
3136
3137
3138function validateProps(element, props) {
3139 {
3140 // This mirrors the codepath above, but runs for hydration too.
3141 // Warn about invalid children here so that client and hydration are consistent.
3142 // TODO: this seems like it could cause a DEV-only throw for hydration
3143 // if children contains a non-element object. We should try to avoid that.
3144 if (typeof props.children === 'object' && props.children !== null) {
3145 React.Children.forEach(props.children, function (child) {
3146 if (child == null) {
3147 return;
3148 }
3149
3150 if (typeof child === 'string' || typeof child === 'number') {
3151 return;
3152 }
3153
3154 if (typeof child.type !== 'string') {
3155 return;
3156 }
3157
3158 if (!didWarnInvalidChild) {
3159 didWarnInvalidChild = true;
3160 warning$1(false, 'Only strings and numbers are supported as <option> children.');
3161 }
3162 });
3163 } // TODO: Remove support for `selected` in <option>.
3164
3165
3166 if (props.selected != null && !didWarnSelectedSetOnOption) {
3167 warning$1(false, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
3168 didWarnSelectedSetOnOption = true;
3169 }
3170 }
3171}
3172function postMountWrapper$1(element, props) {
3173 // value="" should make a value attribute (#6219)
3174 if (props.value != null) {
3175 element.setAttribute('value', toString(getToStringValue(props.value)));
3176 }
3177}
3178function getHostProps$1(element, props) {
3179 var hostProps = _assign({
3180 children: undefined
3181 }, props);
3182
3183 var content = flattenChildren(props.children);
3184
3185 if (content) {
3186 hostProps.children = content;
3187 }
3188
3189 return hostProps;
3190}
3191
3192// TODO: direct imports like some-package/src/* are bad. Fix me.
3193var didWarnValueDefaultValue$1;
3194
3195{
3196 didWarnValueDefaultValue$1 = false;
3197}
3198
3199function getDeclarationErrorAddendum() {
3200 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
3201
3202 if (ownerName) {
3203 return '\n\nCheck the render method of `' + ownerName + '`.';
3204 }
3205
3206 return '';
3207}
3208
3209var valuePropNames = ['value', 'defaultValue'];
3210/**
3211 * Validation function for `value` and `defaultValue`.
3212 */
3213
3214function checkSelectPropTypes(props) {
3215 ReactControlledValuePropTypes.checkPropTypes('select', props);
3216
3217 for (var i = 0; i < valuePropNames.length; i++) {
3218 var propName = valuePropNames[i];
3219
3220 if (props[propName] == null) {
3221 continue;
3222 }
3223
3224 var isArray = Array.isArray(props[propName]);
3225
3226 if (props.multiple && !isArray) {
3227 warning$1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
3228 } else if (!props.multiple && isArray) {
3229 warning$1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
3230 }
3231 }
3232}
3233
3234function updateOptions(node, multiple, propValue, setDefaultSelected) {
3235 var options = node.options;
3236
3237 if (multiple) {
3238 var selectedValues = propValue;
3239 var selectedValue = {};
3240
3241 for (var i = 0; i < selectedValues.length; i++) {
3242 // Prefix to avoid chaos with special keys.
3243 selectedValue['$' + selectedValues[i]] = true;
3244 }
3245
3246 for (var _i = 0; _i < options.length; _i++) {
3247 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
3248
3249 if (options[_i].selected !== selected) {
3250 options[_i].selected = selected;
3251 }
3252
3253 if (selected && setDefaultSelected) {
3254 options[_i].defaultSelected = true;
3255 }
3256 }
3257 } else {
3258 // Do not set `select.value` as exact behavior isn't consistent across all
3259 // browsers for all cases.
3260 var _selectedValue = toString(getToStringValue(propValue));
3261
3262 var defaultSelected = null;
3263
3264 for (var _i2 = 0; _i2 < options.length; _i2++) {
3265 if (options[_i2].value === _selectedValue) {
3266 options[_i2].selected = true;
3267
3268 if (setDefaultSelected) {
3269 options[_i2].defaultSelected = true;
3270 }
3271
3272 return;
3273 }
3274
3275 if (defaultSelected === null && !options[_i2].disabled) {
3276 defaultSelected = options[_i2];
3277 }
3278 }
3279
3280 if (defaultSelected !== null) {
3281 defaultSelected.selected = true;
3282 }
3283 }
3284}
3285/**
3286 * Implements a <select> host component that allows optionally setting the
3287 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
3288 * stringable. If `multiple` is true, the prop must be an array of stringables.
3289 *
3290 * If `value` is not supplied (or null/undefined), user actions that change the
3291 * selected option will trigger updates to the rendered options.
3292 *
3293 * If it is supplied (and not null/undefined), the rendered options will not
3294 * update in response to user actions. Instead, the `value` prop must change in
3295 * order for the rendered options to update.
3296 *
3297 * If `defaultValue` is provided, any options with the supplied values will be
3298 * selected.
3299 */
3300
3301
3302function getHostProps$2(element, props) {
3303 return _assign({}, props, {
3304 value: undefined
3305 });
3306}
3307function initWrapperState$1(element, props) {
3308 var node = element;
3309
3310 {
3311 checkSelectPropTypes(props);
3312 }
3313
3314 node._wrapperState = {
3315 wasMultiple: !!props.multiple
3316 };
3317
3318 {
3319 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
3320 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');
3321 didWarnValueDefaultValue$1 = true;
3322 }
3323 }
3324}
3325function postMountWrapper$2(element, props) {
3326 var node = element;
3327 node.multiple = !!props.multiple;
3328 var value = props.value;
3329
3330 if (value != null) {
3331 updateOptions(node, !!props.multiple, value, false);
3332 } else if (props.defaultValue != null) {
3333 updateOptions(node, !!props.multiple, props.defaultValue, true);
3334 }
3335}
3336function postUpdateWrapper(element, props) {
3337 var node = element;
3338 var wasMultiple = node._wrapperState.wasMultiple;
3339 node._wrapperState.wasMultiple = !!props.multiple;
3340 var value = props.value;
3341
3342 if (value != null) {
3343 updateOptions(node, !!props.multiple, value, false);
3344 } else if (wasMultiple !== !!props.multiple) {
3345 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
3346 if (props.defaultValue != null) {
3347 updateOptions(node, !!props.multiple, props.defaultValue, true);
3348 } else {
3349 // Revert the select back to its default unselected state.
3350 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
3351 }
3352 }
3353}
3354function restoreControlledState$2(element, props) {
3355 var node = element;
3356 var value = props.value;
3357
3358 if (value != null) {
3359 updateOptions(node, !!props.multiple, value, false);
3360 }
3361}
3362
3363var didWarnValDefaultVal = false;
3364
3365/**
3366 * Implements a <textarea> host component that allows setting `value`, and
3367 * `defaultValue`. This differs from the traditional DOM API because value is
3368 * usually set as PCDATA children.
3369 *
3370 * If `value` is not supplied (or null/undefined), user actions that affect the
3371 * value will trigger updates to the element.
3372 *
3373 * If `value` is supplied (and not null/undefined), the rendered element will
3374 * not trigger updates to the element. Instead, the `value` prop must change in
3375 * order for the rendered element to be updated.
3376 *
3377 * The rendered element will be initialized with an empty value, the prop
3378 * `defaultValue` if specified, or the children content (deprecated).
3379 */
3380function getHostProps$3(element, props) {
3381 var node = element;
3382
3383 if (!(props.dangerouslySetInnerHTML == null)) {
3384 {
3385 throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
3386 }
3387 } // Always set children to the same thing. In IE9, the selection range will
3388 // get reset if `textContent` is mutated. We could add a check in setTextContent
3389 // to only set the value if/when the value differs from the node value (which would
3390 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
3391 // solution. The value can be a boolean or object so that's why it's forced
3392 // to be a string.
3393
3394
3395 var hostProps = _assign({}, props, {
3396 value: undefined,
3397 defaultValue: undefined,
3398 children: toString(node._wrapperState.initialValue)
3399 });
3400
3401 return hostProps;
3402}
3403function initWrapperState$2(element, props) {
3404 var node = element;
3405
3406 {
3407 ReactControlledValuePropTypes.checkPropTypes('textarea', props);
3408
3409 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
3410 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');
3411 didWarnValDefaultVal = true;
3412 }
3413 }
3414
3415 var initialValue = props.value; // Only bother fetching default value if we're going to use it
3416
3417 if (initialValue == null) {
3418 var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>.
3419
3420 var children = props.children;
3421
3422 if (children != null) {
3423 {
3424 warning$1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
3425 }
3426
3427 if (!(defaultValue == null)) {
3428 {
3429 throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
3430 }
3431 }
3432
3433 if (Array.isArray(children)) {
3434 if (!(children.length <= 1)) {
3435 {
3436 throw Error("<textarea> can only have at most one child.");
3437 }
3438 }
3439
3440 children = children[0];
3441 }
3442
3443 defaultValue = children;
3444 }
3445
3446 if (defaultValue == null) {
3447 defaultValue = '';
3448 }
3449
3450 initialValue = defaultValue;
3451 }
3452
3453 node._wrapperState = {
3454 initialValue: getToStringValue(initialValue)
3455 };
3456}
3457function updateWrapper$1(element, props) {
3458 var node = element;
3459 var value = getToStringValue(props.value);
3460 var defaultValue = getToStringValue(props.defaultValue);
3461
3462 if (value != null) {
3463 // Cast `value` to a string to ensure the value is set correctly. While
3464 // browsers typically do this as necessary, jsdom doesn't.
3465 var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
3466
3467 if (newValue !== node.value) {
3468 node.value = newValue;
3469 }
3470
3471 if (props.defaultValue == null && node.defaultValue !== newValue) {
3472 node.defaultValue = newValue;
3473 }
3474 }
3475
3476 if (defaultValue != null) {
3477 node.defaultValue = toString(defaultValue);
3478 }
3479}
3480function postMountWrapper$3(element, props) {
3481 var node = element; // This is in postMount because we need access to the DOM node, which is not
3482 // available until after the component has mounted.
3483
3484 var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
3485 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
3486 // will populate textContent as well.
3487 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
3488
3489 if (textContent === node._wrapperState.initialValue) {
3490 if (textContent !== '' && textContent !== null) {
3491 node.value = textContent;
3492 }
3493 }
3494}
3495function restoreControlledState$3(element, props) {
3496 // DOM component is still mounted; update
3497 updateWrapper$1(element, props);
3498}
3499
3500var HTML_NAMESPACE$1 = 'http://www.w3.org/1999/xhtml';
3501var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
3502var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
3503var Namespaces = {
3504 html: HTML_NAMESPACE$1,
3505 mathml: MATH_NAMESPACE,
3506 svg: SVG_NAMESPACE
3507}; // Assumes there is no parent namespace.
3508
3509function getIntrinsicNamespace(type) {
3510 switch (type) {
3511 case 'svg':
3512 return SVG_NAMESPACE;
3513
3514 case 'math':
3515 return MATH_NAMESPACE;
3516
3517 default:
3518 return HTML_NAMESPACE$1;
3519 }
3520}
3521function getChildNamespace(parentNamespace, type) {
3522 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE$1) {
3523 // No (or default) parent namespace: potential entry point.
3524 return getIntrinsicNamespace(type);
3525 }
3526
3527 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
3528 // We're leaving SVG.
3529 return HTML_NAMESPACE$1;
3530 } // By default, pass namespace below.
3531
3532
3533 return parentNamespace;
3534}
3535
3536/* globals MSApp */
3537
3538/**
3539 * Create a function which has 'unsafe' privileges (required by windows8 apps)
3540 */
3541var createMicrosoftUnsafeLocalFunction = function (func) {
3542 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
3543 return function (arg0, arg1, arg2, arg3) {
3544 MSApp.execUnsafeLocalFunction(function () {
3545 return func(arg0, arg1, arg2, arg3);
3546 });
3547 };
3548 } else {
3549 return func;
3550 }
3551};
3552
3553var reusableSVGContainer;
3554/**
3555 * Set the innerHTML property of a node
3556 *
3557 * @param {DOMElement} node
3558 * @param {string} html
3559 * @internal
3560 */
3561
3562var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
3563 if (node.namespaceURI === Namespaces.svg) {
3564 {
3565 if (enableTrustedTypesIntegration) {
3566 // TODO: reconsider the text of this warning and when it should show
3567 // before enabling the feature flag.
3568 !(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;
3569 }
3570 }
3571
3572 if (!('innerHTML' in node)) {
3573 // IE does not have innerHTML for SVG nodes, so instead we inject the
3574 // new markup in a temp node and then move the child nodes across into
3575 // the target node
3576 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
3577 reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
3578 var svgNode = reusableSVGContainer.firstChild;
3579
3580 while (node.firstChild) {
3581 node.removeChild(node.firstChild);
3582 }
3583
3584 while (svgNode.firstChild) {
3585 node.appendChild(svgNode.firstChild);
3586 }
3587
3588 return;
3589 }
3590 }
3591
3592 node.innerHTML = html;
3593});
3594
3595/**
3596 * HTML nodeType values that represent the type of the node
3597 */
3598var ELEMENT_NODE = 1;
3599var TEXT_NODE = 3;
3600var COMMENT_NODE = 8;
3601var DOCUMENT_NODE = 9;
3602var DOCUMENT_FRAGMENT_NODE = 11;
3603
3604/**
3605 * Set the textContent property of a node. For text updates, it's faster
3606 * to set the `nodeValue` of the Text node directly instead of using
3607 * `.textContent` which will remove the existing node and create a new one.
3608 *
3609 * @param {DOMElement} node
3610 * @param {string} text
3611 * @internal
3612 */
3613
3614var setTextContent = function (node, text) {
3615 if (text) {
3616 var firstChild = node.firstChild;
3617
3618 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
3619 firstChild.nodeValue = text;
3620 return;
3621 }
3622 }
3623
3624 node.textContent = text;
3625};
3626
3627// Do not use the below two methods directly!
3628// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
3629// (It is the only module that is allowed to access these methods.)
3630function unsafeCastStringToDOMTopLevelType(topLevelType) {
3631 return topLevelType;
3632}
3633function unsafeCastDOMTopLevelTypeToString(topLevelType) {
3634 return topLevelType;
3635}
3636
3637/**
3638 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
3639 *
3640 * @param {string} styleProp
3641 * @param {string} eventName
3642 * @returns {object}
3643 */
3644
3645function makePrefixMap(styleProp, eventName) {
3646 var prefixes = {};
3647 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
3648 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
3649 prefixes['Moz' + styleProp] = 'moz' + eventName;
3650 return prefixes;
3651}
3652/**
3653 * A list of event names to a configurable list of vendor prefixes.
3654 */
3655
3656
3657var vendorPrefixes = {
3658 animationend: makePrefixMap('Animation', 'AnimationEnd'),
3659 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
3660 animationstart: makePrefixMap('Animation', 'AnimationStart'),
3661 transitionend: makePrefixMap('Transition', 'TransitionEnd')
3662};
3663/**
3664 * Event names that have already been detected and prefixed (if applicable).
3665 */
3666
3667var prefixedEventNames = {};
3668/**
3669 * Element to check for prefixes on.
3670 */
3671
3672var style = {};
3673/**
3674 * Bootstrap if a DOM exists.
3675 */
3676
3677if (canUseDOM) {
3678 style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
3679 // the un-prefixed "animation" and "transition" properties are defined on the
3680 // style object but the events that fire will still be prefixed, so we need
3681 // to check if the un-prefixed events are usable, and if not remove them from the map.
3682
3683 if (!('AnimationEvent' in window)) {
3684 delete vendorPrefixes.animationend.animation;
3685 delete vendorPrefixes.animationiteration.animation;
3686 delete vendorPrefixes.animationstart.animation;
3687 } // Same as above
3688
3689
3690 if (!('TransitionEvent' in window)) {
3691 delete vendorPrefixes.transitionend.transition;
3692 }
3693}
3694/**
3695 * Attempts to determine the correct vendor prefixed event name.
3696 *
3697 * @param {string} eventName
3698 * @returns {string}
3699 */
3700
3701
3702function getVendorPrefixedEventName(eventName) {
3703 if (prefixedEventNames[eventName]) {
3704 return prefixedEventNames[eventName];
3705 } else if (!vendorPrefixes[eventName]) {
3706 return eventName;
3707 }
3708
3709 var prefixMap = vendorPrefixes[eventName];
3710
3711 for (var styleProp in prefixMap) {
3712 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
3713 return prefixedEventNames[eventName] = prefixMap[styleProp];
3714 }
3715 }
3716
3717 return eventName;
3718}
3719
3720/**
3721 * To identify top level events in ReactDOM, we use constants defined by this
3722 * module. This is the only module that uses the unsafe* methods to express
3723 * that the constants actually correspond to the browser event names. This lets
3724 * us save some bundle size by avoiding a top level type -> event name map.
3725 * The rest of ReactDOM code should import top level types from this file.
3726 */
3727
3728var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
3729var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
3730var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
3731var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
3732var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
3733var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
3734var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
3735var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
3736var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
3737var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
3738var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
3739var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
3740var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
3741var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
3742var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
3743var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
3744var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
3745var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
3746var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
3747var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
3748var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
3749var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
3750var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
3751var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
3752var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
3753var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
3754var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
3755var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
3756var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
3757var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
3758var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
3759var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
3760var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
3761var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
3762var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
3763var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
3764var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
3765var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
3766var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
3767var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
3768var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
3769var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
3770var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
3771var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
3772var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
3773var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
3774var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
3775var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
3776var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
3777var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
3778var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
3779var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
3780var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
3781var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
3782var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
3783
3784
3785var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
3786var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
3787var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
3788var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
3789var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
3790var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
3791var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
3792var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
3793var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
3794var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
3795var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
3796var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
3797var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
3798var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
3799var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
3800var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
3801var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
3802var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
3803var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
3804var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
3805var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
3806var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
3807var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
3808var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
3809var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
3810// Note that events in this list will *not* be listened to at the top level
3811// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
3812
3813var 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];
3814function getRawEventName(topLevelType) {
3815 return unsafeCastDOMTopLevelTypeToString(topLevelType);
3816}
3817
3818/**
3819 * `ReactInstanceMap` maintains a mapping from a public facing stateful
3820 * instance (key) and the internal representation (value). This allows public
3821 * methods to accept the user facing instance as an argument and map them back
3822 * to internal methods.
3823 *
3824 * Note that this module is currently shared and assumed to be stateless.
3825 * If this becomes an actual Map, that will break.
3826 */
3827
3828/**
3829 * This API should be called `delete` but we'd have to make sure to always
3830 * transform these to strings for IE support. When this transform is fully
3831 * supported we can rename it.
3832 */
3833
3834function get(key) {
3835 return key._reactInternalFiber;
3836}
3837function has$1(key) {
3838 return key._reactInternalFiber !== undefined;
3839}
3840function set(key, value) {
3841 key._reactInternalFiber = value;
3842}
3843
3844// Don't change these two values. They're used by React Dev Tools.
3845var NoEffect =
3846/* */
38470;
3848var PerformedWork =
3849/* */
38501; // You can change the rest (and add more).
3851
3852var Placement =
3853/* */
38542;
3855var Update =
3856/* */
38574;
3858var PlacementAndUpdate =
3859/* */
38606;
3861var Deletion =
3862/* */
38638;
3864var ContentReset =
3865/* */
386616;
3867var Callback =
3868/* */
386932;
3870var DidCapture =
3871/* */
387264;
3873var Ref =
3874/* */
3875128;
3876var Snapshot =
3877/* */
3878256;
3879var Passive =
3880/* */
3881512;
3882var Hydrating =
3883/* */
38841024;
3885var HydratingAndUpdate =
3886/* */
38871028; // Passive & Update & Callback & Ref & Snapshot
3888
3889var LifecycleEffectMask =
3890/* */
3891932; // Union of all host effects
3892
3893var HostEffectMask =
3894/* */
38952047;
3896var Incomplete =
3897/* */
38982048;
3899var ShouldCapture =
3900/* */
39014096;
3902
3903var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
3904function getNearestMountedFiber(fiber) {
3905 var node = fiber;
3906 var nearestMounted = fiber;
3907
3908 if (!fiber.alternate) {
3909 // If there is no alternate, this might be a new tree that isn't inserted
3910 // yet. If it is, then it will have a pending insertion effect on it.
3911 var nextNode = node;
3912
3913 do {
3914 node = nextNode;
3915
3916 if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
3917 // This is an insertion or in-progress hydration. The nearest possible
3918 // mounted fiber is the parent but we need to continue to figure out
3919 // if that one is still mounted.
3920 nearestMounted = node.return;
3921 }
3922
3923 nextNode = node.return;
3924 } while (nextNode);
3925 } else {
3926 while (node.return) {
3927 node = node.return;
3928 }
3929 }
3930
3931 if (node.tag === HostRoot) {
3932 // TODO: Check if this was a nested HostRoot when used with
3933 // renderContainerIntoSubtree.
3934 return nearestMounted;
3935 } // If we didn't hit the root, that means that we're in an disconnected tree
3936 // that has been unmounted.
3937
3938
3939 return null;
3940}
3941function getSuspenseInstanceFromFiber(fiber) {
3942 if (fiber.tag === SuspenseComponent) {
3943 var suspenseState = fiber.memoizedState;
3944
3945 if (suspenseState === null) {
3946 var current = fiber.alternate;
3947
3948 if (current !== null) {
3949 suspenseState = current.memoizedState;
3950 }
3951 }
3952
3953 if (suspenseState !== null) {
3954 return suspenseState.dehydrated;
3955 }
3956 }
3957
3958 return null;
3959}
3960function getContainerFromFiber(fiber) {
3961 return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
3962}
3963function isFiberMounted(fiber) {
3964 return getNearestMountedFiber(fiber) === fiber;
3965}
3966function isMounted(component) {
3967 {
3968 var owner = ReactCurrentOwner$1.current;
3969
3970 if (owner !== null && owner.tag === ClassComponent) {
3971 var ownerFiber = owner;
3972 var instance = ownerFiber.stateNode;
3973 !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;
3974 instance._warnedAboutRefsInRender = true;
3975 }
3976 }
3977
3978 var fiber = get(component);
3979
3980 if (!fiber) {
3981 return false;
3982 }
3983
3984 return getNearestMountedFiber(fiber) === fiber;
3985}
3986
3987function assertIsMounted(fiber) {
3988 if (!(getNearestMountedFiber(fiber) === fiber)) {
3989 {
3990 throw Error("Unable to find node on an unmounted component.");
3991 }
3992 }
3993}
3994
3995function findCurrentFiberUsingSlowPath(fiber) {
3996 var alternate = fiber.alternate;
3997
3998 if (!alternate) {
3999 // If there is no alternate, then we only need to check if it is mounted.
4000 var nearestMounted = getNearestMountedFiber(fiber);
4001
4002 if (!(nearestMounted !== null)) {
4003 {
4004 throw Error("Unable to find node on an unmounted component.");
4005 }
4006 }
4007
4008 if (nearestMounted !== fiber) {
4009 return null;
4010 }
4011
4012 return fiber;
4013 } // If we have two possible branches, we'll walk backwards up to the root
4014 // to see what path the root points to. On the way we may hit one of the
4015 // special cases and we'll deal with them.
4016
4017
4018 var a = fiber;
4019 var b = alternate;
4020
4021 while (true) {
4022 var parentA = a.return;
4023
4024 if (parentA === null) {
4025 // We're at the root.
4026 break;
4027 }
4028
4029 var parentB = parentA.alternate;
4030
4031 if (parentB === null) {
4032 // There is no alternate. This is an unusual case. Currently, it only
4033 // happens when a Suspense component is hidden. An extra fragment fiber
4034 // is inserted in between the Suspense fiber and its children. Skip
4035 // over this extra fragment fiber and proceed to the next parent.
4036 var nextParent = parentA.return;
4037
4038 if (nextParent !== null) {
4039 a = b = nextParent;
4040 continue;
4041 } // If there's no parent, we're at the root.
4042
4043
4044 break;
4045 } // If both copies of the parent fiber point to the same child, we can
4046 // assume that the child is current. This happens when we bailout on low
4047 // priority: the bailed out fiber's child reuses the current child.
4048
4049
4050 if (parentA.child === parentB.child) {
4051 var child = parentA.child;
4052
4053 while (child) {
4054 if (child === a) {
4055 // We've determined that A is the current branch.
4056 assertIsMounted(parentA);
4057 return fiber;
4058 }
4059
4060 if (child === b) {
4061 // We've determined that B is the current branch.
4062 assertIsMounted(parentA);
4063 return alternate;
4064 }
4065
4066 child = child.sibling;
4067 } // We should never have an alternate for any mounting node. So the only
4068 // way this could possibly happen is if this was unmounted, if at all.
4069
4070
4071 {
4072 {
4073 throw Error("Unable to find node on an unmounted component.");
4074 }
4075 }
4076 }
4077
4078 if (a.return !== b.return) {
4079 // The return pointer of A and the return pointer of B point to different
4080 // fibers. We assume that return pointers never criss-cross, so A must
4081 // belong to the child set of A.return, and B must belong to the child
4082 // set of B.return.
4083 a = parentA;
4084 b = parentB;
4085 } else {
4086 // The return pointers point to the same fiber. We'll have to use the
4087 // default, slow path: scan the child sets of each parent alternate to see
4088 // which child belongs to which set.
4089 //
4090 // Search parent A's child set
4091 var didFindChild = false;
4092 var _child = parentA.child;
4093
4094 while (_child) {
4095 if (_child === a) {
4096 didFindChild = true;
4097 a = parentA;
4098 b = parentB;
4099 break;
4100 }
4101
4102 if (_child === b) {
4103 didFindChild = true;
4104 b = parentA;
4105 a = parentB;
4106 break;
4107 }
4108
4109 _child = _child.sibling;
4110 }
4111
4112 if (!didFindChild) {
4113 // Search parent B's child set
4114 _child = parentB.child;
4115
4116 while (_child) {
4117 if (_child === a) {
4118 didFindChild = true;
4119 a = parentB;
4120 b = parentA;
4121 break;
4122 }
4123
4124 if (_child === b) {
4125 didFindChild = true;
4126 b = parentB;
4127 a = parentA;
4128 break;
4129 }
4130
4131 _child = _child.sibling;
4132 }
4133
4134 if (!didFindChild) {
4135 {
4136 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.");
4137 }
4138 }
4139 }
4140 }
4141
4142 if (!(a.alternate === b)) {
4143 {
4144 throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
4145 }
4146 }
4147 } // If the root is not a host container, we're in a disconnected tree. I.e.
4148 // unmounted.
4149
4150
4151 if (!(a.tag === HostRoot)) {
4152 {
4153 throw Error("Unable to find node on an unmounted component.");
4154 }
4155 }
4156
4157 if (a.stateNode.current === a) {
4158 // We've determined that A is the current branch.
4159 return fiber;
4160 } // Otherwise B has to be current branch.
4161
4162
4163 return alternate;
4164}
4165function findCurrentHostFiber(parent) {
4166 var currentParent = findCurrentFiberUsingSlowPath(parent);
4167
4168 if (!currentParent) {
4169 return null;
4170 } // Next we'll drill down this component to find the first HostComponent/Text.
4171
4172
4173 var node = currentParent;
4174
4175 while (true) {
4176 if (node.tag === HostComponent || node.tag === HostText) {
4177 return node;
4178 } else if (node.child) {
4179 node.child.return = node;
4180 node = node.child;
4181 continue;
4182 }
4183
4184 if (node === currentParent) {
4185 return null;
4186 }
4187
4188 while (!node.sibling) {
4189 if (!node.return || node.return === currentParent) {
4190 return null;
4191 }
4192
4193 node = node.return;
4194 }
4195
4196 node.sibling.return = node.return;
4197 node = node.sibling;
4198 } // Flow needs the return null here, but ESLint complains about it.
4199 // eslint-disable-next-line no-unreachable
4200
4201
4202 return null;
4203}
4204function findCurrentHostFiberWithNoPortals(parent) {
4205 var currentParent = findCurrentFiberUsingSlowPath(parent);
4206
4207 if (!currentParent) {
4208 return null;
4209 } // Next we'll drill down this component to find the first HostComponent/Text.
4210
4211
4212 var node = currentParent;
4213
4214 while (true) {
4215 if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI && node.tag === FundamentalComponent) {
4216 return node;
4217 } else if (node.child && node.tag !== HostPortal) {
4218 node.child.return = node;
4219 node = node.child;
4220 continue;
4221 }
4222
4223 if (node === currentParent) {
4224 return null;
4225 }
4226
4227 while (!node.sibling) {
4228 if (!node.return || node.return === currentParent) {
4229 return null;
4230 }
4231
4232 node = node.return;
4233 }
4234
4235 node.sibling.return = node.return;
4236 node = node.sibling;
4237 } // Flow needs the return null here, but ESLint complains about it.
4238 // eslint-disable-next-line no-unreachable
4239
4240
4241 return null;
4242}
4243
4244var attemptSynchronousHydration;
4245function setAttemptSynchronousHydration(fn) {
4246 attemptSynchronousHydration = fn;
4247}
4248var attemptUserBlockingHydration;
4249function setAttemptUserBlockingHydration(fn) {
4250 attemptUserBlockingHydration = fn;
4251}
4252var attemptContinuousHydration;
4253function setAttemptContinuousHydration(fn) {
4254 attemptContinuousHydration = fn;
4255}
4256var attemptHydrationAtCurrentPriority;
4257function setAttemptHydrationAtCurrentPriority(fn) {
4258 attemptHydrationAtCurrentPriority = fn;
4259} // TODO: Upgrade this definition once we're on a newer version of Flow that
4260// has this definition built-in.
4261
4262var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
4263
4264var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
4265
4266// if the last target was dehydrated.
4267
4268var queuedFocus = null;
4269var queuedDrag = null;
4270var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
4271
4272var queuedPointers = new Map();
4273var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
4274
4275var queuedExplicitHydrationTargets = [];
4276function hasQueuedDiscreteEvents() {
4277 return queuedDiscreteEvents.length > 0;
4278}
4279
4280var 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];
4281var 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];
4282function isReplayableDiscreteEvent(eventType) {
4283 return discreteReplayableEvents.indexOf(eventType) > -1;
4284}
4285
4286function trapReplayableEvent(topLevelType, document, listeningSet) {
4287 listenToTopLevel(topLevelType, document, listeningSet);
4288
4289 if (enableFlareAPI) {
4290 // Trap events for the responder system.
4291 var passiveEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_passive';
4292
4293 if (!listeningSet.has(passiveEventKey)) {
4294 trapEventForResponderEventSystem(document, topLevelType, true);
4295 listeningSet.add(passiveEventKey);
4296 } // TODO: This listens to all events as active which might have
4297 // undesirable effects. It's also unnecessary to have both
4298 // passive and active listeners. Instead, we could start with
4299 // a passive and upgrade it to an active one if needed.
4300 // For replaying purposes the active is never needed since we
4301 // currently don't preventDefault.
4302
4303
4304 var activeEventKey = unsafeCastDOMTopLevelTypeToString(topLevelType) + '_active';
4305
4306 if (!listeningSet.has(activeEventKey)) {
4307 trapEventForResponderEventSystem(document, topLevelType, false);
4308 listeningSet.add(activeEventKey);
4309 }
4310 }
4311}
4312
4313function eagerlyTrapReplayableEvents(document) {
4314 var listeningSet = getListeningSetForElement(document); // Discrete
4315
4316 discreteReplayableEvents.forEach(function (topLevelType) {
4317 trapReplayableEvent(topLevelType, document, listeningSet);
4318 }); // Continuous
4319
4320 continuousReplayableEvents.forEach(function (topLevelType) {
4321 trapReplayableEvent(topLevelType, document, listeningSet);
4322 });
4323}
4324
4325function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4326 return {
4327 blockedOn: blockedOn,
4328 topLevelType: topLevelType,
4329 eventSystemFlags: eventSystemFlags | IS_REPLAYED,
4330 nativeEvent: nativeEvent
4331 };
4332}
4333
4334function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4335 var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4336 queuedDiscreteEvents.push(queuedEvent);
4337
4338 if (enableSelectiveHydration) {
4339 if (queuedDiscreteEvents.length === 1) {
4340 // If this was the first discrete event, we might be able to
4341 // synchronously unblock it so that preventDefault still works.
4342 while (queuedEvent.blockedOn !== null) {
4343 var _fiber = getInstanceFromNode$1(queuedEvent.blockedOn);
4344
4345 if (_fiber === null) {
4346 break;
4347 }
4348
4349 attemptSynchronousHydration(_fiber);
4350
4351 if (queuedEvent.blockedOn === null) {
4352 // We got unblocked by hydration. Let's try again.
4353 replayUnblockedEvents(); // If we're reblocked, on an inner boundary, we might need
4354 // to attempt hydrating that one.
4355
4356 continue;
4357 } else {
4358 // We're still blocked from hydation, we have to give up
4359 // and replay later.
4360 break;
4361 }
4362 }
4363 }
4364 }
4365} // Resets the replaying for this type of continuous event to no event.
4366
4367function clearIfContinuousEvent(topLevelType, nativeEvent) {
4368 switch (topLevelType) {
4369 case TOP_FOCUS:
4370 case TOP_BLUR:
4371 queuedFocus = null;
4372 break;
4373
4374 case TOP_DRAG_ENTER:
4375 case TOP_DRAG_LEAVE:
4376 queuedDrag = null;
4377 break;
4378
4379 case TOP_MOUSE_OVER:
4380 case TOP_MOUSE_OUT:
4381 queuedMouse = null;
4382 break;
4383
4384 case TOP_POINTER_OVER:
4385 case TOP_POINTER_OUT:
4386 {
4387 var pointerId = nativeEvent.pointerId;
4388 queuedPointers.delete(pointerId);
4389 break;
4390 }
4391
4392 case TOP_GOT_POINTER_CAPTURE:
4393 case TOP_LOST_POINTER_CAPTURE:
4394 {
4395 var _pointerId = nativeEvent.pointerId;
4396 queuedPointerCaptures.delete(_pointerId);
4397 break;
4398 }
4399 }
4400}
4401
4402function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4403 if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
4404 var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
4405
4406 if (blockedOn !== null) {
4407 var _fiber2 = getInstanceFromNode$1(blockedOn);
4408
4409 if (_fiber2 !== null) {
4410 // Attempt to increase the priority of this target.
4411 attemptContinuousHydration(_fiber2);
4412 }
4413 }
4414
4415 return queuedEvent;
4416 } // If we have already queued this exact event, then it's because
4417 // the different event systems have different DOM event listeners.
4418 // We can accumulate the flags and store a single event to be
4419 // replayed.
4420
4421
4422 existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
4423 return existingQueuedEvent;
4424}
4425
4426function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent) {
4427 // These set relatedTarget to null because the replayed event will be treated as if we
4428 // moved from outside the window (no target) onto the target once it hydrates.
4429 // Instead of mutating we could clone the event.
4430 switch (topLevelType) {
4431 case TOP_FOCUS:
4432 {
4433 var focusEvent = nativeEvent;
4434 queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, focusEvent);
4435 return true;
4436 }
4437
4438 case TOP_DRAG_ENTER:
4439 {
4440 var dragEvent = nativeEvent;
4441 queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, dragEvent);
4442 return true;
4443 }
4444
4445 case TOP_MOUSE_OVER:
4446 {
4447 var mouseEvent = nativeEvent;
4448 queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, mouseEvent);
4449 return true;
4450 }
4451
4452 case TOP_POINTER_OVER:
4453 {
4454 var pointerEvent = nativeEvent;
4455 var pointerId = pointerEvent.pointerId;
4456 queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, pointerEvent));
4457 return true;
4458 }
4459
4460 case TOP_GOT_POINTER_CAPTURE:
4461 {
4462 var _pointerEvent = nativeEvent;
4463 var _pointerId2 = _pointerEvent.pointerId;
4464 queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, _pointerEvent));
4465 return true;
4466 }
4467 }
4468
4469 return false;
4470} // Check if this target is unblocked. Returns true if it's unblocked.
4471
4472function attemptExplicitHydrationTarget(queuedTarget) {
4473 // TODO: This function shares a lot of logic with attemptToDispatchEvent.
4474 // Try to unify them. It's a bit tricky since it would require two return
4475 // values.
4476 var targetInst = getClosestInstanceFromNode(queuedTarget.target);
4477
4478 if (targetInst !== null) {
4479 var nearestMounted = getNearestMountedFiber(targetInst);
4480
4481 if (nearestMounted !== null) {
4482 var tag = nearestMounted.tag;
4483
4484 if (tag === SuspenseComponent) {
4485 var instance = getSuspenseInstanceFromFiber(nearestMounted);
4486
4487 if (instance !== null) {
4488 // We're blocked on hydrating this boundary.
4489 // Increase its priority.
4490 queuedTarget.blockedOn = instance;
4491 unstable_runWithPriority(queuedTarget.priority, function () {
4492 attemptHydrationAtCurrentPriority(nearestMounted);
4493 });
4494 return;
4495 }
4496 } else if (tag === HostRoot) {
4497 var root = nearestMounted.stateNode;
4498
4499 if (root.hydrate) {
4500 queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
4501 // a root other than sync.
4502
4503 return;
4504 }
4505 }
4506 }
4507 }
4508
4509 queuedTarget.blockedOn = null;
4510}
4511
4512function queueExplicitHydrationTarget(target) {
4513 if (enableSelectiveHydration) {
4514 var priority = unstable_getCurrentPriorityLevel();
4515 var queuedTarget = {
4516 blockedOn: null,
4517 target: target,
4518 priority: priority
4519 };
4520 var i = 0;
4521
4522 for (; i < queuedExplicitHydrationTargets.length; i++) {
4523 if (priority <= queuedExplicitHydrationTargets[i].priority) {
4524 break;
4525 }
4526 }
4527
4528 queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
4529
4530 if (i === 0) {
4531 attemptExplicitHydrationTarget(queuedTarget);
4532 }
4533 }
4534}
4535
4536function attemptReplayContinuousQueuedEvent(queuedEvent) {
4537 if (queuedEvent.blockedOn !== null) {
4538 return false;
4539 }
4540
4541 var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.nativeEvent);
4542
4543 if (nextBlockedOn !== null) {
4544 // We're still blocked. Try again later.
4545 var _fiber3 = getInstanceFromNode$1(nextBlockedOn);
4546
4547 if (_fiber3 !== null) {
4548 attemptContinuousHydration(_fiber3);
4549 }
4550
4551 queuedEvent.blockedOn = nextBlockedOn;
4552 return false;
4553 }
4554
4555 return true;
4556}
4557
4558function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
4559 if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
4560 map.delete(key);
4561 }
4562}
4563
4564function replayUnblockedEvents() {
4565 hasScheduledReplayAttempt = false; // First replay discrete events.
4566
4567 while (queuedDiscreteEvents.length > 0) {
4568 var nextDiscreteEvent = queuedDiscreteEvents[0];
4569
4570 if (nextDiscreteEvent.blockedOn !== null) {
4571 // We're still blocked.
4572 // Increase the priority of this boundary to unblock
4573 // the next discrete event.
4574 var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);
4575
4576 if (_fiber4 !== null) {
4577 attemptUserBlockingHydration(_fiber4);
4578 }
4579
4580 break;
4581 }
4582
4583 var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.nativeEvent);
4584
4585 if (nextBlockedOn !== null) {
4586 // We're still blocked. Try again later.
4587 nextDiscreteEvent.blockedOn = nextBlockedOn;
4588 } else {
4589 // We've successfully replayed the first event. Let's try the next one.
4590 queuedDiscreteEvents.shift();
4591 }
4592 } // Next replay any continuous events.
4593
4594
4595 if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
4596 queuedFocus = null;
4597 }
4598
4599 if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
4600 queuedDrag = null;
4601 }
4602
4603 if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
4604 queuedMouse = null;
4605 }
4606
4607 queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
4608 queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
4609}
4610
4611function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
4612 if (queuedEvent.blockedOn === unblocked) {
4613 queuedEvent.blockedOn = null;
4614
4615 if (!hasScheduledReplayAttempt) {
4616 hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
4617 // now unblocked. This first might not actually be unblocked yet.
4618 // We could check it early to avoid scheduling an unnecessary callback.
4619
4620 unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
4621 }
4622 }
4623}
4624
4625function retryIfBlockedOn(unblocked) {
4626 // Mark anything that was blocked on this as no longer blocked
4627 // and eligible for a replay.
4628 if (queuedDiscreteEvents.length > 0) {
4629 scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
4630 // worth it because we expect very few discrete events to queue up and once
4631 // we are actually fully unblocked it will be fast to replay them.
4632
4633 for (var i = 1; i < queuedDiscreteEvents.length; i++) {
4634 var queuedEvent = queuedDiscreteEvents[i];
4635
4636 if (queuedEvent.blockedOn === unblocked) {
4637 queuedEvent.blockedOn = null;
4638 }
4639 }
4640 }
4641
4642 if (queuedFocus !== null) {
4643 scheduleCallbackIfUnblocked(queuedFocus, unblocked);
4644 }
4645
4646 if (queuedDrag !== null) {
4647 scheduleCallbackIfUnblocked(queuedDrag, unblocked);
4648 }
4649
4650 if (queuedMouse !== null) {
4651 scheduleCallbackIfUnblocked(queuedMouse, unblocked);
4652 }
4653
4654 var unblock = function (queuedEvent) {
4655 return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
4656 };
4657
4658 queuedPointers.forEach(unblock);
4659 queuedPointerCaptures.forEach(unblock);
4660
4661 for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
4662 var queuedTarget = queuedExplicitHydrationTargets[_i];
4663
4664 if (queuedTarget.blockedOn === unblocked) {
4665 queuedTarget.blockedOn = null;
4666 }
4667 }
4668
4669 while (queuedExplicitHydrationTargets.length > 0) {
4670 var nextExplicitTarget = queuedExplicitHydrationTargets[0];
4671
4672 if (nextExplicitTarget.blockedOn !== null) {
4673 // We're still blocked.
4674 break;
4675 } else {
4676 attemptExplicitHydrationTarget(nextExplicitTarget);
4677
4678 if (nextExplicitTarget.blockedOn === null) {
4679 // We're unblocked.
4680 queuedExplicitHydrationTargets.shift();
4681 }
4682 }
4683 }
4684}
4685
4686function addEventBubbleListener(element, eventType, listener) {
4687 element.addEventListener(eventType, listener, false);
4688}
4689function addEventCaptureListener(element, eventType, listener) {
4690 element.addEventListener(eventType, listener, true);
4691}
4692function addEventCaptureListenerWithPassiveFlag(element, eventType, listener, passive) {
4693 element.addEventListener(eventType, listener, {
4694 capture: true,
4695 passive: passive
4696 });
4697}
4698
4699/**
4700 * Gets the target node from a native browser event by accounting for
4701 * inconsistencies in browser DOM APIs.
4702 *
4703 * @param {object} nativeEvent Native browser event.
4704 * @return {DOMEventTarget} Target node.
4705 */
4706
4707function getEventTarget(nativeEvent) {
4708 // Fallback to nativeEvent.srcElement for IE9
4709 // https://github.com/facebook/react/issues/12506
4710 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
4711
4712 if (target.correspondingUseElement) {
4713 target = target.correspondingUseElement;
4714 } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
4715 // @see http://www.quirksmode.org/js/events_properties.html
4716
4717
4718 return target.nodeType === TEXT_NODE ? target.parentNode : target;
4719}
4720
4721function getParent(inst) {
4722 do {
4723 inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
4724 // That is depending on if we want nested subtrees (layers) to bubble
4725 // events to their parent. We could also go through parentNode on the
4726 // host node but that wouldn't work for React Native and doesn't let us
4727 // do the portal feature.
4728 } while (inst && inst.tag !== HostComponent);
4729
4730 if (inst) {
4731 return inst;
4732 }
4733
4734 return null;
4735}
4736/**
4737 * Return the lowest common ancestor of A and B, or null if they are in
4738 * different trees.
4739 */
4740
4741
4742function getLowestCommonAncestor(instA, instB) {
4743 var depthA = 0;
4744
4745 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
4746 depthA++;
4747 }
4748
4749 var depthB = 0;
4750
4751 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
4752 depthB++;
4753 } // If A is deeper, crawl up.
4754
4755
4756 while (depthA - depthB > 0) {
4757 instA = getParent(instA);
4758 depthA--;
4759 } // If B is deeper, crawl up.
4760
4761
4762 while (depthB - depthA > 0) {
4763 instB = getParent(instB);
4764 depthB--;
4765 } // Walk in lockstep until we find a match.
4766
4767
4768 var depth = depthA;
4769
4770 while (depth--) {
4771 if (instA === instB || instA === instB.alternate) {
4772 return instA;
4773 }
4774
4775 instA = getParent(instA);
4776 instB = getParent(instB);
4777 }
4778
4779 return null;
4780}
4781/**
4782 * Return if A is an ancestor of B.
4783 */
4784
4785
4786/**
4787 * Return the parent instance of the passed-in instance.
4788 */
4789
4790
4791/**
4792 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
4793 */
4794
4795function traverseTwoPhase(inst, fn, arg) {
4796 var path = [];
4797
4798 while (inst) {
4799 path.push(inst);
4800 inst = getParent(inst);
4801 }
4802
4803 var i;
4804
4805 for (i = path.length; i-- > 0;) {
4806 fn(path[i], 'captured', arg);
4807 }
4808
4809 for (i = 0; i < path.length; i++) {
4810 fn(path[i], 'bubbled', arg);
4811 }
4812}
4813/**
4814 * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
4815 * should would receive a `mouseEnter` or `mouseLeave` event.
4816 *
4817 * Does not invoke the callback on the nearest common ancestor because nothing
4818 * "entered" or "left" that element.
4819 */
4820
4821function traverseEnterLeave(from, to, fn, argFrom, argTo) {
4822 var common = from && to ? getLowestCommonAncestor(from, to) : null;
4823 var pathFrom = [];
4824
4825 while (true) {
4826 if (!from) {
4827 break;
4828 }
4829
4830 if (from === common) {
4831 break;
4832 }
4833
4834 var alternate = from.alternate;
4835
4836 if (alternate !== null && alternate === common) {
4837 break;
4838 }
4839
4840 pathFrom.push(from);
4841 from = getParent(from);
4842 }
4843
4844 var pathTo = [];
4845
4846 while (true) {
4847 if (!to) {
4848 break;
4849 }
4850
4851 if (to === common) {
4852 break;
4853 }
4854
4855 var _alternate = to.alternate;
4856
4857 if (_alternate !== null && _alternate === common) {
4858 break;
4859 }
4860
4861 pathTo.push(to);
4862 to = getParent(to);
4863 }
4864
4865 for (var i = 0; i < pathFrom.length; i++) {
4866 fn(pathFrom[i], 'bubbled', argFrom);
4867 }
4868
4869 for (var _i = pathTo.length; _i-- > 0;) {
4870 fn(pathTo[_i], 'captured', argTo);
4871 }
4872}
4873
4874/**
4875 * Some event types have a notion of different registration names for different
4876 * "phases" of propagation. This finds listeners by a given phase.
4877 */
4878function listenerAtPhase(inst, event, propagationPhase) {
4879 var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
4880 return getListener(inst, registrationName);
4881}
4882/**
4883 * A small set of propagation patterns, each of which will accept a small amount
4884 * of information, and generate a set of "dispatch ready event objects" - which
4885 * are sets of events that have already been annotated with a set of dispatched
4886 * listener functions/ids. The API is designed this way to discourage these
4887 * propagation strategies from actually executing the dispatches, since we
4888 * always want to collect the entire set of dispatches before executing even a
4889 * single one.
4890 */
4891
4892/**
4893 * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
4894 * here, allows us to not have to bind or create functions for each event.
4895 * Mutating the event's members allows us to not have to create a wrapping
4896 * "dispatch" object that pairs the event with the listener.
4897 */
4898
4899
4900function accumulateDirectionalDispatches(inst, phase, event) {
4901 {
4902 !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0;
4903 }
4904
4905 var listener = listenerAtPhase(inst, event, phase);
4906
4907 if (listener) {
4908 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4909 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4910 }
4911}
4912/**
4913 * Collect dispatches (must be entirely collected before dispatching - see unit
4914 * tests). Lazily allocate the array to conserve memory. We must loop through
4915 * each event and perform the traversal for each one. We cannot perform a
4916 * single traversal for the entire collection of events because each event may
4917 * have a different target.
4918 */
4919
4920
4921function accumulateTwoPhaseDispatchesSingle(event) {
4922 if (event && event.dispatchConfig.phasedRegistrationNames) {
4923 traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
4924 }
4925}
4926/**
4927 * Accumulates without regard to direction, does not look for phased
4928 * registration names. Same as `accumulateDirectDispatchesSingle` but without
4929 * requiring that the `dispatchMarker` be the same as the dispatched ID.
4930 */
4931
4932
4933function accumulateDispatches(inst, ignoredDirection, event) {
4934 if (inst && event && event.dispatchConfig.registrationName) {
4935 var registrationName = event.dispatchConfig.registrationName;
4936 var listener = getListener(inst, registrationName);
4937
4938 if (listener) {
4939 event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
4940 event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
4941 }
4942 }
4943}
4944/**
4945 * Accumulates dispatches on an `SyntheticEvent`, but only for the
4946 * `dispatchMarker`.
4947 * @param {SyntheticEvent} event
4948 */
4949
4950
4951function accumulateDirectDispatchesSingle(event) {
4952 if (event && event.dispatchConfig.registrationName) {
4953 accumulateDispatches(event._targetInst, null, event);
4954 }
4955}
4956
4957function accumulateTwoPhaseDispatches(events) {
4958 forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
4959}
4960
4961function accumulateEnterLeaveDispatches(leave, enter, from, to) {
4962 traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
4963}
4964function accumulateDirectDispatches(events) {
4965 forEachAccumulated(events, accumulateDirectDispatchesSingle);
4966}
4967
4968/* eslint valid-typeof: 0 */
4969var EVENT_POOL_SIZE = 10;
4970/**
4971 * @interface Event
4972 * @see http://www.w3.org/TR/DOM-Level-3-Events/
4973 */
4974
4975var EventInterface = {
4976 type: null,
4977 target: null,
4978 // currentTarget is set when dispatching; no use in copying it here
4979 currentTarget: function () {
4980 return null;
4981 },
4982 eventPhase: null,
4983 bubbles: null,
4984 cancelable: null,
4985 timeStamp: function (event) {
4986 return event.timeStamp || Date.now();
4987 },
4988 defaultPrevented: null,
4989 isTrusted: null
4990};
4991
4992function functionThatReturnsTrue() {
4993 return true;
4994}
4995
4996function functionThatReturnsFalse() {
4997 return false;
4998}
4999/**
5000 * Synthetic events are dispatched by event plugins, typically in response to a
5001 * top-level event delegation handler.
5002 *
5003 * These systems should generally use pooling to reduce the frequency of garbage
5004 * collection. The system should check `isPersistent` to determine whether the
5005 * event should be released into the pool after being dispatched. Users that
5006 * need a persisted event should invoke `persist`.
5007 *
5008 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
5009 * normalizing browser quirks. Subclasses do not necessarily have to implement a
5010 * DOM interface; custom application-specific events can also subclass this.
5011 *
5012 * @param {object} dispatchConfig Configuration used to dispatch this event.
5013 * @param {*} targetInst Marker identifying the event target.
5014 * @param {object} nativeEvent Native browser event.
5015 * @param {DOMEventTarget} nativeEventTarget Target node.
5016 */
5017
5018
5019function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
5020 {
5021 // these have a getter/setter for warnings
5022 delete this.nativeEvent;
5023 delete this.preventDefault;
5024 delete this.stopPropagation;
5025 delete this.isDefaultPrevented;
5026 delete this.isPropagationStopped;
5027 }
5028
5029 this.dispatchConfig = dispatchConfig;
5030 this._targetInst = targetInst;
5031 this.nativeEvent = nativeEvent;
5032 var Interface = this.constructor.Interface;
5033
5034 for (var propName in Interface) {
5035 if (!Interface.hasOwnProperty(propName)) {
5036 continue;
5037 }
5038
5039 {
5040 delete this[propName]; // this has a getter/setter for warnings
5041 }
5042
5043 var normalize = Interface[propName];
5044
5045 if (normalize) {
5046 this[propName] = normalize(nativeEvent);
5047 } else {
5048 if (propName === 'target') {
5049 this.target = nativeEventTarget;
5050 } else {
5051 this[propName] = nativeEvent[propName];
5052 }
5053 }
5054 }
5055
5056 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
5057
5058 if (defaultPrevented) {
5059 this.isDefaultPrevented = functionThatReturnsTrue;
5060 } else {
5061 this.isDefaultPrevented = functionThatReturnsFalse;
5062 }
5063
5064 this.isPropagationStopped = functionThatReturnsFalse;
5065 return this;
5066}
5067
5068_assign(SyntheticEvent.prototype, {
5069 preventDefault: function () {
5070 this.defaultPrevented = true;
5071 var event = this.nativeEvent;
5072
5073 if (!event) {
5074 return;
5075 }
5076
5077 if (event.preventDefault) {
5078 event.preventDefault();
5079 } else if (typeof event.returnValue !== 'unknown') {
5080 event.returnValue = false;
5081 }
5082
5083 this.isDefaultPrevented = functionThatReturnsTrue;
5084 },
5085 stopPropagation: function () {
5086 var event = this.nativeEvent;
5087
5088 if (!event) {
5089 return;
5090 }
5091
5092 if (event.stopPropagation) {
5093 event.stopPropagation();
5094 } else if (typeof event.cancelBubble !== 'unknown') {
5095 // The ChangeEventPlugin registers a "propertychange" event for
5096 // IE. This event does not support bubbling or cancelling, and
5097 // any references to cancelBubble throw "Member not found". A
5098 // typeof check of "unknown" circumvents this issue (and is also
5099 // IE specific).
5100 event.cancelBubble = true;
5101 }
5102
5103 this.isPropagationStopped = functionThatReturnsTrue;
5104 },
5105
5106 /**
5107 * We release all dispatched `SyntheticEvent`s after each event loop, adding
5108 * them back into the pool. This allows a way to hold onto a reference that
5109 * won't be added back into the pool.
5110 */
5111 persist: function () {
5112 this.isPersistent = functionThatReturnsTrue;
5113 },
5114
5115 /**
5116 * Checks if this event should be released back into the pool.
5117 *
5118 * @return {boolean} True if this should not be released, false otherwise.
5119 */
5120 isPersistent: functionThatReturnsFalse,
5121
5122 /**
5123 * `PooledClass` looks for `destructor` on each instance it releases.
5124 */
5125 destructor: function () {
5126 var Interface = this.constructor.Interface;
5127
5128 for (var propName in Interface) {
5129 {
5130 Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
5131 }
5132 }
5133
5134 this.dispatchConfig = null;
5135 this._targetInst = null;
5136 this.nativeEvent = null;
5137 this.isDefaultPrevented = functionThatReturnsFalse;
5138 this.isPropagationStopped = functionThatReturnsFalse;
5139 this._dispatchListeners = null;
5140 this._dispatchInstances = null;
5141
5142 {
5143 Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
5144 Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
5145 Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
5146 Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
5147 Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
5148 }
5149 }
5150});
5151
5152SyntheticEvent.Interface = EventInterface;
5153/**
5154 * Helper to reduce boilerplate when creating subclasses.
5155 */
5156
5157SyntheticEvent.extend = function (Interface) {
5158 var Super = this;
5159
5160 var E = function () {};
5161
5162 E.prototype = Super.prototype;
5163 var prototype = new E();
5164
5165 function Class() {
5166 return Super.apply(this, arguments);
5167 }
5168
5169 _assign(prototype, Class.prototype);
5170
5171 Class.prototype = prototype;
5172 Class.prototype.constructor = Class;
5173 Class.Interface = _assign({}, Super.Interface, Interface);
5174 Class.extend = Super.extend;
5175 addEventPoolingTo(Class);
5176 return Class;
5177};
5178
5179addEventPoolingTo(SyntheticEvent);
5180/**
5181 * Helper to nullify syntheticEvent instance properties when destructing
5182 *
5183 * @param {String} propName
5184 * @param {?object} getVal
5185 * @return {object} defineProperty object
5186 */
5187
5188function getPooledWarningPropertyDefinition(propName, getVal) {
5189 var isFunction = typeof getVal === 'function';
5190 return {
5191 configurable: true,
5192 set: set,
5193 get: get
5194 };
5195
5196 function set(val) {
5197 var action = isFunction ? 'setting the method' : 'setting the property';
5198 warn(action, 'This is effectively a no-op');
5199 return val;
5200 }
5201
5202 function get() {
5203 var action = isFunction ? 'accessing the method' : 'accessing the property';
5204 var result = isFunction ? 'This is a no-op function' : 'This is set to null';
5205 warn(action, result);
5206 return getVal;
5207 }
5208
5209 function warn(action, result) {
5210 var warningCondition = false;
5211 !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;
5212 }
5213}
5214
5215function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
5216 var EventConstructor = this;
5217
5218 if (EventConstructor.eventPool.length) {
5219 var instance = EventConstructor.eventPool.pop();
5220 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
5221 return instance;
5222 }
5223
5224 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
5225}
5226
5227function releasePooledEvent(event) {
5228 var EventConstructor = this;
5229
5230 if (!(event instanceof EventConstructor)) {
5231 {
5232 throw Error("Trying to release an event instance into a pool of a different type.");
5233 }
5234 }
5235
5236 event.destructor();
5237
5238 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
5239 EventConstructor.eventPool.push(event);
5240 }
5241}
5242
5243function addEventPoolingTo(EventConstructor) {
5244 EventConstructor.eventPool = [];
5245 EventConstructor.getPooled = getPooledEvent;
5246 EventConstructor.release = releasePooledEvent;
5247}
5248
5249/**
5250 * @interface Event
5251 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
5252 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
5253 */
5254
5255var SyntheticAnimationEvent = SyntheticEvent.extend({
5256 animationName: null,
5257 elapsedTime: null,
5258 pseudoElement: null
5259});
5260
5261/**
5262 * @interface Event
5263 * @see http://www.w3.org/TR/clipboard-apis/
5264 */
5265
5266var SyntheticClipboardEvent = SyntheticEvent.extend({
5267 clipboardData: function (event) {
5268 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
5269 }
5270});
5271
5272var SyntheticUIEvent = SyntheticEvent.extend({
5273 view: null,
5274 detail: null
5275});
5276
5277/**
5278 * @interface FocusEvent
5279 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5280 */
5281
5282var SyntheticFocusEvent = SyntheticUIEvent.extend({
5283 relatedTarget: null
5284});
5285
5286/**
5287 * `charCode` represents the actual "character code" and is safe to use with
5288 * `String.fromCharCode`. As such, only keys that correspond to printable
5289 * characters produce a valid `charCode`, the only exception to this is Enter.
5290 * The Tab-key is considered non-printable and does not have a `charCode`,
5291 * presumably because it does not produce a tab-character in browsers.
5292 *
5293 * @param {object} nativeEvent Native browser event.
5294 * @return {number} Normalized `charCode` property.
5295 */
5296function getEventCharCode(nativeEvent) {
5297 var charCode;
5298 var keyCode = nativeEvent.keyCode;
5299
5300 if ('charCode' in nativeEvent) {
5301 charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
5302
5303 if (charCode === 0 && keyCode === 13) {
5304 charCode = 13;
5305 }
5306 } else {
5307 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
5308 charCode = keyCode;
5309 } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
5310 // report Enter as charCode 10 when ctrl is pressed.
5311
5312
5313 if (charCode === 10) {
5314 charCode = 13;
5315 } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
5316 // Must not discard the (non-)printable Enter-key.
5317
5318
5319 if (charCode >= 32 || charCode === 13) {
5320 return charCode;
5321 }
5322
5323 return 0;
5324}
5325
5326/**
5327 * Normalization of deprecated HTML5 `key` values
5328 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5329 */
5330
5331var normalizeKey = {
5332 Esc: 'Escape',
5333 Spacebar: ' ',
5334 Left: 'ArrowLeft',
5335 Up: 'ArrowUp',
5336 Right: 'ArrowRight',
5337 Down: 'ArrowDown',
5338 Del: 'Delete',
5339 Win: 'OS',
5340 Menu: 'ContextMenu',
5341 Apps: 'ContextMenu',
5342 Scroll: 'ScrollLock',
5343 MozPrintableKey: 'Unidentified'
5344};
5345/**
5346 * Translation from legacy `keyCode` to HTML5 `key`
5347 * Only special keys supported, all others depend on keyboard layout or browser
5348 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
5349 */
5350
5351var translateToKey = {
5352 '8': 'Backspace',
5353 '9': 'Tab',
5354 '12': 'Clear',
5355 '13': 'Enter',
5356 '16': 'Shift',
5357 '17': 'Control',
5358 '18': 'Alt',
5359 '19': 'Pause',
5360 '20': 'CapsLock',
5361 '27': 'Escape',
5362 '32': ' ',
5363 '33': 'PageUp',
5364 '34': 'PageDown',
5365 '35': 'End',
5366 '36': 'Home',
5367 '37': 'ArrowLeft',
5368 '38': 'ArrowUp',
5369 '39': 'ArrowRight',
5370 '40': 'ArrowDown',
5371 '45': 'Insert',
5372 '46': 'Delete',
5373 '112': 'F1',
5374 '113': 'F2',
5375 '114': 'F3',
5376 '115': 'F4',
5377 '116': 'F5',
5378 '117': 'F6',
5379 '118': 'F7',
5380 '119': 'F8',
5381 '120': 'F9',
5382 '121': 'F10',
5383 '122': 'F11',
5384 '123': 'F12',
5385 '144': 'NumLock',
5386 '145': 'ScrollLock',
5387 '224': 'Meta'
5388};
5389/**
5390 * @param {object} nativeEvent Native browser event.
5391 * @return {string} Normalized `key` property.
5392 */
5393
5394function getEventKey(nativeEvent) {
5395 if (nativeEvent.key) {
5396 // Normalize inconsistent values reported by browsers due to
5397 // implementations of a working draft specification.
5398 // FireFox implements `key` but returns `MozPrintableKey` for all
5399 // printable characters (normalized to `Unidentified`), ignore it.
5400 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
5401
5402 if (key !== 'Unidentified') {
5403 return key;
5404 }
5405 } // Browser does not implement `key`, polyfill as much of it as we can.
5406
5407
5408 if (nativeEvent.type === 'keypress') {
5409 var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
5410 // thus be captured by `keypress`, no other non-printable key should.
5411
5412 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
5413 }
5414
5415 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
5416 // While user keyboard layout determines the actual meaning of each
5417 // `keyCode` value, almost all function keys have a universal value.
5418 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
5419 }
5420
5421 return '';
5422}
5423
5424/**
5425 * Translation from modifier key to the associated property in the event.
5426 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
5427 */
5428var modifierKeyToProp = {
5429 Alt: 'altKey',
5430 Control: 'ctrlKey',
5431 Meta: 'metaKey',
5432 Shift: 'shiftKey'
5433}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
5434// getModifierState. If getModifierState is not supported, we map it to a set of
5435// modifier keys exposed by the event. In this case, Lock-keys are not supported.
5436
5437function modifierStateGetter(keyArg) {
5438 var syntheticEvent = this;
5439 var nativeEvent = syntheticEvent.nativeEvent;
5440
5441 if (nativeEvent.getModifierState) {
5442 return nativeEvent.getModifierState(keyArg);
5443 }
5444
5445 var keyProp = modifierKeyToProp[keyArg];
5446 return keyProp ? !!nativeEvent[keyProp] : false;
5447}
5448
5449function getEventModifierState(nativeEvent) {
5450 return modifierStateGetter;
5451}
5452
5453/**
5454 * @interface KeyboardEvent
5455 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5456 */
5457
5458var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
5459 key: getEventKey,
5460 location: null,
5461 ctrlKey: null,
5462 shiftKey: null,
5463 altKey: null,
5464 metaKey: null,
5465 repeat: null,
5466 locale: null,
5467 getModifierState: getEventModifierState,
5468 // Legacy Interface
5469 charCode: function (event) {
5470 // `charCode` is the result of a KeyPress event and represents the value of
5471 // the actual printable character.
5472 // KeyPress is deprecated, but its replacement is not yet final and not
5473 // implemented in any major browser. Only KeyPress has charCode.
5474 if (event.type === 'keypress') {
5475 return getEventCharCode(event);
5476 }
5477
5478 return 0;
5479 },
5480 keyCode: function (event) {
5481 // `keyCode` is the result of a KeyDown/Up event and represents the value of
5482 // physical keyboard key.
5483 // The actual meaning of the value depends on the users' keyboard layout
5484 // which cannot be detected. Assuming that it is a US keyboard layout
5485 // provides a surprisingly accurate mapping for US and European users.
5486 // Due to this, it is left to the user to implement at this time.
5487 if (event.type === 'keydown' || event.type === 'keyup') {
5488 return event.keyCode;
5489 }
5490
5491 return 0;
5492 },
5493 which: function (event) {
5494 // `which` is an alias for either `keyCode` or `charCode` depending on the
5495 // type of the event.
5496 if (event.type === 'keypress') {
5497 return getEventCharCode(event);
5498 }
5499
5500 if (event.type === 'keydown' || event.type === 'keyup') {
5501 return event.keyCode;
5502 }
5503
5504 return 0;
5505 }
5506});
5507
5508var previousScreenX = 0;
5509var previousScreenY = 0; // Use flags to signal movementX/Y has already been set
5510
5511var isMovementXSet = false;
5512var isMovementYSet = false;
5513/**
5514 * @interface MouseEvent
5515 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5516 */
5517
5518var SyntheticMouseEvent = SyntheticUIEvent.extend({
5519 screenX: null,
5520 screenY: null,
5521 clientX: null,
5522 clientY: null,
5523 pageX: null,
5524 pageY: null,
5525 ctrlKey: null,
5526 shiftKey: null,
5527 altKey: null,
5528 metaKey: null,
5529 getModifierState: getEventModifierState,
5530 button: null,
5531 buttons: null,
5532 relatedTarget: function (event) {
5533 return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
5534 },
5535 movementX: function (event) {
5536 if ('movementX' in event) {
5537 return event.movementX;
5538 }
5539
5540 var screenX = previousScreenX;
5541 previousScreenX = event.screenX;
5542
5543 if (!isMovementXSet) {
5544 isMovementXSet = true;
5545 return 0;
5546 }
5547
5548 return event.type === 'mousemove' ? event.screenX - screenX : 0;
5549 },
5550 movementY: function (event) {
5551 if ('movementY' in event) {
5552 return event.movementY;
5553 }
5554
5555 var screenY = previousScreenY;
5556 previousScreenY = event.screenY;
5557
5558 if (!isMovementYSet) {
5559 isMovementYSet = true;
5560 return 0;
5561 }
5562
5563 return event.type === 'mousemove' ? event.screenY - screenY : 0;
5564 }
5565});
5566
5567/**
5568 * @interface PointerEvent
5569 * @see http://www.w3.org/TR/pointerevents/
5570 */
5571
5572var SyntheticPointerEvent = SyntheticMouseEvent.extend({
5573 pointerId: null,
5574 width: null,
5575 height: null,
5576 pressure: null,
5577 tangentialPressure: null,
5578 tiltX: null,
5579 tiltY: null,
5580 twist: null,
5581 pointerType: null,
5582 isPrimary: null
5583});
5584
5585/**
5586 * @interface DragEvent
5587 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5588 */
5589
5590var SyntheticDragEvent = SyntheticMouseEvent.extend({
5591 dataTransfer: null
5592});
5593
5594/**
5595 * @interface TouchEvent
5596 * @see http://www.w3.org/TR/touch-events/
5597 */
5598
5599var SyntheticTouchEvent = SyntheticUIEvent.extend({
5600 touches: null,
5601 targetTouches: null,
5602 changedTouches: null,
5603 altKey: null,
5604 metaKey: null,
5605 ctrlKey: null,
5606 shiftKey: null,
5607 getModifierState: getEventModifierState
5608});
5609
5610/**
5611 * @interface Event
5612 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
5613 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
5614 */
5615
5616var SyntheticTransitionEvent = SyntheticEvent.extend({
5617 propertyName: null,
5618 elapsedTime: null,
5619 pseudoElement: null
5620});
5621
5622/**
5623 * @interface WheelEvent
5624 * @see http://www.w3.org/TR/DOM-Level-3-Events/
5625 */
5626
5627var SyntheticWheelEvent = SyntheticMouseEvent.extend({
5628 deltaX: function (event) {
5629 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
5630 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
5631 },
5632 deltaY: function (event) {
5633 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
5634 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
5635 'wheelDelta' in event ? -event.wheelDelta : 0;
5636 },
5637 deltaZ: null,
5638 // Browsers without "deltaMode" is reporting in raw wheel delta where one
5639 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
5640 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
5641 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
5642 deltaMode: null
5643});
5644
5645/**
5646 * Turns
5647 * ['abort', ...]
5648 * into
5649 * eventTypes = {
5650 * 'abort': {
5651 * phasedRegistrationNames: {
5652 * bubbled: 'onAbort',
5653 * captured: 'onAbortCapture',
5654 * },
5655 * dependencies: [TOP_ABORT],
5656 * },
5657 * ...
5658 * };
5659 * topLevelEventsToDispatchConfig = new Map([
5660 * [TOP_ABORT, { sameConfig }],
5661 * ]);
5662 */
5663
5664var eventTuples = [// Discrete events
5665[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
5666[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
5667[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]];
5668var eventTypes = {};
5669var topLevelEventsToDispatchConfig = {};
5670
5671for (var i = 0; i < eventTuples.length; i++) {
5672 var eventTuple = eventTuples[i];
5673 var topEvent = eventTuple[0];
5674 var event = eventTuple[1];
5675 var eventPriority = eventTuple[2];
5676 var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
5677 var onEvent = 'on' + capitalizedEvent;
5678 var config = {
5679 phasedRegistrationNames: {
5680 bubbled: onEvent,
5681 captured: onEvent + 'Capture'
5682 },
5683 dependencies: [topEvent],
5684 eventPriority: eventPriority
5685 };
5686 eventTypes[event] = config;
5687 topLevelEventsToDispatchConfig[topEvent] = config;
5688} // Only used in DEV for exhaustiveness validation.
5689
5690
5691var 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];
5692var SimpleEventPlugin = {
5693 eventTypes: eventTypes,
5694 getEventPriority: function (topLevelType) {
5695 var config = topLevelEventsToDispatchConfig[topLevelType];
5696 return config !== undefined ? config.eventPriority : ContinuousEvent;
5697 },
5698 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
5699 var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
5700
5701 if (!dispatchConfig) {
5702 return null;
5703 }
5704
5705 var EventConstructor;
5706
5707 switch (topLevelType) {
5708 case TOP_KEY_PRESS:
5709 // Firefox creates a keypress event for function keys too. This removes
5710 // the unwanted keypress events. Enter is however both printable and
5711 // non-printable. One would expect Tab to be as well (but it isn't).
5712 if (getEventCharCode(nativeEvent) === 0) {
5713 return null;
5714 }
5715
5716 /* falls through */
5717
5718 case TOP_KEY_DOWN:
5719 case TOP_KEY_UP:
5720 EventConstructor = SyntheticKeyboardEvent;
5721 break;
5722
5723 case TOP_BLUR:
5724 case TOP_FOCUS:
5725 EventConstructor = SyntheticFocusEvent;
5726 break;
5727
5728 case TOP_CLICK:
5729 // Firefox creates a click event on right mouse clicks. This removes the
5730 // unwanted click events.
5731 if (nativeEvent.button === 2) {
5732 return null;
5733 }
5734
5735 /* falls through */
5736
5737 case TOP_AUX_CLICK:
5738 case TOP_DOUBLE_CLICK:
5739 case TOP_MOUSE_DOWN:
5740 case TOP_MOUSE_MOVE:
5741 case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events
5742
5743 /* falls through */
5744
5745 case TOP_MOUSE_OUT:
5746 case TOP_MOUSE_OVER:
5747 case TOP_CONTEXT_MENU:
5748 EventConstructor = SyntheticMouseEvent;
5749 break;
5750
5751 case TOP_DRAG:
5752 case TOP_DRAG_END:
5753 case TOP_DRAG_ENTER:
5754 case TOP_DRAG_EXIT:
5755 case TOP_DRAG_LEAVE:
5756 case TOP_DRAG_OVER:
5757 case TOP_DRAG_START:
5758 case TOP_DROP:
5759 EventConstructor = SyntheticDragEvent;
5760 break;
5761
5762 case TOP_TOUCH_CANCEL:
5763 case TOP_TOUCH_END:
5764 case TOP_TOUCH_MOVE:
5765 case TOP_TOUCH_START:
5766 EventConstructor = SyntheticTouchEvent;
5767 break;
5768
5769 case TOP_ANIMATION_END:
5770 case TOP_ANIMATION_ITERATION:
5771 case TOP_ANIMATION_START:
5772 EventConstructor = SyntheticAnimationEvent;
5773 break;
5774
5775 case TOP_TRANSITION_END:
5776 EventConstructor = SyntheticTransitionEvent;
5777 break;
5778
5779 case TOP_SCROLL:
5780 EventConstructor = SyntheticUIEvent;
5781 break;
5782
5783 case TOP_WHEEL:
5784 EventConstructor = SyntheticWheelEvent;
5785 break;
5786
5787 case TOP_COPY:
5788 case TOP_CUT:
5789 case TOP_PASTE:
5790 EventConstructor = SyntheticClipboardEvent;
5791 break;
5792
5793 case TOP_GOT_POINTER_CAPTURE:
5794 case TOP_LOST_POINTER_CAPTURE:
5795 case TOP_POINTER_CANCEL:
5796 case TOP_POINTER_DOWN:
5797 case TOP_POINTER_MOVE:
5798 case TOP_POINTER_OUT:
5799 case TOP_POINTER_OVER:
5800 case TOP_POINTER_UP:
5801 EventConstructor = SyntheticPointerEvent;
5802 break;
5803
5804 default:
5805 {
5806 if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
5807 warningWithoutStack$1(false, 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
5808 }
5809 } // HTML Events
5810 // @see http://www.w3.org/TR/html5/index.html#events-0
5811
5812
5813 EventConstructor = SyntheticEvent;
5814 break;
5815 }
5816
5817 var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
5818 accumulateTwoPhaseDispatches(event);
5819 return event;
5820 }
5821};
5822
5823var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
5824// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
5825
5826if (enableFlareAPI && canUseDOM) {
5827 try {
5828 var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
5829
5830 Object.defineProperty(options, 'passive', {
5831 get: function () {
5832 passiveBrowserEventsSupported = true;
5833 }
5834 });
5835 window.addEventListener('test', options, options);
5836 window.removeEventListener('test', options, options);
5837 } catch (e) {
5838 passiveBrowserEventsSupported = false;
5839 }
5840}
5841
5842// Intentionally not named imports because Rollup would use dynamic dispatch for
5843// CommonJS interop named imports.
5844var UserBlockingPriority$1 = unstable_UserBlockingPriority;
5845var runWithPriority$1 = unstable_runWithPriority;
5846var getEventPriority = SimpleEventPlugin.getEventPriority;
5847var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
5848var callbackBookkeepingPool = [];
5849
5850/**
5851 * Find the deepest React component completely containing the root of the
5852 * passed-in instance (for use when entire React trees are nested within each
5853 * other). If React trees are not nested, returns null.
5854 */
5855function findRootContainerNode(inst) {
5856 if (inst.tag === HostRoot) {
5857 return inst.stateNode.containerInfo;
5858 } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
5859 // traversal, but caching is difficult to do correctly without using a
5860 // mutation observer to listen for all DOM changes.
5861
5862
5863 while (inst.return) {
5864 inst = inst.return;
5865 }
5866
5867 if (inst.tag !== HostRoot) {
5868 // This can happen if we're in a detached tree.
5869 return null;
5870 }
5871
5872 return inst.stateNode.containerInfo;
5873} // Used to store ancestor hierarchy in top level callback
5874
5875
5876function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
5877 if (callbackBookkeepingPool.length) {
5878 var instance = callbackBookkeepingPool.pop();
5879 instance.topLevelType = topLevelType;
5880 instance.eventSystemFlags = eventSystemFlags;
5881 instance.nativeEvent = nativeEvent;
5882 instance.targetInst = targetInst;
5883 return instance;
5884 }
5885
5886 return {
5887 topLevelType: topLevelType,
5888 eventSystemFlags: eventSystemFlags,
5889 nativeEvent: nativeEvent,
5890 targetInst: targetInst,
5891 ancestors: []
5892 };
5893}
5894
5895function releaseTopLevelCallbackBookKeeping(instance) {
5896 instance.topLevelType = null;
5897 instance.nativeEvent = null;
5898 instance.targetInst = null;
5899 instance.ancestors.length = 0;
5900
5901 if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
5902 callbackBookkeepingPool.push(instance);
5903 }
5904}
5905
5906function handleTopLevel(bookKeeping) {
5907 var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
5908 // It's important that we build the array of ancestors before calling any
5909 // event handlers, because event handlers can modify the DOM, leading to
5910 // inconsistencies with ReactMount's node cache. See #1105.
5911
5912 var ancestor = targetInst;
5913
5914 do {
5915 if (!ancestor) {
5916 var ancestors = bookKeeping.ancestors;
5917 ancestors.push(ancestor);
5918 break;
5919 }
5920
5921 var root = findRootContainerNode(ancestor);
5922
5923 if (!root) {
5924 break;
5925 }
5926
5927 var tag = ancestor.tag;
5928
5929 if (tag === HostComponent || tag === HostText) {
5930 bookKeeping.ancestors.push(ancestor);
5931 }
5932
5933 ancestor = getClosestInstanceFromNode(root);
5934 } while (ancestor);
5935
5936 for (var i = 0; i < bookKeeping.ancestors.length; i++) {
5937 targetInst = bookKeeping.ancestors[i];
5938 var eventTarget = getEventTarget(bookKeeping.nativeEvent);
5939 var topLevelType = bookKeeping.topLevelType;
5940 var nativeEvent = bookKeeping.nativeEvent;
5941 runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, bookKeeping.eventSystemFlags);
5942 }
5943} // TODO: can we stop exporting these?
5944
5945
5946var _enabled = true;
5947function setEnabled(enabled) {
5948 _enabled = !!enabled;
5949}
5950function isEnabled() {
5951 return _enabled;
5952}
5953function trapBubbledEvent(topLevelType, element) {
5954 trapEventForPluginEventSystem(element, topLevelType, false);
5955}
5956function trapCapturedEvent(topLevelType, element) {
5957 trapEventForPluginEventSystem(element, topLevelType, true);
5958}
5959function trapEventForResponderEventSystem(element, topLevelType, passive) {
5960 if (enableFlareAPI) {
5961 var rawEventName = getRawEventName(topLevelType);
5962 var eventFlags = RESPONDER_EVENT_SYSTEM; // If passive option is not supported, then the event will be
5963 // active and not passive, but we flag it as using not being
5964 // supported too. This way the responder event plugins know,
5965 // and can provide polyfills if needed.
5966
5967 if (passive) {
5968 if (passiveBrowserEventsSupported) {
5969 eventFlags |= IS_PASSIVE;
5970 } else {
5971 eventFlags |= IS_ACTIVE;
5972 eventFlags |= PASSIVE_NOT_SUPPORTED;
5973 passive = false;
5974 }
5975 } else {
5976 eventFlags |= IS_ACTIVE;
5977 } // Check if interactive and wrap in discreteUpdates
5978
5979
5980 var listener = dispatchEvent.bind(null, topLevelType, eventFlags);
5981
5982 if (passiveBrowserEventsSupported) {
5983 addEventCaptureListenerWithPassiveFlag(element, rawEventName, listener, passive);
5984 } else {
5985 addEventCaptureListener(element, rawEventName, listener);
5986 }
5987 }
5988}
5989
5990function trapEventForPluginEventSystem(element, topLevelType, capture) {
5991 var listener;
5992
5993 switch (getEventPriority(topLevelType)) {
5994 case DiscreteEvent:
5995 listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
5996 break;
5997
5998 case UserBlockingEvent:
5999 listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
6000 break;
6001
6002 case ContinuousEvent:
6003 default:
6004 listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM);
6005 break;
6006 }
6007
6008 var rawEventName = getRawEventName(topLevelType);
6009
6010 if (capture) {
6011 addEventCaptureListener(element, rawEventName, listener);
6012 } else {
6013 addEventBubbleListener(element, rawEventName, listener);
6014 }
6015}
6016
6017function dispatchDiscreteEvent(topLevelType, eventSystemFlags, nativeEvent) {
6018 flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
6019 discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, nativeEvent);
6020}
6021
6022function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, nativeEvent) {
6023 runWithPriority$1(UserBlockingPriority$1, dispatchEvent.bind(null, topLevelType, eventSystemFlags, nativeEvent));
6024}
6025
6026function dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
6027 var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
6028
6029 try {
6030 // Event queue being processed in the same cycle allows
6031 // `preventDefault`.
6032 batchedEventUpdates(handleTopLevel, bookKeeping);
6033 } finally {
6034 releaseTopLevelCallbackBookKeeping(bookKeeping);
6035 }
6036}
6037
6038function dispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
6039 if (!_enabled) {
6040 return;
6041 }
6042
6043 if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
6044 // If we already have a queue of discrete events, and this is another discrete
6045 // event, then we can't dispatch it regardless of its target, since they
6046 // need to dispatch in order.
6047 queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
6048 topLevelType, eventSystemFlags, nativeEvent);
6049 return;
6050 }
6051
6052 var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent);
6053
6054 if (blockedOn === null) {
6055 // We successfully dispatched this event.
6056 clearIfContinuousEvent(topLevelType, nativeEvent);
6057 return;
6058 }
6059
6060 if (isReplayableDiscreteEvent(topLevelType)) {
6061 // This this to be replayed later once the target is available.
6062 queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent);
6063 return;
6064 }
6065
6066 if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, nativeEvent)) {
6067 return;
6068 } // We need to clear only if we didn't queue because
6069 // queueing is accummulative.
6070
6071
6072 clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
6073 // in case the event system needs to trace it.
6074
6075 if (enableFlareAPI) {
6076 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6077 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
6078 }
6079
6080 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6081 // React Flare event system
6082 dispatchEventForResponderEventSystem(topLevelType, null, nativeEvent, getEventTarget(nativeEvent), eventSystemFlags);
6083 }
6084 } else {
6085 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
6086 }
6087} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
6088
6089function attemptToDispatchEvent(topLevelType, eventSystemFlags, nativeEvent) {
6090 // TODO: Warn if _enabled is false.
6091 var nativeEventTarget = getEventTarget(nativeEvent);
6092 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
6093
6094 if (targetInst !== null) {
6095 var nearestMounted = getNearestMountedFiber(targetInst);
6096
6097 if (nearestMounted === null) {
6098 // This tree has been unmounted already. Dispatch without a target.
6099 targetInst = null;
6100 } else {
6101 var tag = nearestMounted.tag;
6102
6103 if (tag === SuspenseComponent) {
6104 var instance = getSuspenseInstanceFromFiber(nearestMounted);
6105
6106 if (instance !== null) {
6107 // Queue the event to be replayed later. Abort dispatching since we
6108 // don't want this event dispatched twice through the event system.
6109 // TODO: If this is the first discrete event in the queue. Schedule an increased
6110 // priority for this boundary.
6111 return instance;
6112 } // This shouldn't happen, something went wrong but to avoid blocking
6113 // the whole system, dispatch the event without a target.
6114 // TODO: Warn.
6115
6116
6117 targetInst = null;
6118 } else if (tag === HostRoot) {
6119 var root = nearestMounted.stateNode;
6120
6121 if (root.hydrate) {
6122 // If this happens during a replay something went wrong and it might block
6123 // the whole system.
6124 return getContainerFromFiber(nearestMounted);
6125 }
6126
6127 targetInst = null;
6128 } else if (nearestMounted !== targetInst) {
6129 // If we get an event (ex: img onload) before committing that
6130 // component's mount, ignore it for now (that is, treat it as if it was an
6131 // event on a non-React tree). We might also consider queueing events and
6132 // dispatching them after the mount.
6133 targetInst = null;
6134 }
6135 }
6136 }
6137
6138 if (enableFlareAPI) {
6139 if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) {
6140 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6141 }
6142
6143 if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) {
6144 // React Flare event system
6145 dispatchEventForResponderEventSystem(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
6146 }
6147 } else {
6148 dispatchEventForPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
6149 } // We're not blocked on anything.
6150
6151
6152 return null;
6153}
6154
6155/**
6156 * Checks if an event is supported in the current execution environment.
6157 *
6158 * NOTE: This will not work correctly for non-generic events such as `change`,
6159 * `reset`, `load`, `error`, and `select`.
6160 *
6161 * Borrows from Modernizr.
6162 *
6163 * @param {string} eventNameSuffix Event name, e.g. "click".
6164 * @return {boolean} True if the event is supported.
6165 * @internal
6166 * @license Modernizr 3.0.0pre (Custom Build) | MIT
6167 */
6168
6169function isEventSupported(eventNameSuffix) {
6170 if (!canUseDOM) {
6171 return false;
6172 }
6173
6174 var eventName = 'on' + eventNameSuffix;
6175 var isSupported = eventName in document;
6176
6177 if (!isSupported) {
6178 var element = document.createElement('div');
6179 element.setAttribute(eventName, 'return;');
6180 isSupported = typeof element[eventName] === 'function';
6181 }
6182
6183 return isSupported;
6184}
6185
6186/**
6187 * Summary of `ReactBrowserEventEmitter` event handling:
6188 *
6189 * - Top-level delegation is used to trap most native browser events. This
6190 * may only occur in the main thread and is the responsibility of
6191 * ReactDOMEventListener, which is injected and can therefore support
6192 * pluggable event sources. This is the only work that occurs in the main
6193 * thread.
6194 *
6195 * - We normalize and de-duplicate events to account for browser quirks. This
6196 * may be done in the worker thread.
6197 *
6198 * - Forward these native events (with the associated top-level type used to
6199 * trap it) to `EventPluginHub`, which in turn will ask plugins if they want
6200 * to extract any synthetic events.
6201 *
6202 * - The `EventPluginHub` will then process each event by annotating them with
6203 * "dispatches", a sequence of listeners and IDs that care about that event.
6204 *
6205 * - The `EventPluginHub` then dispatches the events.
6206 *
6207 * Overview of React and the event system:
6208 *
6209 * +------------+ .
6210 * | DOM | .
6211 * +------------+ .
6212 * | .
6213 * v .
6214 * +------------+ .
6215 * | ReactEvent | .
6216 * | Listener | .
6217 * +------------+ . +-----------+
6218 * | . +--------+|SimpleEvent|
6219 * | . | |Plugin |
6220 * +-----|------+ . v +-----------+
6221 * | | | . +--------------+ +------------+
6222 * | +-----------.--->|EventPluginHub| | Event |
6223 * | | . | | +-----------+ | Propagators|
6224 * | ReactEvent | . | | |TapEvent | |------------|
6225 * | Emitter | . | |<---+|Plugin | |other plugin|
6226 * | | . | | +-----------+ | utilities |
6227 * | +-----------.--->| | +------------+
6228 * | | | . +--------------+
6229 * +-----|------+ . ^ +-----------+
6230 * | . | |Enter/Leave|
6231 * + . +-------+|Plugin |
6232 * +-------------+ . +-----------+
6233 * | application | .
6234 * |-------------| .
6235 * | | .
6236 * | | .
6237 * +-------------+ .
6238 * .
6239 * React Core . General Purpose Event Plugin System
6240 */
6241
6242var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
6243var elementListeningSets = new PossiblyWeakMap();
6244function getListeningSetForElement(element) {
6245 var listeningSet = elementListeningSets.get(element);
6246
6247 if (listeningSet === undefined) {
6248 listeningSet = new Set();
6249 elementListeningSets.set(element, listeningSet);
6250 }
6251
6252 return listeningSet;
6253}
6254/**
6255 * We listen for bubbled touch events on the document object.
6256 *
6257 * Firefox v8.01 (and possibly others) exhibited strange behavior when
6258 * mounting `onmousemove` events at some node that was not the document
6259 * element. The symptoms were that if your mouse is not moving over something
6260 * contained within that mount point (for example on the background) the
6261 * top-level listeners for `onmousemove` won't be called. However, if you
6262 * register the `mousemove` on the document object, then it will of course
6263 * catch all `mousemove`s. This along with iOS quirks, justifies restricting
6264 * top-level listeners to the document object only, at least for these
6265 * movement types of events and possibly all events.
6266 *
6267 * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
6268 *
6269 * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
6270 * they bubble to document.
6271 *
6272 * @param {string} registrationName Name of listener (e.g. `onClick`).
6273 * @param {object} mountAt Container where to mount the listener
6274 */
6275
6276function listenTo(registrationName, mountAt) {
6277 var listeningSet = getListeningSetForElement(mountAt);
6278 var dependencies = registrationNameDependencies[registrationName];
6279
6280 for (var i = 0; i < dependencies.length; i++) {
6281 var dependency = dependencies[i];
6282 listenToTopLevel(dependency, mountAt, listeningSet);
6283 }
6284}
6285function listenToTopLevel(topLevelType, mountAt, listeningSet) {
6286 if (!listeningSet.has(topLevelType)) {
6287 switch (topLevelType) {
6288 case TOP_SCROLL:
6289 trapCapturedEvent(TOP_SCROLL, mountAt);
6290 break;
6291
6292 case TOP_FOCUS:
6293 case TOP_BLUR:
6294 trapCapturedEvent(TOP_FOCUS, mountAt);
6295 trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
6296 // but this ensures we mark both as attached rather than just one.
6297
6298 listeningSet.add(TOP_BLUR);
6299 listeningSet.add(TOP_FOCUS);
6300 break;
6301
6302 case TOP_CANCEL:
6303 case TOP_CLOSE:
6304 if (isEventSupported(getRawEventName(topLevelType))) {
6305 trapCapturedEvent(topLevelType, mountAt);
6306 }
6307
6308 break;
6309
6310 case TOP_INVALID:
6311 case TOP_SUBMIT:
6312 case TOP_RESET:
6313 // We listen to them on the target DOM elements.
6314 // Some of them bubble so we don't want them to fire twice.
6315 break;
6316
6317 default:
6318 // By default, listen on the top level to all non-media events.
6319 // Media events don't bubble so adding the listener wouldn't do anything.
6320 var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;
6321
6322 if (!isMediaEvent) {
6323 trapBubbledEvent(topLevelType, mountAt);
6324 }
6325
6326 break;
6327 }
6328
6329 listeningSet.add(topLevelType);
6330 }
6331}
6332function isListeningToAllDependencies(registrationName, mountAt) {
6333 var listeningSet = getListeningSetForElement(mountAt);
6334 var dependencies = registrationNameDependencies[registrationName];
6335
6336 for (var i = 0; i < dependencies.length; i++) {
6337 var dependency = dependencies[i];
6338
6339 if (!listeningSet.has(dependency)) {
6340 return false;
6341 }
6342 }
6343
6344 return true;
6345}
6346
6347// List derived from Gecko source code:
6348// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
6349var shorthandToLonghand = {
6350 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
6351 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
6352 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
6353 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6354 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
6355 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
6356 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
6357 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
6358 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
6359 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
6360 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
6361 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
6362 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
6363 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
6364 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
6365 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
6366 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
6367 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
6368 columns: ['columnCount', 'columnWidth'],
6369 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
6370 flexFlow: ['flexDirection', 'flexWrap'],
6371 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
6372 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
6373 gap: ['columnGap', 'rowGap'],
6374 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6375 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
6376 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
6377 gridColumnGap: ['columnGap'],
6378 gridGap: ['columnGap', 'rowGap'],
6379 gridRow: ['gridRowEnd', 'gridRowStart'],
6380 gridRowGap: ['rowGap'],
6381 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
6382 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
6383 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
6384 marker: ['markerEnd', 'markerMid', 'markerStart'],
6385 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
6386 maskPosition: ['maskPositionX', 'maskPositionY'],
6387 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
6388 overflow: ['overflowX', 'overflowY'],
6389 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
6390 placeContent: ['alignContent', 'justifyContent'],
6391 placeItems: ['alignItems', 'justifyItems'],
6392 placeSelf: ['alignSelf', 'justifySelf'],
6393 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
6394 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
6395 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
6396 wordWrap: ['overflowWrap']
6397};
6398
6399/**
6400 * CSS properties which accept numbers but are not in units of "px".
6401 */
6402var isUnitlessNumber = {
6403 animationIterationCount: true,
6404 borderImageOutset: true,
6405 borderImageSlice: true,
6406 borderImageWidth: true,
6407 boxFlex: true,
6408 boxFlexGroup: true,
6409 boxOrdinalGroup: true,
6410 columnCount: true,
6411 columns: true,
6412 flex: true,
6413 flexGrow: true,
6414 flexPositive: true,
6415 flexShrink: true,
6416 flexNegative: true,
6417 flexOrder: true,
6418 gridArea: true,
6419 gridRow: true,
6420 gridRowEnd: true,
6421 gridRowSpan: true,
6422 gridRowStart: true,
6423 gridColumn: true,
6424 gridColumnEnd: true,
6425 gridColumnSpan: true,
6426 gridColumnStart: true,
6427 fontWeight: true,
6428 lineClamp: true,
6429 lineHeight: true,
6430 opacity: true,
6431 order: true,
6432 orphans: true,
6433 tabSize: true,
6434 widows: true,
6435 zIndex: true,
6436 zoom: true,
6437 // SVG-related properties
6438 fillOpacity: true,
6439 floodOpacity: true,
6440 stopOpacity: true,
6441 strokeDasharray: true,
6442 strokeDashoffset: true,
6443 strokeMiterlimit: true,
6444 strokeOpacity: true,
6445 strokeWidth: true
6446};
6447/**
6448 * @param {string} prefix vendor-specific prefix, eg: Webkit
6449 * @param {string} key style name, eg: transitionDuration
6450 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
6451 * WebkitTransitionDuration
6452 */
6453
6454function prefixKey(prefix, key) {
6455 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
6456}
6457/**
6458 * Support style names that may come passed in prefixed by adding permutations
6459 * of vendor prefixes.
6460 */
6461
6462
6463var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
6464// infinite loop, because it iterates over the newly added props too.
6465
6466Object.keys(isUnitlessNumber).forEach(function (prop) {
6467 prefixes.forEach(function (prefix) {
6468 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
6469 });
6470});
6471
6472/**
6473 * Convert a value into the proper css writable value. The style name `name`
6474 * should be logical (no hyphens), as specified
6475 * in `CSSProperty.isUnitlessNumber`.
6476 *
6477 * @param {string} name CSS property name such as `topMargin`.
6478 * @param {*} value CSS property value such as `10px`.
6479 * @return {string} Normalized style value with dimensions applied.
6480 */
6481
6482function dangerousStyleValue(name, value, isCustomProperty) {
6483 // Note that we've removed escapeTextForBrowser() calls here since the
6484 // whole string will be escaped when the attribute is injected into
6485 // the markup. If you provide unsafe user data here they can inject
6486 // arbitrary CSS which may be problematic (I couldn't repro this):
6487 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
6488 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
6489 // This is not an XSS hole but instead a potential CSS injection issue
6490 // which has lead to a greater discussion about how we're going to
6491 // trust URLs moving forward. See #2115901
6492 var isEmpty = value == null || typeof value === 'boolean' || value === '';
6493
6494 if (isEmpty) {
6495 return '';
6496 }
6497
6498 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
6499 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
6500 }
6501
6502 return ('' + value).trim();
6503}
6504
6505var uppercasePattern = /([A-Z])/g;
6506var msPattern = /^ms-/;
6507/**
6508 * Hyphenates a camelcased CSS property name, for example:
6509 *
6510 * > hyphenateStyleName('backgroundColor')
6511 * < "background-color"
6512 * > hyphenateStyleName('MozTransition')
6513 * < "-moz-transition"
6514 * > hyphenateStyleName('msTransition')
6515 * < "-ms-transition"
6516 *
6517 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
6518 * is converted to `-ms-`.
6519 */
6520
6521function hyphenateStyleName(name) {
6522 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
6523}
6524
6525var warnValidStyle = function () {};
6526
6527{
6528 // 'msTransform' is correct, but the other prefixes should be capitalized
6529 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
6530 var msPattern$1 = /^-ms-/;
6531 var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
6532
6533 var badStyleValueWithSemicolonPattern = /;\s*$/;
6534 var warnedStyleNames = {};
6535 var warnedStyleValues = {};
6536 var warnedForNaNValue = false;
6537 var warnedForInfinityValue = false;
6538
6539 var camelize = function (string) {
6540 return string.replace(hyphenPattern, function (_, character) {
6541 return character.toUpperCase();
6542 });
6543 };
6544
6545 var warnHyphenatedStyleName = function (name) {
6546 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6547 return;
6548 }
6549
6550 warnedStyleNames[name] = true;
6551 warning$1(false, 'Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
6552 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
6553 // is converted to lowercase `ms`.
6554 camelize(name.replace(msPattern$1, 'ms-')));
6555 };
6556
6557 var warnBadVendoredStyleName = function (name) {
6558 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
6559 return;
6560 }
6561
6562 warnedStyleNames[name] = true;
6563 warning$1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
6564 };
6565
6566 var warnStyleValueWithSemicolon = function (name, value) {
6567 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
6568 return;
6569 }
6570
6571 warnedStyleValues[value] = true;
6572 warning$1(false, "Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
6573 };
6574
6575 var warnStyleValueIsNaN = function (name, value) {
6576 if (warnedForNaNValue) {
6577 return;
6578 }
6579
6580 warnedForNaNValue = true;
6581 warning$1(false, '`NaN` is an invalid value for the `%s` css style property.', name);
6582 };
6583
6584 var warnStyleValueIsInfinity = function (name, value) {
6585 if (warnedForInfinityValue) {
6586 return;
6587 }
6588
6589 warnedForInfinityValue = true;
6590 warning$1(false, '`Infinity` is an invalid value for the `%s` css style property.', name);
6591 };
6592
6593 warnValidStyle = function (name, value) {
6594 if (name.indexOf('-') > -1) {
6595 warnHyphenatedStyleName(name);
6596 } else if (badVendoredStyleNamePattern.test(name)) {
6597 warnBadVendoredStyleName(name);
6598 } else if (badStyleValueWithSemicolonPattern.test(value)) {
6599 warnStyleValueWithSemicolon(name, value);
6600 }
6601
6602 if (typeof value === 'number') {
6603 if (isNaN(value)) {
6604 warnStyleValueIsNaN(name, value);
6605 } else if (!isFinite(value)) {
6606 warnStyleValueIsInfinity(name, value);
6607 }
6608 }
6609 };
6610}
6611
6612var warnValidStyle$1 = warnValidStyle;
6613
6614/**
6615 * Operations for dealing with CSS properties.
6616 */
6617
6618/**
6619 * This creates a string that is expected to be equivalent to the style
6620 * attribute generated by server-side rendering. It by-passes warnings and
6621 * security checks so it's not safe to use this value for anything other than
6622 * comparison. It is only used in DEV for SSR validation.
6623 */
6624
6625function createDangerousStringForStyles(styles) {
6626 {
6627 var serialized = '';
6628 var delimiter = '';
6629
6630 for (var styleName in styles) {
6631 if (!styles.hasOwnProperty(styleName)) {
6632 continue;
6633 }
6634
6635 var styleValue = styles[styleName];
6636
6637 if (styleValue != null) {
6638 var isCustomProperty = styleName.indexOf('--') === 0;
6639 serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
6640 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
6641 delimiter = ';';
6642 }
6643 }
6644
6645 return serialized || null;
6646 }
6647}
6648/**
6649 * Sets the value for multiple styles on a node. If a value is specified as
6650 * '' (empty string), the corresponding style property will be unset.
6651 *
6652 * @param {DOMElement} node
6653 * @param {object} styles
6654 */
6655
6656function setValueForStyles(node, styles) {
6657 var style = node.style;
6658
6659 for (var styleName in styles) {
6660 if (!styles.hasOwnProperty(styleName)) {
6661 continue;
6662 }
6663
6664 var isCustomProperty = styleName.indexOf('--') === 0;
6665
6666 {
6667 if (!isCustomProperty) {
6668 warnValidStyle$1(styleName, styles[styleName]);
6669 }
6670 }
6671
6672 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
6673
6674 if (styleName === 'float') {
6675 styleName = 'cssFloat';
6676 }
6677
6678 if (isCustomProperty) {
6679 style.setProperty(styleName, styleValue);
6680 } else {
6681 style[styleName] = styleValue;
6682 }
6683 }
6684}
6685
6686function isValueEmpty(value) {
6687 return value == null || typeof value === 'boolean' || value === '';
6688}
6689/**
6690 * Given {color: 'red', overflow: 'hidden'} returns {
6691 * color: 'color',
6692 * overflowX: 'overflow',
6693 * overflowY: 'overflow',
6694 * }. This can be read as "the overflowY property was set by the overflow
6695 * shorthand". That is, the values are the property that each was derived from.
6696 */
6697
6698
6699function expandShorthandMap(styles) {
6700 var expanded = {};
6701
6702 for (var key in styles) {
6703 var longhands = shorthandToLonghand[key] || [key];
6704
6705 for (var i = 0; i < longhands.length; i++) {
6706 expanded[longhands[i]] = key;
6707 }
6708 }
6709
6710 return expanded;
6711}
6712/**
6713 * When mixing shorthand and longhand property names, we warn during updates if
6714 * we expect an incorrect result to occur. In particular, we warn for:
6715 *
6716 * Updating a shorthand property (longhand gets overwritten):
6717 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
6718 * becomes .style.font = 'baz'
6719 * Removing a shorthand property (longhand gets lost too):
6720 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
6721 * becomes .style.font = ''
6722 * Removing a longhand property (should revert to shorthand; doesn't):
6723 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
6724 * becomes .style.fontVariant = ''
6725 */
6726
6727
6728function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
6729 if (!warnAboutShorthandPropertyCollision) {
6730 return;
6731 }
6732
6733 if (!nextStyles) {
6734 return;
6735 }
6736
6737 var expandedUpdates = expandShorthandMap(styleUpdates);
6738 var expandedStyles = expandShorthandMap(nextStyles);
6739 var warnedAbout = {};
6740
6741 for (var key in expandedUpdates) {
6742 var originalKey = expandedUpdates[key];
6743 var correctOriginalKey = expandedStyles[key];
6744
6745 if (correctOriginalKey && originalKey !== correctOriginalKey) {
6746 var warningKey = originalKey + ',' + correctOriginalKey;
6747
6748 if (warnedAbout[warningKey]) {
6749 continue;
6750 }
6751
6752 warnedAbout[warningKey] = true;
6753 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);
6754 }
6755 }
6756}
6757
6758// For HTML, certain tags should omit their close tag. We keep a whitelist for
6759// those special-case tags.
6760var omittedCloseTags = {
6761 area: true,
6762 base: true,
6763 br: true,
6764 col: true,
6765 embed: true,
6766 hr: true,
6767 img: true,
6768 input: true,
6769 keygen: true,
6770 link: true,
6771 meta: true,
6772 param: true,
6773 source: true,
6774 track: true,
6775 wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
6776
6777};
6778
6779// `omittedCloseTags` except that `menuitem` should still have its closing tag.
6780
6781var voidElementTags = _assign({
6782 menuitem: true
6783}, omittedCloseTags);
6784
6785// or add stack by default to invariants where possible.
6786
6787var HTML$1 = '__html';
6788var ReactDebugCurrentFrame$3 = null;
6789
6790{
6791 ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
6792}
6793
6794function assertValidProps(tag, props) {
6795 if (!props) {
6796 return;
6797 } // Note the use of `==` which checks for null or undefined.
6798
6799
6800 if (voidElementTags[tag]) {
6801 if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
6802 {
6803 throw Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + (ReactDebugCurrentFrame$3.getStackAddendum()));
6804 }
6805 }
6806 }
6807
6808 if (props.dangerouslySetInnerHTML != null) {
6809 if (!(props.children == null)) {
6810 {
6811 throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
6812 }
6813 }
6814
6815 if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML$1 in props.dangerouslySetInnerHTML)) {
6816 {
6817 throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.");
6818 }
6819 }
6820 }
6821
6822 {
6823 !(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;
6824 }
6825
6826 if (!(props.style == null || typeof props.style === 'object')) {
6827 {
6828 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()));
6829 }
6830 }
6831}
6832
6833function isCustomComponent(tagName, props) {
6834 if (tagName.indexOf('-') === -1) {
6835 return typeof props.is === 'string';
6836 }
6837
6838 switch (tagName) {
6839 // These are reserved SVG and MathML elements.
6840 // We don't mind this whitelist too much because we expect it to never grow.
6841 // The alternative is to track the namespace in a few places which is convoluted.
6842 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
6843 case 'annotation-xml':
6844 case 'color-profile':
6845 case 'font-face':
6846 case 'font-face-src':
6847 case 'font-face-uri':
6848 case 'font-face-format':
6849 case 'font-face-name':
6850 case 'missing-glyph':
6851 return false;
6852
6853 default:
6854 return true;
6855 }
6856}
6857
6858// When adding attributes to the HTML or SVG whitelist, be sure to
6859// also add them to this module to ensure casing and incorrect name
6860// warnings.
6861var possibleStandardNames = {
6862 // HTML
6863 accept: 'accept',
6864 acceptcharset: 'acceptCharset',
6865 'accept-charset': 'acceptCharset',
6866 accesskey: 'accessKey',
6867 action: 'action',
6868 allowfullscreen: 'allowFullScreen',
6869 alt: 'alt',
6870 as: 'as',
6871 async: 'async',
6872 autocapitalize: 'autoCapitalize',
6873 autocomplete: 'autoComplete',
6874 autocorrect: 'autoCorrect',
6875 autofocus: 'autoFocus',
6876 autoplay: 'autoPlay',
6877 autosave: 'autoSave',
6878 capture: 'capture',
6879 cellpadding: 'cellPadding',
6880 cellspacing: 'cellSpacing',
6881 challenge: 'challenge',
6882 charset: 'charSet',
6883 checked: 'checked',
6884 children: 'children',
6885 cite: 'cite',
6886 class: 'className',
6887 classid: 'classID',
6888 classname: 'className',
6889 cols: 'cols',
6890 colspan: 'colSpan',
6891 content: 'content',
6892 contenteditable: 'contentEditable',
6893 contextmenu: 'contextMenu',
6894 controls: 'controls',
6895 controlslist: 'controlsList',
6896 coords: 'coords',
6897 crossorigin: 'crossOrigin',
6898 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
6899 data: 'data',
6900 datetime: 'dateTime',
6901 default: 'default',
6902 defaultchecked: 'defaultChecked',
6903 defaultvalue: 'defaultValue',
6904 defer: 'defer',
6905 dir: 'dir',
6906 disabled: 'disabled',
6907 disablepictureinpicture: 'disablePictureInPicture',
6908 download: 'download',
6909 draggable: 'draggable',
6910 enctype: 'encType',
6911 for: 'htmlFor',
6912 form: 'form',
6913 formmethod: 'formMethod',
6914 formaction: 'formAction',
6915 formenctype: 'formEncType',
6916 formnovalidate: 'formNoValidate',
6917 formtarget: 'formTarget',
6918 frameborder: 'frameBorder',
6919 headers: 'headers',
6920 height: 'height',
6921 hidden: 'hidden',
6922 high: 'high',
6923 href: 'href',
6924 hreflang: 'hrefLang',
6925 htmlfor: 'htmlFor',
6926 httpequiv: 'httpEquiv',
6927 'http-equiv': 'httpEquiv',
6928 icon: 'icon',
6929 id: 'id',
6930 innerhtml: 'innerHTML',
6931 inputmode: 'inputMode',
6932 integrity: 'integrity',
6933 is: 'is',
6934 itemid: 'itemID',
6935 itemprop: 'itemProp',
6936 itemref: 'itemRef',
6937 itemscope: 'itemScope',
6938 itemtype: 'itemType',
6939 keyparams: 'keyParams',
6940 keytype: 'keyType',
6941 kind: 'kind',
6942 label: 'label',
6943 lang: 'lang',
6944 list: 'list',
6945 loop: 'loop',
6946 low: 'low',
6947 manifest: 'manifest',
6948 marginwidth: 'marginWidth',
6949 marginheight: 'marginHeight',
6950 max: 'max',
6951 maxlength: 'maxLength',
6952 media: 'media',
6953 mediagroup: 'mediaGroup',
6954 method: 'method',
6955 min: 'min',
6956 minlength: 'minLength',
6957 multiple: 'multiple',
6958 muted: 'muted',
6959 name: 'name',
6960 nomodule: 'noModule',
6961 nonce: 'nonce',
6962 novalidate: 'noValidate',
6963 open: 'open',
6964 optimum: 'optimum',
6965 pattern: 'pattern',
6966 placeholder: 'placeholder',
6967 playsinline: 'playsInline',
6968 poster: 'poster',
6969 preload: 'preload',
6970 profile: 'profile',
6971 radiogroup: 'radioGroup',
6972 readonly: 'readOnly',
6973 referrerpolicy: 'referrerPolicy',
6974 rel: 'rel',
6975 required: 'required',
6976 reversed: 'reversed',
6977 role: 'role',
6978 rows: 'rows',
6979 rowspan: 'rowSpan',
6980 sandbox: 'sandbox',
6981 scope: 'scope',
6982 scoped: 'scoped',
6983 scrolling: 'scrolling',
6984 seamless: 'seamless',
6985 selected: 'selected',
6986 shape: 'shape',
6987 size: 'size',
6988 sizes: 'sizes',
6989 span: 'span',
6990 spellcheck: 'spellCheck',
6991 src: 'src',
6992 srcdoc: 'srcDoc',
6993 srclang: 'srcLang',
6994 srcset: 'srcSet',
6995 start: 'start',
6996 step: 'step',
6997 style: 'style',
6998 summary: 'summary',
6999 tabindex: 'tabIndex',
7000 target: 'target',
7001 title: 'title',
7002 type: 'type',
7003 usemap: 'useMap',
7004 value: 'value',
7005 width: 'width',
7006 wmode: 'wmode',
7007 wrap: 'wrap',
7008 // SVG
7009 about: 'about',
7010 accentheight: 'accentHeight',
7011 'accent-height': 'accentHeight',
7012 accumulate: 'accumulate',
7013 additive: 'additive',
7014 alignmentbaseline: 'alignmentBaseline',
7015 'alignment-baseline': 'alignmentBaseline',
7016 allowreorder: 'allowReorder',
7017 alphabetic: 'alphabetic',
7018 amplitude: 'amplitude',
7019 arabicform: 'arabicForm',
7020 'arabic-form': 'arabicForm',
7021 ascent: 'ascent',
7022 attributename: 'attributeName',
7023 attributetype: 'attributeType',
7024 autoreverse: 'autoReverse',
7025 azimuth: 'azimuth',
7026 basefrequency: 'baseFrequency',
7027 baselineshift: 'baselineShift',
7028 'baseline-shift': 'baselineShift',
7029 baseprofile: 'baseProfile',
7030 bbox: 'bbox',
7031 begin: 'begin',
7032 bias: 'bias',
7033 by: 'by',
7034 calcmode: 'calcMode',
7035 capheight: 'capHeight',
7036 'cap-height': 'capHeight',
7037 clip: 'clip',
7038 clippath: 'clipPath',
7039 'clip-path': 'clipPath',
7040 clippathunits: 'clipPathUnits',
7041 cliprule: 'clipRule',
7042 'clip-rule': 'clipRule',
7043 color: 'color',
7044 colorinterpolation: 'colorInterpolation',
7045 'color-interpolation': 'colorInterpolation',
7046 colorinterpolationfilters: 'colorInterpolationFilters',
7047 'color-interpolation-filters': 'colorInterpolationFilters',
7048 colorprofile: 'colorProfile',
7049 'color-profile': 'colorProfile',
7050 colorrendering: 'colorRendering',
7051 'color-rendering': 'colorRendering',
7052 contentscripttype: 'contentScriptType',
7053 contentstyletype: 'contentStyleType',
7054 cursor: 'cursor',
7055 cx: 'cx',
7056 cy: 'cy',
7057 d: 'd',
7058 datatype: 'datatype',
7059 decelerate: 'decelerate',
7060 descent: 'descent',
7061 diffuseconstant: 'diffuseConstant',
7062 direction: 'direction',
7063 display: 'display',
7064 divisor: 'divisor',
7065 dominantbaseline: 'dominantBaseline',
7066 'dominant-baseline': 'dominantBaseline',
7067 dur: 'dur',
7068 dx: 'dx',
7069 dy: 'dy',
7070 edgemode: 'edgeMode',
7071 elevation: 'elevation',
7072 enablebackground: 'enableBackground',
7073 'enable-background': 'enableBackground',
7074 end: 'end',
7075 exponent: 'exponent',
7076 externalresourcesrequired: 'externalResourcesRequired',
7077 fill: 'fill',
7078 fillopacity: 'fillOpacity',
7079 'fill-opacity': 'fillOpacity',
7080 fillrule: 'fillRule',
7081 'fill-rule': 'fillRule',
7082 filter: 'filter',
7083 filterres: 'filterRes',
7084 filterunits: 'filterUnits',
7085 floodopacity: 'floodOpacity',
7086 'flood-opacity': 'floodOpacity',
7087 floodcolor: 'floodColor',
7088 'flood-color': 'floodColor',
7089 focusable: 'focusable',
7090 fontfamily: 'fontFamily',
7091 'font-family': 'fontFamily',
7092 fontsize: 'fontSize',
7093 'font-size': 'fontSize',
7094 fontsizeadjust: 'fontSizeAdjust',
7095 'font-size-adjust': 'fontSizeAdjust',
7096 fontstretch: 'fontStretch',
7097 'font-stretch': 'fontStretch',
7098 fontstyle: 'fontStyle',
7099 'font-style': 'fontStyle',
7100 fontvariant: 'fontVariant',
7101 'font-variant': 'fontVariant',
7102 fontweight: 'fontWeight',
7103 'font-weight': 'fontWeight',
7104 format: 'format',
7105 from: 'from',
7106 fx: 'fx',
7107 fy: 'fy',
7108 g1: 'g1',
7109 g2: 'g2',
7110 glyphname: 'glyphName',
7111 'glyph-name': 'glyphName',
7112 glyphorientationhorizontal: 'glyphOrientationHorizontal',
7113 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
7114 glyphorientationvertical: 'glyphOrientationVertical',
7115 'glyph-orientation-vertical': 'glyphOrientationVertical',
7116 glyphref: 'glyphRef',
7117 gradienttransform: 'gradientTransform',
7118 gradientunits: 'gradientUnits',
7119 hanging: 'hanging',
7120 horizadvx: 'horizAdvX',
7121 'horiz-adv-x': 'horizAdvX',
7122 horizoriginx: 'horizOriginX',
7123 'horiz-origin-x': 'horizOriginX',
7124 ideographic: 'ideographic',
7125 imagerendering: 'imageRendering',
7126 'image-rendering': 'imageRendering',
7127 in2: 'in2',
7128 in: 'in',
7129 inlist: 'inlist',
7130 intercept: 'intercept',
7131 k1: 'k1',
7132 k2: 'k2',
7133 k3: 'k3',
7134 k4: 'k4',
7135 k: 'k',
7136 kernelmatrix: 'kernelMatrix',
7137 kernelunitlength: 'kernelUnitLength',
7138 kerning: 'kerning',
7139 keypoints: 'keyPoints',
7140 keysplines: 'keySplines',
7141 keytimes: 'keyTimes',
7142 lengthadjust: 'lengthAdjust',
7143 letterspacing: 'letterSpacing',
7144 'letter-spacing': 'letterSpacing',
7145 lightingcolor: 'lightingColor',
7146 'lighting-color': 'lightingColor',
7147 limitingconeangle: 'limitingConeAngle',
7148 local: 'local',
7149 markerend: 'markerEnd',
7150 'marker-end': 'markerEnd',
7151 markerheight: 'markerHeight',
7152 markermid: 'markerMid',
7153 'marker-mid': 'markerMid',
7154 markerstart: 'markerStart',
7155 'marker-start': 'markerStart',
7156 markerunits: 'markerUnits',
7157 markerwidth: 'markerWidth',
7158 mask: 'mask',
7159 maskcontentunits: 'maskContentUnits',
7160 maskunits: 'maskUnits',
7161 mathematical: 'mathematical',
7162 mode: 'mode',
7163 numoctaves: 'numOctaves',
7164 offset: 'offset',
7165 opacity: 'opacity',
7166 operator: 'operator',
7167 order: 'order',
7168 orient: 'orient',
7169 orientation: 'orientation',
7170 origin: 'origin',
7171 overflow: 'overflow',
7172 overlineposition: 'overlinePosition',
7173 'overline-position': 'overlinePosition',
7174 overlinethickness: 'overlineThickness',
7175 'overline-thickness': 'overlineThickness',
7176 paintorder: 'paintOrder',
7177 'paint-order': 'paintOrder',
7178 panose1: 'panose1',
7179 'panose-1': 'panose1',
7180 pathlength: 'pathLength',
7181 patterncontentunits: 'patternContentUnits',
7182 patterntransform: 'patternTransform',
7183 patternunits: 'patternUnits',
7184 pointerevents: 'pointerEvents',
7185 'pointer-events': 'pointerEvents',
7186 points: 'points',
7187 pointsatx: 'pointsAtX',
7188 pointsaty: 'pointsAtY',
7189 pointsatz: 'pointsAtZ',
7190 prefix: 'prefix',
7191 preservealpha: 'preserveAlpha',
7192 preserveaspectratio: 'preserveAspectRatio',
7193 primitiveunits: 'primitiveUnits',
7194 property: 'property',
7195 r: 'r',
7196 radius: 'radius',
7197 refx: 'refX',
7198 refy: 'refY',
7199 renderingintent: 'renderingIntent',
7200 'rendering-intent': 'renderingIntent',
7201 repeatcount: 'repeatCount',
7202 repeatdur: 'repeatDur',
7203 requiredextensions: 'requiredExtensions',
7204 requiredfeatures: 'requiredFeatures',
7205 resource: 'resource',
7206 restart: 'restart',
7207 result: 'result',
7208 results: 'results',
7209 rotate: 'rotate',
7210 rx: 'rx',
7211 ry: 'ry',
7212 scale: 'scale',
7213 security: 'security',
7214 seed: 'seed',
7215 shaperendering: 'shapeRendering',
7216 'shape-rendering': 'shapeRendering',
7217 slope: 'slope',
7218 spacing: 'spacing',
7219 specularconstant: 'specularConstant',
7220 specularexponent: 'specularExponent',
7221 speed: 'speed',
7222 spreadmethod: 'spreadMethod',
7223 startoffset: 'startOffset',
7224 stddeviation: 'stdDeviation',
7225 stemh: 'stemh',
7226 stemv: 'stemv',
7227 stitchtiles: 'stitchTiles',
7228 stopcolor: 'stopColor',
7229 'stop-color': 'stopColor',
7230 stopopacity: 'stopOpacity',
7231 'stop-opacity': 'stopOpacity',
7232 strikethroughposition: 'strikethroughPosition',
7233 'strikethrough-position': 'strikethroughPosition',
7234 strikethroughthickness: 'strikethroughThickness',
7235 'strikethrough-thickness': 'strikethroughThickness',
7236 string: 'string',
7237 stroke: 'stroke',
7238 strokedasharray: 'strokeDasharray',
7239 'stroke-dasharray': 'strokeDasharray',
7240 strokedashoffset: 'strokeDashoffset',
7241 'stroke-dashoffset': 'strokeDashoffset',
7242 strokelinecap: 'strokeLinecap',
7243 'stroke-linecap': 'strokeLinecap',
7244 strokelinejoin: 'strokeLinejoin',
7245 'stroke-linejoin': 'strokeLinejoin',
7246 strokemiterlimit: 'strokeMiterlimit',
7247 'stroke-miterlimit': 'strokeMiterlimit',
7248 strokewidth: 'strokeWidth',
7249 'stroke-width': 'strokeWidth',
7250 strokeopacity: 'strokeOpacity',
7251 'stroke-opacity': 'strokeOpacity',
7252 suppresscontenteditablewarning: 'suppressContentEditableWarning',
7253 suppresshydrationwarning: 'suppressHydrationWarning',
7254 surfacescale: 'surfaceScale',
7255 systemlanguage: 'systemLanguage',
7256 tablevalues: 'tableValues',
7257 targetx: 'targetX',
7258 targety: 'targetY',
7259 textanchor: 'textAnchor',
7260 'text-anchor': 'textAnchor',
7261 textdecoration: 'textDecoration',
7262 'text-decoration': 'textDecoration',
7263 textlength: 'textLength',
7264 textrendering: 'textRendering',
7265 'text-rendering': 'textRendering',
7266 to: 'to',
7267 transform: 'transform',
7268 typeof: 'typeof',
7269 u1: 'u1',
7270 u2: 'u2',
7271 underlineposition: 'underlinePosition',
7272 'underline-position': 'underlinePosition',
7273 underlinethickness: 'underlineThickness',
7274 'underline-thickness': 'underlineThickness',
7275 unicode: 'unicode',
7276 unicodebidi: 'unicodeBidi',
7277 'unicode-bidi': 'unicodeBidi',
7278 unicoderange: 'unicodeRange',
7279 'unicode-range': 'unicodeRange',
7280 unitsperem: 'unitsPerEm',
7281 'units-per-em': 'unitsPerEm',
7282 unselectable: 'unselectable',
7283 valphabetic: 'vAlphabetic',
7284 'v-alphabetic': 'vAlphabetic',
7285 values: 'values',
7286 vectoreffect: 'vectorEffect',
7287 'vector-effect': 'vectorEffect',
7288 version: 'version',
7289 vertadvy: 'vertAdvY',
7290 'vert-adv-y': 'vertAdvY',
7291 vertoriginx: 'vertOriginX',
7292 'vert-origin-x': 'vertOriginX',
7293 vertoriginy: 'vertOriginY',
7294 'vert-origin-y': 'vertOriginY',
7295 vhanging: 'vHanging',
7296 'v-hanging': 'vHanging',
7297 videographic: 'vIdeographic',
7298 'v-ideographic': 'vIdeographic',
7299 viewbox: 'viewBox',
7300 viewtarget: 'viewTarget',
7301 visibility: 'visibility',
7302 vmathematical: 'vMathematical',
7303 'v-mathematical': 'vMathematical',
7304 vocab: 'vocab',
7305 widths: 'widths',
7306 wordspacing: 'wordSpacing',
7307 'word-spacing': 'wordSpacing',
7308 writingmode: 'writingMode',
7309 'writing-mode': 'writingMode',
7310 x1: 'x1',
7311 x2: 'x2',
7312 x: 'x',
7313 xchannelselector: 'xChannelSelector',
7314 xheight: 'xHeight',
7315 'x-height': 'xHeight',
7316 xlinkactuate: 'xlinkActuate',
7317 'xlink:actuate': 'xlinkActuate',
7318 xlinkarcrole: 'xlinkArcrole',
7319 'xlink:arcrole': 'xlinkArcrole',
7320 xlinkhref: 'xlinkHref',
7321 'xlink:href': 'xlinkHref',
7322 xlinkrole: 'xlinkRole',
7323 'xlink:role': 'xlinkRole',
7324 xlinkshow: 'xlinkShow',
7325 'xlink:show': 'xlinkShow',
7326 xlinktitle: 'xlinkTitle',
7327 'xlink:title': 'xlinkTitle',
7328 xlinktype: 'xlinkType',
7329 'xlink:type': 'xlinkType',
7330 xmlbase: 'xmlBase',
7331 'xml:base': 'xmlBase',
7332 xmllang: 'xmlLang',
7333 'xml:lang': 'xmlLang',
7334 xmlns: 'xmlns',
7335 'xml:space': 'xmlSpace',
7336 xmlnsxlink: 'xmlnsXlink',
7337 'xmlns:xlink': 'xmlnsXlink',
7338 xmlspace: 'xmlSpace',
7339 y1: 'y1',
7340 y2: 'y2',
7341 y: 'y',
7342 ychannelselector: 'yChannelSelector',
7343 z: 'z',
7344 zoomandpan: 'zoomAndPan'
7345};
7346
7347var ariaProperties = {
7348 'aria-current': 0,
7349 // state
7350 'aria-details': 0,
7351 'aria-disabled': 0,
7352 // state
7353 'aria-hidden': 0,
7354 // state
7355 'aria-invalid': 0,
7356 // state
7357 'aria-keyshortcuts': 0,
7358 'aria-label': 0,
7359 'aria-roledescription': 0,
7360 // Widget Attributes
7361 'aria-autocomplete': 0,
7362 'aria-checked': 0,
7363 'aria-expanded': 0,
7364 'aria-haspopup': 0,
7365 'aria-level': 0,
7366 'aria-modal': 0,
7367 'aria-multiline': 0,
7368 'aria-multiselectable': 0,
7369 'aria-orientation': 0,
7370 'aria-placeholder': 0,
7371 'aria-pressed': 0,
7372 'aria-readonly': 0,
7373 'aria-required': 0,
7374 'aria-selected': 0,
7375 'aria-sort': 0,
7376 'aria-valuemax': 0,
7377 'aria-valuemin': 0,
7378 'aria-valuenow': 0,
7379 'aria-valuetext': 0,
7380 // Live Region Attributes
7381 'aria-atomic': 0,
7382 'aria-busy': 0,
7383 'aria-live': 0,
7384 'aria-relevant': 0,
7385 // Drag-and-Drop Attributes
7386 'aria-dropeffect': 0,
7387 'aria-grabbed': 0,
7388 // Relationship Attributes
7389 'aria-activedescendant': 0,
7390 'aria-colcount': 0,
7391 'aria-colindex': 0,
7392 'aria-colspan': 0,
7393 'aria-controls': 0,
7394 'aria-describedby': 0,
7395 'aria-errormessage': 0,
7396 'aria-flowto': 0,
7397 'aria-labelledby': 0,
7398 'aria-owns': 0,
7399 'aria-posinset': 0,
7400 'aria-rowcount': 0,
7401 'aria-rowindex': 0,
7402 'aria-rowspan': 0,
7403 'aria-setsize': 0
7404};
7405
7406var warnedProperties = {};
7407var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7408var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7409var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
7410
7411function validateProperty(tagName, name) {
7412 if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
7413 return true;
7414 }
7415
7416 if (rARIACamel.test(name)) {
7417 var ariaName = 'aria-' + name.slice(4).toLowerCase();
7418 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7419 // DOM properties, then it is an invalid aria-* attribute.
7420
7421 if (correctName == null) {
7422 warning$1(false, 'Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
7423 warnedProperties[name] = true;
7424 return true;
7425 } // aria-* attributes should be lowercase; suggest the lowercase version.
7426
7427
7428 if (name !== correctName) {
7429 warning$1(false, 'Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
7430 warnedProperties[name] = true;
7431 return true;
7432 }
7433 }
7434
7435 if (rARIA.test(name)) {
7436 var lowerCasedName = name.toLowerCase();
7437 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
7438 // DOM properties, then it is an invalid aria-* attribute.
7439
7440 if (standardName == null) {
7441 warnedProperties[name] = true;
7442 return false;
7443 } // aria-* attributes should be lowercase; suggest the lowercase version.
7444
7445
7446 if (name !== standardName) {
7447 warning$1(false, 'Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
7448 warnedProperties[name] = true;
7449 return true;
7450 }
7451 }
7452
7453 return true;
7454}
7455
7456function warnInvalidARIAProps(type, props) {
7457 var invalidProps = [];
7458
7459 for (var key in props) {
7460 var isValid = validateProperty(type, key);
7461
7462 if (!isValid) {
7463 invalidProps.push(key);
7464 }
7465 }
7466
7467 var unknownPropString = invalidProps.map(function (prop) {
7468 return '`' + prop + '`';
7469 }).join(', ');
7470
7471 if (invalidProps.length === 1) {
7472 warning$1(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7473 } else if (invalidProps.length > 1) {
7474 warning$1(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
7475 }
7476}
7477
7478function validateProperties(type, props) {
7479 if (isCustomComponent(type, props)) {
7480 return;
7481 }
7482
7483 warnInvalidARIAProps(type, props);
7484}
7485
7486var didWarnValueNull = false;
7487function validateProperties$1(type, props) {
7488 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
7489 return;
7490 }
7491
7492 if (props != null && props.value === null && !didWarnValueNull) {
7493 didWarnValueNull = true;
7494
7495 if (type === 'select' && props.multiple) {
7496 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);
7497 } else {
7498 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);
7499 }
7500 }
7501}
7502
7503var validateProperty$1 = function () {};
7504
7505{
7506 var warnedProperties$1 = {};
7507 var _hasOwnProperty = Object.prototype.hasOwnProperty;
7508 var EVENT_NAME_REGEX = /^on./;
7509 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
7510 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
7511 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
7512
7513 validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
7514 if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
7515 return true;
7516 }
7517
7518 var lowerCasedName = name.toLowerCase();
7519
7520 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
7521 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.');
7522 warnedProperties$1[name] = true;
7523 return true;
7524 } // We can't rely on the event system being injected on the server.
7525
7526
7527 if (canUseEventSystem) {
7528 if (registrationNameModules.hasOwnProperty(name)) {
7529 return true;
7530 }
7531
7532 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
7533
7534 if (registrationName != null) {
7535 warning$1(false, 'Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
7536 warnedProperties$1[name] = true;
7537 return true;
7538 }
7539
7540 if (EVENT_NAME_REGEX.test(name)) {
7541 warning$1(false, 'Unknown event handler property `%s`. It will be ignored.', name);
7542 warnedProperties$1[name] = true;
7543 return true;
7544 }
7545 } else if (EVENT_NAME_REGEX.test(name)) {
7546 // If no event plugins have been injected, we are in a server environment.
7547 // So we can't tell if the event name is correct for sure, but we can filter
7548 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
7549 if (INVALID_EVENT_NAME_REGEX.test(name)) {
7550 warning$1(false, 'Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
7551 }
7552
7553 warnedProperties$1[name] = true;
7554 return true;
7555 } // Let the ARIA attribute hook validate ARIA attributes
7556
7557
7558 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
7559 return true;
7560 }
7561
7562 if (lowerCasedName === 'innerhtml') {
7563 warning$1(false, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
7564 warnedProperties$1[name] = true;
7565 return true;
7566 }
7567
7568 if (lowerCasedName === 'aria') {
7569 warning$1(false, 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
7570 warnedProperties$1[name] = true;
7571 return true;
7572 }
7573
7574 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
7575 warning$1(false, 'Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
7576 warnedProperties$1[name] = true;
7577 return true;
7578 }
7579
7580 if (typeof value === 'number' && isNaN(value)) {
7581 warning$1(false, 'Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
7582 warnedProperties$1[name] = true;
7583 return true;
7584 }
7585
7586 var propertyInfo = getPropertyInfo(name);
7587 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
7588
7589 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
7590 var standardName = possibleStandardNames[lowerCasedName];
7591
7592 if (standardName !== name) {
7593 warning$1(false, 'Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
7594 warnedProperties$1[name] = true;
7595 return true;
7596 }
7597 } else if (!isReserved && name !== lowerCasedName) {
7598 // Unknown attributes should have lowercase casing since that's how they
7599 // will be cased anyway with server rendering.
7600 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);
7601 warnedProperties$1[name] = true;
7602 return true;
7603 }
7604
7605 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7606 if (value) {
7607 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);
7608 } else {
7609 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);
7610 }
7611
7612 warnedProperties$1[name] = true;
7613 return true;
7614 } // Now that we've validated casing, do not validate
7615 // data types for reserved props
7616
7617
7618 if (isReserved) {
7619 return true;
7620 } // Warn when a known attribute is a bad type
7621
7622
7623 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
7624 warnedProperties$1[name] = true;
7625 return false;
7626 } // Warn when passing the strings 'false' or 'true' into a boolean prop
7627
7628
7629 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
7630 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);
7631 warnedProperties$1[name] = true;
7632 return true;
7633 }
7634
7635 return true;
7636 };
7637}
7638
7639var warnUnknownProperties = function (type, props, canUseEventSystem) {
7640 var unknownProps = [];
7641
7642 for (var key in props) {
7643 var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
7644
7645 if (!isValid) {
7646 unknownProps.push(key);
7647 }
7648 }
7649
7650 var unknownPropString = unknownProps.map(function (prop) {
7651 return '`' + prop + '`';
7652 }).join(', ');
7653
7654 if (unknownProps.length === 1) {
7655 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);
7656 } else if (unknownProps.length > 1) {
7657 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);
7658 }
7659};
7660
7661function validateProperties$2(type, props, canUseEventSystem) {
7662 if (isCustomComponent(type, props)) {
7663 return;
7664 }
7665
7666 warnUnknownProperties(type, props, canUseEventSystem);
7667}
7668
7669// TODO: direct imports like some-package/src/* are bad. Fix me.
7670var didWarnInvalidHydration = false;
7671var didWarnShadyDOM = false;
7672var didWarnScriptTags = false;
7673var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
7674var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
7675var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
7676var AUTOFOCUS = 'autoFocus';
7677var CHILDREN = 'children';
7678var STYLE$1 = 'style';
7679var HTML = '__html';
7680var LISTENERS = 'listeners';
7681var HTML_NAMESPACE = Namespaces.html;
7682var warnedUnknownTags;
7683var suppressHydrationWarning;
7684var validatePropertiesInDevelopment;
7685var warnForTextDifference;
7686var warnForPropDifference;
7687var warnForExtraAttributes;
7688var warnForInvalidEventListener;
7689var canDiffStyleForHydrationWarning;
7690var normalizeMarkupForTextOrAttribute;
7691var normalizeHTML;
7692
7693{
7694 warnedUnknownTags = {
7695 // Chrome is the only major browser not shipping <time>. But as of July
7696 // 2017 it intends to ship it due to widespread usage. We intentionally
7697 // *don't* warn for <time> even if it's unrecognized by Chrome because
7698 // it soon will be, and many apps have been using it anyway.
7699 time: true,
7700 // There are working polyfills for <dialog>. Let people use it.
7701 dialog: true,
7702 // Electron ships a custom <webview> tag to display external web content in
7703 // an isolated frame and process.
7704 // This tag is not present in non Electron environments such as JSDom which
7705 // is often used for testing purposes.
7706 // @see https://electronjs.org/docs/api/webview-tag
7707 webview: true
7708 };
7709
7710 validatePropertiesInDevelopment = function (type, props) {
7711 validateProperties(type, props);
7712 validateProperties$1(type, props);
7713 validateProperties$2(type, props,
7714 /* canUseEventSystem */
7715 true);
7716 }; // IE 11 parses & normalizes the style attribute as opposed to other
7717 // browsers. It adds spaces and sorts the properties in some
7718 // non-alphabetical order. Handling that would require sorting CSS
7719 // properties in the client & server versions or applying
7720 // `expectedStyle` to a temporary DOM node to read its `style` attribute
7721 // normalized. Since it only affects IE, we're skipping style warnings
7722 // in that browser completely in favor of doing all that work.
7723 // See https://github.com/facebook/react/issues/11807
7724
7725
7726 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
7727 // It also can turn \u0000 into \uFFFD inside attributes.
7728 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
7729 // If we have a mismatch, it might be caused by that.
7730 // We will still patch up in this case but not fire the warning.
7731
7732 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
7733 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
7734
7735 normalizeMarkupForTextOrAttribute = function (markup) {
7736 var markupString = typeof markup === 'string' ? markup : '' + markup;
7737 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
7738 };
7739
7740 warnForTextDifference = function (serverText, clientText) {
7741 if (didWarnInvalidHydration) {
7742 return;
7743 }
7744
7745 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
7746 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
7747
7748 if (normalizedServerText === normalizedClientText) {
7749 return;
7750 }
7751
7752 didWarnInvalidHydration = true;
7753 warningWithoutStack$1(false, 'Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
7754 };
7755
7756 warnForPropDifference = function (propName, serverValue, clientValue) {
7757 if (didWarnInvalidHydration) {
7758 return;
7759 }
7760
7761 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
7762 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
7763
7764 if (normalizedServerValue === normalizedClientValue) {
7765 return;
7766 }
7767
7768 didWarnInvalidHydration = true;
7769 warningWithoutStack$1(false, 'Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
7770 };
7771
7772 warnForExtraAttributes = function (attributeNames) {
7773 if (didWarnInvalidHydration) {
7774 return;
7775 }
7776
7777 didWarnInvalidHydration = true;
7778 var names = [];
7779 attributeNames.forEach(function (name) {
7780 names.push(name);
7781 });
7782 warningWithoutStack$1(false, 'Extra attributes from the server: %s', names);
7783 };
7784
7785 warnForInvalidEventListener = function (registrationName, listener) {
7786 if (listener === false) {
7787 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);
7788 } else {
7789 warning$1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
7790 }
7791 }; // Parse the HTML and read it back to normalize the HTML string so that it
7792 // can be used for comparison.
7793
7794
7795 normalizeHTML = function (parent, html) {
7796 // We could have created a separate document here to avoid
7797 // re-initializing custom elements if they exist. But this breaks
7798 // how <noscript> is being handled. So we use the same document.
7799 // See the discussion in https://github.com/facebook/react/pull/11157.
7800 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
7801 testElement.innerHTML = html;
7802 return testElement.innerHTML;
7803 };
7804}
7805
7806function ensureListeningTo(rootContainerElement, registrationName) {
7807 var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
7808 var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
7809 listenTo(registrationName, doc);
7810}
7811
7812function getOwnerDocumentFromRootContainer(rootContainerElement) {
7813 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
7814}
7815
7816function noop() {}
7817
7818function trapClickOnNonInteractiveElement(node) {
7819 // Mobile Safari does not fire properly bubble click events on
7820 // non-interactive elements, which means delegated click listeners do not
7821 // fire. The workaround for this bug involves attaching an empty click
7822 // listener on the target node.
7823 // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
7824 // Just set it using the onclick property so that we don't have to manage any
7825 // bookkeeping for it. Not sure if we need to clear it when the listener is
7826 // removed.
7827 // TODO: Only do this for the relevant Safaris maybe?
7828 node.onclick = noop;
7829}
7830
7831function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
7832 for (var propKey in nextProps) {
7833 if (!nextProps.hasOwnProperty(propKey)) {
7834 continue;
7835 }
7836
7837 var nextProp = nextProps[propKey];
7838
7839 if (propKey === STYLE$1) {
7840 {
7841 if (nextProp) {
7842 // Freeze the next style object so that we can assume it won't be
7843 // mutated. We have already warned for this in the past.
7844 Object.freeze(nextProp);
7845 }
7846 } // Relies on `updateStylesByID` not mutating `styleUpdates`.
7847
7848
7849 setValueForStyles(domElement, nextProp);
7850 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7851 var nextHtml = nextProp ? nextProp[HTML] : undefined;
7852
7853 if (nextHtml != null) {
7854 setInnerHTML(domElement, nextHtml);
7855 }
7856 } else if (propKey === CHILDREN) {
7857 if (typeof nextProp === 'string') {
7858 // Avoid setting initial textContent when the text is empty. In IE11 setting
7859 // textContent on a <textarea> will cause the placeholder to not
7860 // show within the <textarea> until it has been focused and blurred again.
7861 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
7862 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
7863
7864 if (canSetTextContent) {
7865 setTextContent(domElement, nextProp);
7866 }
7867 } else if (typeof nextProp === 'number') {
7868 setTextContent(domElement, '' + nextProp);
7869 }
7870 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
7871 } else if (propKey === AUTOFOCUS) {// We polyfill it separately on the client during commit.
7872 // We could have excluded it in the property list instead of
7873 // adding a special case here, but then it wouldn't be emitted
7874 // on server rendering (but we *do* want to emit it in SSR).
7875 } else if (registrationNameModules.hasOwnProperty(propKey)) {
7876 if (nextProp != null) {
7877 if (true && typeof nextProp !== 'function') {
7878 warnForInvalidEventListener(propKey, nextProp);
7879 }
7880
7881 ensureListeningTo(rootContainerElement, propKey);
7882 }
7883 } else if (nextProp != null) {
7884 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
7885 }
7886 }
7887}
7888
7889function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
7890 // TODO: Handle wasCustomComponentTag
7891 for (var i = 0; i < updatePayload.length; i += 2) {
7892 var propKey = updatePayload[i];
7893 var propValue = updatePayload[i + 1];
7894
7895 if (propKey === STYLE$1) {
7896 setValueForStyles(domElement, propValue);
7897 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
7898 setInnerHTML(domElement, propValue);
7899 } else if (propKey === CHILDREN) {
7900 setTextContent(domElement, propValue);
7901 } else {
7902 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
7903 }
7904 }
7905}
7906
7907function createElement(type, props, rootContainerElement, parentNamespace) {
7908 var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
7909 // tags get no namespace.
7910
7911 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
7912 var domElement;
7913 var namespaceURI = parentNamespace;
7914
7915 if (namespaceURI === HTML_NAMESPACE) {
7916 namespaceURI = getIntrinsicNamespace(type);
7917 }
7918
7919 if (namespaceURI === HTML_NAMESPACE) {
7920 {
7921 isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
7922 // allow <SVG> or <mATH>.
7923
7924 !(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;
7925 }
7926
7927 if (type === 'script') {
7928 // Create the script via .innerHTML so its "parser-inserted" flag is
7929 // set to true and it does not execute
7930 var div = ownerDocument.createElement('div');
7931
7932 {
7933 if (enableTrustedTypesIntegration && !didWarnScriptTags) {
7934 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).');
7935 didWarnScriptTags = true;
7936 }
7937 }
7938
7939 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
7940 // This is guaranteed to yield a script element.
7941
7942 var firstChild = div.firstChild;
7943 domElement = div.removeChild(firstChild);
7944 } else if (typeof props.is === 'string') {
7945 // $FlowIssue `createElement` should be updated for Web Components
7946 domElement = ownerDocument.createElement(type, {
7947 is: props.is
7948 });
7949 } else {
7950 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
7951 // See discussion in https://github.com/facebook/react/pull/6896
7952 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
7953 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
7954 // attributes on `select`s needs to be added before `option`s are inserted.
7955 // This prevents:
7956 // - a bug where the `select` does not scroll to the correct option because singular
7957 // `select` elements automatically pick the first item #13222
7958 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
7959 // See https://github.com/facebook/react/issues/13222
7960 // and https://github.com/facebook/react/issues/14239
7961
7962 if (type === 'select') {
7963 var node = domElement;
7964
7965 if (props.multiple) {
7966 node.multiple = true;
7967 } else if (props.size) {
7968 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
7969 // it is possible that no option is selected.
7970 //
7971 // This is only necessary when a select in "single selection mode".
7972 node.size = props.size;
7973 }
7974 }
7975 }
7976 } else {
7977 domElement = ownerDocument.createElementNS(namespaceURI, type);
7978 }
7979
7980 {
7981 if (namespaceURI === HTML_NAMESPACE) {
7982 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
7983 warnedUnknownTags[type] = true;
7984 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);
7985 }
7986 }
7987 }
7988
7989 return domElement;
7990}
7991function createTextNode(text, rootContainerElement) {
7992 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
7993}
7994function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
7995 var isCustomComponentTag = isCustomComponent(tag, rawProps);
7996
7997 {
7998 validatePropertiesInDevelopment(tag, rawProps);
7999
8000 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8001 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8002 didWarnShadyDOM = true;
8003 }
8004 } // TODO: Make sure that we check isMounted before firing any of these events.
8005
8006
8007 var props;
8008
8009 switch (tag) {
8010 case 'iframe':
8011 case 'object':
8012 case 'embed':
8013 trapBubbledEvent(TOP_LOAD, domElement);
8014 props = rawProps;
8015 break;
8016
8017 case 'video':
8018 case 'audio':
8019 // Create listener for each media event
8020 for (var i = 0; i < mediaEventTypes.length; i++) {
8021 trapBubbledEvent(mediaEventTypes[i], domElement);
8022 }
8023
8024 props = rawProps;
8025 break;
8026
8027 case 'source':
8028 trapBubbledEvent(TOP_ERROR, domElement);
8029 props = rawProps;
8030 break;
8031
8032 case 'img':
8033 case 'image':
8034 case 'link':
8035 trapBubbledEvent(TOP_ERROR, domElement);
8036 trapBubbledEvent(TOP_LOAD, domElement);
8037 props = rawProps;
8038 break;
8039
8040 case 'form':
8041 trapBubbledEvent(TOP_RESET, domElement);
8042 trapBubbledEvent(TOP_SUBMIT, domElement);
8043 props = rawProps;
8044 break;
8045
8046 case 'details':
8047 trapBubbledEvent(TOP_TOGGLE, domElement);
8048 props = rawProps;
8049 break;
8050
8051 case 'input':
8052 initWrapperState(domElement, rawProps);
8053 props = getHostProps(domElement, rawProps);
8054 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8055 // to onChange. Even if there is no listener.
8056
8057 ensureListeningTo(rootContainerElement, 'onChange');
8058 break;
8059
8060 case 'option':
8061 validateProps(domElement, rawProps);
8062 props = getHostProps$1(domElement, rawProps);
8063 break;
8064
8065 case 'select':
8066 initWrapperState$1(domElement, rawProps);
8067 props = getHostProps$2(domElement, rawProps);
8068 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8069 // to onChange. Even if there is no listener.
8070
8071 ensureListeningTo(rootContainerElement, 'onChange');
8072 break;
8073
8074 case 'textarea':
8075 initWrapperState$2(domElement, rawProps);
8076 props = getHostProps$3(domElement, rawProps);
8077 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8078 // to onChange. Even if there is no listener.
8079
8080 ensureListeningTo(rootContainerElement, 'onChange');
8081 break;
8082
8083 default:
8084 props = rawProps;
8085 }
8086
8087 assertValidProps(tag, props);
8088 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
8089
8090 switch (tag) {
8091 case 'input':
8092 // TODO: Make sure we check if this is still unmounted or do any clean
8093 // up necessary since we never stop tracking anymore.
8094 track(domElement);
8095 postMountWrapper(domElement, rawProps, false);
8096 break;
8097
8098 case 'textarea':
8099 // TODO: Make sure we check if this is still unmounted or do any clean
8100 // up necessary since we never stop tracking anymore.
8101 track(domElement);
8102 postMountWrapper$3(domElement, rawProps);
8103 break;
8104
8105 case 'option':
8106 postMountWrapper$1(domElement, rawProps);
8107 break;
8108
8109 case 'select':
8110 postMountWrapper$2(domElement, rawProps);
8111 break;
8112
8113 default:
8114 if (typeof props.onClick === 'function') {
8115 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8116 trapClickOnNonInteractiveElement(domElement);
8117 }
8118
8119 break;
8120 }
8121} // Calculate the diff between the two objects.
8122
8123function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
8124 {
8125 validatePropertiesInDevelopment(tag, nextRawProps);
8126 }
8127
8128 var updatePayload = null;
8129 var lastProps;
8130 var nextProps;
8131
8132 switch (tag) {
8133 case 'input':
8134 lastProps = getHostProps(domElement, lastRawProps);
8135 nextProps = getHostProps(domElement, nextRawProps);
8136 updatePayload = [];
8137 break;
8138
8139 case 'option':
8140 lastProps = getHostProps$1(domElement, lastRawProps);
8141 nextProps = getHostProps$1(domElement, nextRawProps);
8142 updatePayload = [];
8143 break;
8144
8145 case 'select':
8146 lastProps = getHostProps$2(domElement, lastRawProps);
8147 nextProps = getHostProps$2(domElement, nextRawProps);
8148 updatePayload = [];
8149 break;
8150
8151 case 'textarea':
8152 lastProps = getHostProps$3(domElement, lastRawProps);
8153 nextProps = getHostProps$3(domElement, nextRawProps);
8154 updatePayload = [];
8155 break;
8156
8157 default:
8158 lastProps = lastRawProps;
8159 nextProps = nextRawProps;
8160
8161 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
8162 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8163 trapClickOnNonInteractiveElement(domElement);
8164 }
8165
8166 break;
8167 }
8168
8169 assertValidProps(tag, nextProps);
8170 var propKey;
8171 var styleName;
8172 var styleUpdates = null;
8173
8174 for (propKey in lastProps) {
8175 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
8176 continue;
8177 }
8178
8179 if (propKey === STYLE$1) {
8180 var lastStyle = lastProps[propKey];
8181
8182 for (styleName in lastStyle) {
8183 if (lastStyle.hasOwnProperty(styleName)) {
8184 if (!styleUpdates) {
8185 styleUpdates = {};
8186 }
8187
8188 styleUpdates[styleName] = '';
8189 }
8190 }
8191 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {// Noop. This is handled by the clear text mechanism.
8192 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8193 } else if (propKey === AUTOFOCUS) {// Noop. It doesn't work on updates anyway.
8194 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8195 // This is a special case. If any listener updates we need to ensure
8196 // that the "current" fiber pointer gets updated so we need a commit
8197 // to update this element.
8198 if (!updatePayload) {
8199 updatePayload = [];
8200 }
8201 } else {
8202 // For all other deleted properties we add it to the queue. We use
8203 // the whitelist in the commit phase instead.
8204 (updatePayload = updatePayload || []).push(propKey, null);
8205 }
8206 }
8207
8208 for (propKey in nextProps) {
8209 var nextProp = nextProps[propKey];
8210 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
8211
8212 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
8213 continue;
8214 }
8215
8216 if (propKey === STYLE$1) {
8217 {
8218 if (nextProp) {
8219 // Freeze the next style object so that we can assume it won't be
8220 // mutated. We have already warned for this in the past.
8221 Object.freeze(nextProp);
8222 }
8223 }
8224
8225 if (lastProp) {
8226 // Unset styles on `lastProp` but not on `nextProp`.
8227 for (styleName in lastProp) {
8228 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
8229 if (!styleUpdates) {
8230 styleUpdates = {};
8231 }
8232
8233 styleUpdates[styleName] = '';
8234 }
8235 } // Update styles that changed since `lastProp`.
8236
8237
8238 for (styleName in nextProp) {
8239 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
8240 if (!styleUpdates) {
8241 styleUpdates = {};
8242 }
8243
8244 styleUpdates[styleName] = nextProp[styleName];
8245 }
8246 }
8247 } else {
8248 // Relies on `updateStylesByID` not mutating `styleUpdates`.
8249 if (!styleUpdates) {
8250 if (!updatePayload) {
8251 updatePayload = [];
8252 }
8253
8254 updatePayload.push(propKey, styleUpdates);
8255 }
8256
8257 styleUpdates = nextProp;
8258 }
8259 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8260 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8261 var lastHtml = lastProp ? lastProp[HTML] : undefined;
8262
8263 if (nextHtml != null) {
8264 if (lastHtml !== nextHtml) {
8265 (updatePayload = updatePayload || []).push(propKey, toStringOrTrustedType(nextHtml));
8266 }
8267 } else {// TODO: It might be too late to clear this if we have children
8268 // inserted already.
8269 }
8270 } else if (propKey === CHILDREN) {
8271 if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
8272 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
8273 }
8274 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1) {// Noop
8275 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8276 if (nextProp != null) {
8277 // We eagerly listen to this even though we haven't committed yet.
8278 if (true && typeof nextProp !== 'function') {
8279 warnForInvalidEventListener(propKey, nextProp);
8280 }
8281
8282 ensureListeningTo(rootContainerElement, propKey);
8283 }
8284
8285 if (!updatePayload && lastProp !== nextProp) {
8286 // This is a special case. If any listener updates we need to ensure
8287 // that the "current" props pointer gets updated so we need a commit
8288 // to update this element.
8289 updatePayload = [];
8290 }
8291 } else {
8292 // For any other property we always add it to the queue and then we
8293 // filter it out using the whitelist during the commit.
8294 (updatePayload = updatePayload || []).push(propKey, nextProp);
8295 }
8296 }
8297
8298 if (styleUpdates) {
8299 {
8300 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE$1]);
8301 }
8302
8303 (updatePayload = updatePayload || []).push(STYLE$1, styleUpdates);
8304 }
8305
8306 return updatePayload;
8307} // Apply the diff.
8308
8309function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
8310 // Update checked *before* name.
8311 // In the middle of an update, it is possible to have multiple checked.
8312 // When a checked radio tries to change name, browser makes another radio's checked false.
8313 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
8314 updateChecked(domElement, nextRawProps);
8315 }
8316
8317 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
8318 var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
8319
8320 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
8321 // changed.
8322
8323 switch (tag) {
8324 case 'input':
8325 // Update the wrapper around inputs *after* updating props. This has to
8326 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
8327 // raise warnings and prevent the new value from being assigned.
8328 updateWrapper(domElement, nextRawProps);
8329 break;
8330
8331 case 'textarea':
8332 updateWrapper$1(domElement, nextRawProps);
8333 break;
8334
8335 case 'select':
8336 // <select> value update needs to occur after <option> children
8337 // reconciliation
8338 postUpdateWrapper(domElement, nextRawProps);
8339 break;
8340 }
8341}
8342
8343function getPossibleStandardName(propName) {
8344 {
8345 var lowerCasedName = propName.toLowerCase();
8346
8347 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
8348 return null;
8349 }
8350
8351 return possibleStandardNames[lowerCasedName] || null;
8352 }
8353
8354 return null;
8355}
8356
8357function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
8358 var isCustomComponentTag;
8359 var extraAttributeNames;
8360
8361 {
8362 suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING$1] === true;
8363 isCustomComponentTag = isCustomComponent(tag, rawProps);
8364 validatePropertiesInDevelopment(tag, rawProps);
8365
8366 if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
8367 warning$1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
8368 didWarnShadyDOM = true;
8369 }
8370 } // TODO: Make sure that we check isMounted before firing any of these events.
8371
8372
8373 switch (tag) {
8374 case 'iframe':
8375 case 'object':
8376 case 'embed':
8377 trapBubbledEvent(TOP_LOAD, domElement);
8378 break;
8379
8380 case 'video':
8381 case 'audio':
8382 // Create listener for each media event
8383 for (var i = 0; i < mediaEventTypes.length; i++) {
8384 trapBubbledEvent(mediaEventTypes[i], domElement);
8385 }
8386
8387 break;
8388
8389 case 'source':
8390 trapBubbledEvent(TOP_ERROR, domElement);
8391 break;
8392
8393 case 'img':
8394 case 'image':
8395 case 'link':
8396 trapBubbledEvent(TOP_ERROR, domElement);
8397 trapBubbledEvent(TOP_LOAD, domElement);
8398 break;
8399
8400 case 'form':
8401 trapBubbledEvent(TOP_RESET, domElement);
8402 trapBubbledEvent(TOP_SUBMIT, domElement);
8403 break;
8404
8405 case 'details':
8406 trapBubbledEvent(TOP_TOGGLE, domElement);
8407 break;
8408
8409 case 'input':
8410 initWrapperState(domElement, rawProps);
8411 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8412 // to onChange. Even if there is no listener.
8413
8414 ensureListeningTo(rootContainerElement, 'onChange');
8415 break;
8416
8417 case 'option':
8418 validateProps(domElement, rawProps);
8419 break;
8420
8421 case 'select':
8422 initWrapperState$1(domElement, rawProps);
8423 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8424 // to onChange. Even if there is no listener.
8425
8426 ensureListeningTo(rootContainerElement, 'onChange');
8427 break;
8428
8429 case 'textarea':
8430 initWrapperState$2(domElement, rawProps);
8431 trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
8432 // to onChange. Even if there is no listener.
8433
8434 ensureListeningTo(rootContainerElement, 'onChange');
8435 break;
8436 }
8437
8438 assertValidProps(tag, rawProps);
8439
8440 {
8441 extraAttributeNames = new Set();
8442 var attributes = domElement.attributes;
8443
8444 for (var _i = 0; _i < attributes.length; _i++) {
8445 var name = attributes[_i].name.toLowerCase();
8446
8447 switch (name) {
8448 // Built-in SSR attribute is whitelisted
8449 case 'data-reactroot':
8450 break;
8451 // Controlled attributes are not validated
8452 // TODO: Only ignore them on controlled tags.
8453
8454 case 'value':
8455 break;
8456
8457 case 'checked':
8458 break;
8459
8460 case 'selected':
8461 break;
8462
8463 default:
8464 // Intentionally use the original name.
8465 // See discussion in https://github.com/facebook/react/pull/10676.
8466 extraAttributeNames.add(attributes[_i].name);
8467 }
8468 }
8469 }
8470
8471 var updatePayload = null;
8472
8473 for (var propKey in rawProps) {
8474 if (!rawProps.hasOwnProperty(propKey)) {
8475 continue;
8476 }
8477
8478 var nextProp = rawProps[propKey];
8479
8480 if (propKey === CHILDREN) {
8481 // For text content children we compare against textContent. This
8482 // might match additional HTML that is hidden when we read it using
8483 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
8484 // satisfies our requirement. Our requirement is not to produce perfect
8485 // HTML and attributes. Ideally we should preserve structure but it's
8486 // ok not to if the visible content is still enough to indicate what
8487 // even listeners these nodes might be wired up to.
8488 // TODO: Warn if there is more than a single textNode as a child.
8489 // TODO: Should we use domElement.firstChild.nodeValue to compare?
8490 if (typeof nextProp === 'string') {
8491 if (domElement.textContent !== nextProp) {
8492 if (true && !suppressHydrationWarning) {
8493 warnForTextDifference(domElement.textContent, nextProp);
8494 }
8495
8496 updatePayload = [CHILDREN, nextProp];
8497 }
8498 } else if (typeof nextProp === 'number') {
8499 if (domElement.textContent !== '' + nextProp) {
8500 if (true && !suppressHydrationWarning) {
8501 warnForTextDifference(domElement.textContent, nextProp);
8502 }
8503
8504 updatePayload = [CHILDREN, '' + nextProp];
8505 }
8506 }
8507 } else if (registrationNameModules.hasOwnProperty(propKey)) {
8508 if (nextProp != null) {
8509 if (true && typeof nextProp !== 'function') {
8510 warnForInvalidEventListener(propKey, nextProp);
8511 }
8512
8513 ensureListeningTo(rootContainerElement, propKey);
8514 }
8515 } else if (true && // Convince Flow we've calculated it (it's DEV-only in this method.)
8516 typeof isCustomComponentTag === 'boolean') {
8517 // Validate that the properties correspond to their expected values.
8518 var serverValue = void 0;
8519 var propertyInfo = getPropertyInfo(propKey);
8520
8521 if (suppressHydrationWarning) {// Don't bother comparing. We're ignoring all these warnings.
8522 } else if (enableFlareAPI && propKey === LISTENERS || propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 || // Controlled attributes are not validated
8523 // TODO: Only ignore them on controlled tags.
8524 propKey === 'value' || propKey === 'checked' || propKey === 'selected') {// Noop
8525 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
8526 var serverHTML = domElement.innerHTML;
8527 var nextHtml = nextProp ? nextProp[HTML] : undefined;
8528 var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
8529
8530 if (expectedHTML !== serverHTML) {
8531 warnForPropDifference(propKey, serverHTML, expectedHTML);
8532 }
8533 } else if (propKey === STYLE$1) {
8534 // $FlowFixMe - Should be inferred as not undefined.
8535 extraAttributeNames.delete(propKey);
8536
8537 if (canDiffStyleForHydrationWarning) {
8538 var expectedStyle = createDangerousStringForStyles(nextProp);
8539 serverValue = domElement.getAttribute('style');
8540
8541 if (expectedStyle !== serverValue) {
8542 warnForPropDifference(propKey, serverValue, expectedStyle);
8543 }
8544 }
8545 } else if (isCustomComponentTag) {
8546 // $FlowFixMe - Should be inferred as not undefined.
8547 extraAttributeNames.delete(propKey.toLowerCase());
8548 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8549
8550 if (nextProp !== serverValue) {
8551 warnForPropDifference(propKey, serverValue, nextProp);
8552 }
8553 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
8554 var isMismatchDueToBadCasing = false;
8555
8556 if (propertyInfo !== null) {
8557 // $FlowFixMe - Should be inferred as not undefined.
8558 extraAttributeNames.delete(propertyInfo.attributeName);
8559 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
8560 } else {
8561 var ownNamespace = parentNamespace;
8562
8563 if (ownNamespace === HTML_NAMESPACE) {
8564 ownNamespace = getIntrinsicNamespace(tag);
8565 }
8566
8567 if (ownNamespace === HTML_NAMESPACE) {
8568 // $FlowFixMe - Should be inferred as not undefined.
8569 extraAttributeNames.delete(propKey.toLowerCase());
8570 } else {
8571 var standardName = getPossibleStandardName(propKey);
8572
8573 if (standardName !== null && standardName !== propKey) {
8574 // If an SVG prop is supplied with bad casing, it will
8575 // be successfully parsed from HTML, but will produce a mismatch
8576 // (and would be incorrectly rendered on the client).
8577 // However, we already warn about bad casing elsewhere.
8578 // So we'll skip the misleading extra mismatch warning in this case.
8579 isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
8580
8581 extraAttributeNames.delete(standardName);
8582 } // $FlowFixMe - Should be inferred as not undefined.
8583
8584
8585 extraAttributeNames.delete(propKey);
8586 }
8587
8588 serverValue = getValueForAttribute(domElement, propKey, nextProp);
8589 }
8590
8591 if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
8592 warnForPropDifference(propKey, serverValue, nextProp);
8593 }
8594 }
8595 }
8596 }
8597
8598 {
8599 // $FlowFixMe - Should be inferred as not undefined.
8600 if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
8601 // $FlowFixMe - Should be inferred as not undefined.
8602 warnForExtraAttributes(extraAttributeNames);
8603 }
8604 }
8605
8606 switch (tag) {
8607 case 'input':
8608 // TODO: Make sure we check if this is still unmounted or do any clean
8609 // up necessary since we never stop tracking anymore.
8610 track(domElement);
8611 postMountWrapper(domElement, rawProps, true);
8612 break;
8613
8614 case 'textarea':
8615 // TODO: Make sure we check if this is still unmounted or do any clean
8616 // up necessary since we never stop tracking anymore.
8617 track(domElement);
8618 postMountWrapper$3(domElement, rawProps);
8619 break;
8620
8621 case 'select':
8622 case 'option':
8623 // For input and textarea we current always set the value property at
8624 // post mount to force it to diverge from attributes. However, for
8625 // option and select we don't quite do the same thing and select
8626 // is not resilient to the DOM state changing so we don't do that here.
8627 // TODO: Consider not doing this for input and textarea.
8628 break;
8629
8630 default:
8631 if (typeof rawProps.onClick === 'function') {
8632 // TODO: This cast may not be sound for SVG, MathML or custom elements.
8633 trapClickOnNonInteractiveElement(domElement);
8634 }
8635
8636 break;
8637 }
8638
8639 return updatePayload;
8640}
8641function diffHydratedText(textNode, text) {
8642 var isDifferent = textNode.nodeValue !== text;
8643 return isDifferent;
8644}
8645function warnForUnmatchedText(textNode, text) {
8646 {
8647 warnForTextDifference(textNode.nodeValue, text);
8648 }
8649}
8650function warnForDeletedHydratableElement(parentNode, child) {
8651 {
8652 if (didWarnInvalidHydration) {
8653 return;
8654 }
8655
8656 didWarnInvalidHydration = true;
8657 warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
8658 }
8659}
8660function warnForDeletedHydratableText(parentNode, child) {
8661 {
8662 if (didWarnInvalidHydration) {
8663 return;
8664 }
8665
8666 didWarnInvalidHydration = true;
8667 warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
8668 }
8669}
8670function warnForInsertedHydratedElement(parentNode, tag, props) {
8671 {
8672 if (didWarnInvalidHydration) {
8673 return;
8674 }
8675
8676 didWarnInvalidHydration = true;
8677 warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
8678 }
8679}
8680function warnForInsertedHydratedText(parentNode, text) {
8681 {
8682 if (text === '') {
8683 // We expect to insert empty text nodes since they're not represented in
8684 // the HTML.
8685 // TODO: Remove this special case if we can just avoid inserting empty
8686 // text nodes.
8687 return;
8688 }
8689
8690 if (didWarnInvalidHydration) {
8691 return;
8692 }
8693
8694 didWarnInvalidHydration = true;
8695 warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
8696 }
8697}
8698function restoreControlledState$$1(domElement, tag, props) {
8699 switch (tag) {
8700 case 'input':
8701 restoreControlledState$1(domElement, props);
8702 return;
8703
8704 case 'textarea':
8705 restoreControlledState$3(domElement, props);
8706 return;
8707
8708 case 'select':
8709 restoreControlledState$2(domElement, props);
8710 return;
8711 }
8712}
8713function listenToEventResponderEventTypes(eventTypes, element) {
8714 if (enableFlareAPI) {
8715 // Get the listening Set for this element. We use this to track
8716 // what events we're listening to.
8717 var listeningSet = getListeningSetForElement(element); // Go through each target event type of the event responder
8718
8719 for (var i = 0, length = eventTypes.length; i < length; ++i) {
8720 var eventType = eventTypes[i];
8721 var isPassive = !endsWith(eventType, '_active');
8722 var eventKey = isPassive ? eventType + '_passive' : eventType;
8723 var targetEventType = isPassive ? eventType : eventType.substring(0, eventType.length - 7);
8724
8725 if (!listeningSet.has(eventKey)) {
8726 trapEventForResponderEventSystem(element, targetEventType, isPassive);
8727 listeningSet.add(eventKey);
8728 }
8729 }
8730 }
8731} // We can remove this once the event API is stable and out of a flag
8732
8733if (enableFlareAPI) {
8734 setListenToResponderEventTypes(listenToEventResponderEventTypes);
8735}
8736
8737function getActiveElement(doc) {
8738 doc = doc || (typeof document !== 'undefined' ? document : undefined);
8739
8740 if (typeof doc === 'undefined') {
8741 return null;
8742 }
8743
8744 try {
8745 return doc.activeElement || doc.body;
8746 } catch (e) {
8747 return doc.body;
8748 }
8749}
8750
8751/**
8752 * Given any node return the first leaf node without children.
8753 *
8754 * @param {DOMElement|DOMTextNode} node
8755 * @return {DOMElement|DOMTextNode}
8756 */
8757
8758function getLeafNode(node) {
8759 while (node && node.firstChild) {
8760 node = node.firstChild;
8761 }
8762
8763 return node;
8764}
8765/**
8766 * Get the next sibling within a container. This will walk up the
8767 * DOM if a node's siblings have been exhausted.
8768 *
8769 * @param {DOMElement|DOMTextNode} node
8770 * @return {?DOMElement|DOMTextNode}
8771 */
8772
8773
8774function getSiblingNode(node) {
8775 while (node) {
8776 if (node.nextSibling) {
8777 return node.nextSibling;
8778 }
8779
8780 node = node.parentNode;
8781 }
8782}
8783/**
8784 * Get object describing the nodes which contain characters at offset.
8785 *
8786 * @param {DOMElement|DOMTextNode} root
8787 * @param {number} offset
8788 * @return {?object}
8789 */
8790
8791
8792function getNodeForCharacterOffset(root, offset) {
8793 var node = getLeafNode(root);
8794 var nodeStart = 0;
8795 var nodeEnd = 0;
8796
8797 while (node) {
8798 if (node.nodeType === TEXT_NODE) {
8799 nodeEnd = nodeStart + node.textContent.length;
8800
8801 if (nodeStart <= offset && nodeEnd >= offset) {
8802 return {
8803 node: node,
8804 offset: offset - nodeStart
8805 };
8806 }
8807
8808 nodeStart = nodeEnd;
8809 }
8810
8811 node = getLeafNode(getSiblingNode(node));
8812 }
8813}
8814
8815/**
8816 * @param {DOMElement} outerNode
8817 * @return {?object}
8818 */
8819
8820function getOffsets(outerNode) {
8821 var ownerDocument = outerNode.ownerDocument;
8822 var win = ownerDocument && ownerDocument.defaultView || window;
8823 var selection = win.getSelection && win.getSelection();
8824
8825 if (!selection || selection.rangeCount === 0) {
8826 return null;
8827 }
8828
8829 var anchorNode = selection.anchorNode,
8830 anchorOffset = selection.anchorOffset,
8831 focusNode = selection.focusNode,
8832 focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
8833 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
8834 // expose properties, triggering a "Permission denied error" if any of its
8835 // properties are accessed. The only seemingly possible way to avoid erroring
8836 // is to access a property that typically works for non-anonymous divs and
8837 // catch any error that may otherwise arise. See
8838 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
8839
8840 try {
8841 /* eslint-disable no-unused-expressions */
8842 anchorNode.nodeType;
8843 focusNode.nodeType;
8844 /* eslint-enable no-unused-expressions */
8845 } catch (e) {
8846 return null;
8847 }
8848
8849 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
8850}
8851/**
8852 * Returns {start, end} where `start` is the character/codepoint index of
8853 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
8854 * `end` is the index of (focusNode, focusOffset).
8855 *
8856 * Returns null if you pass in garbage input but we should probably just crash.
8857 *
8858 * Exported only for testing.
8859 */
8860
8861function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
8862 var length = 0;
8863 var start = -1;
8864 var end = -1;
8865 var indexWithinAnchor = 0;
8866 var indexWithinFocus = 0;
8867 var node = outerNode;
8868 var parentNode = null;
8869
8870 outer: while (true) {
8871 var next = null;
8872
8873 while (true) {
8874 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
8875 start = length + anchorOffset;
8876 }
8877
8878 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
8879 end = length + focusOffset;
8880 }
8881
8882 if (node.nodeType === TEXT_NODE) {
8883 length += node.nodeValue.length;
8884 }
8885
8886 if ((next = node.firstChild) === null) {
8887 break;
8888 } // Moving from `node` to its first child `next`.
8889
8890
8891 parentNode = node;
8892 node = next;
8893 }
8894
8895 while (true) {
8896 if (node === outerNode) {
8897 // If `outerNode` has children, this is always the second time visiting
8898 // it. If it has no children, this is still the first loop, and the only
8899 // valid selection is anchorNode and focusNode both equal to this node
8900 // and both offsets 0, in which case we will have handled above.
8901 break outer;
8902 }
8903
8904 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
8905 start = length;
8906 }
8907
8908 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
8909 end = length;
8910 }
8911
8912 if ((next = node.nextSibling) !== null) {
8913 break;
8914 }
8915
8916 node = parentNode;
8917 parentNode = node.parentNode;
8918 } // Moving from `node` to its next sibling `next`.
8919
8920
8921 node = next;
8922 }
8923
8924 if (start === -1 || end === -1) {
8925 // This should never happen. (Would happen if the anchor/focus nodes aren't
8926 // actually inside the passed-in node.)
8927 return null;
8928 }
8929
8930 return {
8931 start: start,
8932 end: end
8933 };
8934}
8935/**
8936 * In modern non-IE browsers, we can support both forward and backward
8937 * selections.
8938 *
8939 * Note: IE10+ supports the Selection object, but it does not support
8940 * the `extend` method, which means that even in modern IE, it's not possible
8941 * to programmatically create a backward selection. Thus, for all IE
8942 * versions, we use the old IE API to create our selections.
8943 *
8944 * @param {DOMElement|DOMTextNode} node
8945 * @param {object} offsets
8946 */
8947
8948function setOffsets(node, offsets) {
8949 var doc = node.ownerDocument || document;
8950 var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
8951 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
8952 // fails when pasting 100+ items)
8953
8954 if (!win.getSelection) {
8955 return;
8956 }
8957
8958 var selection = win.getSelection();
8959 var length = node.textContent.length;
8960 var start = Math.min(offsets.start, length);
8961 var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
8962 // Flip backward selections, so we can set with a single range.
8963
8964 if (!selection.extend && start > end) {
8965 var temp = end;
8966 end = start;
8967 start = temp;
8968 }
8969
8970 var startMarker = getNodeForCharacterOffset(node, start);
8971 var endMarker = getNodeForCharacterOffset(node, end);
8972
8973 if (startMarker && endMarker) {
8974 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
8975 return;
8976 }
8977
8978 var range = doc.createRange();
8979 range.setStart(startMarker.node, startMarker.offset);
8980 selection.removeAllRanges();
8981
8982 if (start > end) {
8983 selection.addRange(range);
8984 selection.extend(endMarker.node, endMarker.offset);
8985 } else {
8986 range.setEnd(endMarker.node, endMarker.offset);
8987 selection.addRange(range);
8988 }
8989 }
8990}
8991
8992function isTextNode(node) {
8993 return node && node.nodeType === TEXT_NODE;
8994}
8995
8996function containsNode(outerNode, innerNode) {
8997 if (!outerNode || !innerNode) {
8998 return false;
8999 } else if (outerNode === innerNode) {
9000 return true;
9001 } else if (isTextNode(outerNode)) {
9002 return false;
9003 } else if (isTextNode(innerNode)) {
9004 return containsNode(outerNode, innerNode.parentNode);
9005 } else if ('contains' in outerNode) {
9006 return outerNode.contains(innerNode);
9007 } else if (outerNode.compareDocumentPosition) {
9008 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
9009 } else {
9010 return false;
9011 }
9012}
9013
9014function isInDocument(node) {
9015 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
9016}
9017
9018function isSameOriginFrame(iframe) {
9019 try {
9020 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
9021 // to throw, e.g. if it has a cross-origin src attribute.
9022 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
9023 // iframe.contentDocument.defaultView;
9024 // A safety way is to access one of the cross origin properties: Window or Location
9025 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
9026 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
9027 return typeof iframe.contentWindow.location.href === 'string';
9028 } catch (err) {
9029 return false;
9030 }
9031}
9032
9033function getActiveElementDeep() {
9034 var win = window;
9035 var element = getActiveElement();
9036
9037 while (element instanceof win.HTMLIFrameElement) {
9038 if (isSameOriginFrame(element)) {
9039 win = element.contentWindow;
9040 } else {
9041 return element;
9042 }
9043
9044 element = getActiveElement(win.document);
9045 }
9046
9047 return element;
9048}
9049/**
9050 * @ReactInputSelection: React input selection module. Based on Selection.js,
9051 * but modified to be suitable for react and has a couple of bug fixes (doesn't
9052 * assume buttons have range selections allowed).
9053 * Input selection module for React.
9054 */
9055
9056/**
9057 * @hasSelectionCapabilities: we get the element types that support selection
9058 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
9059 * and `selectionEnd` rows.
9060 */
9061
9062
9063function hasSelectionCapabilities(elem) {
9064 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
9065 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
9066}
9067function getSelectionInformation() {
9068 var focusedElem = getActiveElementDeep();
9069 return {
9070 focusedElem: focusedElem,
9071 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
9072 };
9073}
9074/**
9075 * @restoreSelection: If any selection information was potentially lost,
9076 * restore it. This is useful when performing operations that could remove dom
9077 * nodes and place them back in, resulting in focus being lost.
9078 */
9079
9080function restoreSelection(priorSelectionInformation) {
9081 var curFocusedElem = getActiveElementDeep();
9082 var priorFocusedElem = priorSelectionInformation.focusedElem;
9083 var priorSelectionRange = priorSelectionInformation.selectionRange;
9084
9085 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
9086 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
9087 setSelection(priorFocusedElem, priorSelectionRange);
9088 } // Focusing a node can change the scroll position, which is undesirable
9089
9090
9091 var ancestors = [];
9092 var ancestor = priorFocusedElem;
9093
9094 while (ancestor = ancestor.parentNode) {
9095 if (ancestor.nodeType === ELEMENT_NODE) {
9096 ancestors.push({
9097 element: ancestor,
9098 left: ancestor.scrollLeft,
9099 top: ancestor.scrollTop
9100 });
9101 }
9102 }
9103
9104 if (typeof priorFocusedElem.focus === 'function') {
9105 priorFocusedElem.focus();
9106 }
9107
9108 for (var i = 0; i < ancestors.length; i++) {
9109 var info = ancestors[i];
9110 info.element.scrollLeft = info.left;
9111 info.element.scrollTop = info.top;
9112 }
9113 }
9114}
9115/**
9116 * @getSelection: Gets the selection bounds of a focused textarea, input or
9117 * contentEditable node.
9118 * -@input: Look up selection bounds of this input
9119 * -@return {start: selectionStart, end: selectionEnd}
9120 */
9121
9122function getSelection(input) {
9123 var selection;
9124
9125 if ('selectionStart' in input) {
9126 // Modern browser with input or textarea.
9127 selection = {
9128 start: input.selectionStart,
9129 end: input.selectionEnd
9130 };
9131 } else {
9132 // Content editable or old IE textarea.
9133 selection = getOffsets(input);
9134 }
9135
9136 return selection || {
9137 start: 0,
9138 end: 0
9139 };
9140}
9141/**
9142 * @setSelection: Sets the selection bounds of a textarea or input and focuses
9143 * the input.
9144 * -@input Set selection bounds of this input or textarea
9145 * -@offsets Object of same form that is returned from get*
9146 */
9147
9148function setSelection(input, offsets) {
9149 var start = offsets.start,
9150 end = offsets.end;
9151
9152 if (end === undefined) {
9153 end = start;
9154 }
9155
9156 if ('selectionStart' in input) {
9157 input.selectionStart = start;
9158 input.selectionEnd = Math.min(end, input.value.length);
9159 } else {
9160 setOffsets(input, offsets);
9161 }
9162}
9163
9164var validateDOMNesting = function () {};
9165
9166var updatedAncestorInfo = function () {};
9167
9168{
9169 // This validation code was written based on the HTML5 parsing spec:
9170 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
9171 //
9172 // Note: this does not catch all invalid nesting, nor does it try to (as it's
9173 // not clear what practical benefit doing so provides); instead, we warn only
9174 // for cases where the parser will give a parse tree differing from what React
9175 // intended. For example, <b><div></div></b> is invalid but we don't warn
9176 // because it still parses correctly; we do warn for other cases like nested
9177 // <p> tags where the beginning of the second element implicitly closes the
9178 // first, causing a confusing mess.
9179 // https://html.spec.whatwg.org/multipage/syntax.html#special
9180 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
9181
9182 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
9183 // TODO: Distinguish by namespace here -- for <title>, including it here
9184 // errs on the side of fewer warnings
9185 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
9186
9187 var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
9188
9189 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
9190 var emptyAncestorInfo = {
9191 current: null,
9192 formTag: null,
9193 aTagInScope: null,
9194 buttonTagInScope: null,
9195 nobrTagInScope: null,
9196 pTagInButtonScope: null,
9197 listItemTagAutoclosing: null,
9198 dlItemTagAutoclosing: null
9199 };
9200
9201 updatedAncestorInfo = function (oldInfo, tag) {
9202 var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
9203
9204 var info = {
9205 tag: tag
9206 };
9207
9208 if (inScopeTags.indexOf(tag) !== -1) {
9209 ancestorInfo.aTagInScope = null;
9210 ancestorInfo.buttonTagInScope = null;
9211 ancestorInfo.nobrTagInScope = null;
9212 }
9213
9214 if (buttonScopeTags.indexOf(tag) !== -1) {
9215 ancestorInfo.pTagInButtonScope = null;
9216 } // See rules for 'li', 'dd', 'dt' start tags in
9217 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9218
9219
9220 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
9221 ancestorInfo.listItemTagAutoclosing = null;
9222 ancestorInfo.dlItemTagAutoclosing = null;
9223 }
9224
9225 ancestorInfo.current = info;
9226
9227 if (tag === 'form') {
9228 ancestorInfo.formTag = info;
9229 }
9230
9231 if (tag === 'a') {
9232 ancestorInfo.aTagInScope = info;
9233 }
9234
9235 if (tag === 'button') {
9236 ancestorInfo.buttonTagInScope = info;
9237 }
9238
9239 if (tag === 'nobr') {
9240 ancestorInfo.nobrTagInScope = info;
9241 }
9242
9243 if (tag === 'p') {
9244 ancestorInfo.pTagInButtonScope = info;
9245 }
9246
9247 if (tag === 'li') {
9248 ancestorInfo.listItemTagAutoclosing = info;
9249 }
9250
9251 if (tag === 'dd' || tag === 'dt') {
9252 ancestorInfo.dlItemTagAutoclosing = info;
9253 }
9254
9255 return ancestorInfo;
9256 };
9257 /**
9258 * Returns whether
9259 */
9260
9261
9262 var isTagValidWithParent = function (tag, parentTag) {
9263 // First, let's check if we're in an unusual parsing mode...
9264 switch (parentTag) {
9265 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
9266 case 'select':
9267 return tag === 'option' || tag === 'optgroup' || tag === '#text';
9268
9269 case 'optgroup':
9270 return tag === 'option' || tag === '#text';
9271 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
9272 // but
9273
9274 case 'option':
9275 return tag === '#text';
9276 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
9277 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
9278 // No special behavior since these rules fall back to "in body" mode for
9279 // all except special table nodes which cause bad parsing behavior anyway.
9280 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
9281
9282 case 'tr':
9283 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
9284 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
9285
9286 case 'tbody':
9287 case 'thead':
9288 case 'tfoot':
9289 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
9290 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
9291
9292 case 'colgroup':
9293 return tag === 'col' || tag === 'template';
9294 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
9295
9296 case 'table':
9297 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
9298 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
9299
9300 case 'head':
9301 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
9302 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
9303
9304 case 'html':
9305 return tag === 'head' || tag === 'body' || tag === 'frameset';
9306
9307 case 'frameset':
9308 return tag === 'frame';
9309
9310 case '#document':
9311 return tag === 'html';
9312 } // Probably in the "in body" parsing mode, so we outlaw only tag combos
9313 // where the parsing rules cause implicit opens or closes to be added.
9314 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
9315
9316
9317 switch (tag) {
9318 case 'h1':
9319 case 'h2':
9320 case 'h3':
9321 case 'h4':
9322 case 'h5':
9323 case 'h6':
9324 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
9325
9326 case 'rp':
9327 case 'rt':
9328 return impliedEndTags.indexOf(parentTag) === -1;
9329
9330 case 'body':
9331 case 'caption':
9332 case 'col':
9333 case 'colgroup':
9334 case 'frameset':
9335 case 'frame':
9336 case 'head':
9337 case 'html':
9338 case 'tbody':
9339 case 'td':
9340 case 'tfoot':
9341 case 'th':
9342 case 'thead':
9343 case 'tr':
9344 // These tags are only valid with a few parents that have special child
9345 // parsing rules -- if we're down here, then none of those matched and
9346 // so we allow it only if we don't know what the parent is, as all other
9347 // cases are invalid.
9348 return parentTag == null;
9349 }
9350
9351 return true;
9352 };
9353 /**
9354 * Returns whether
9355 */
9356
9357
9358 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
9359 switch (tag) {
9360 case 'address':
9361 case 'article':
9362 case 'aside':
9363 case 'blockquote':
9364 case 'center':
9365 case 'details':
9366 case 'dialog':
9367 case 'dir':
9368 case 'div':
9369 case 'dl':
9370 case 'fieldset':
9371 case 'figcaption':
9372 case 'figure':
9373 case 'footer':
9374 case 'header':
9375 case 'hgroup':
9376 case 'main':
9377 case 'menu':
9378 case 'nav':
9379 case 'ol':
9380 case 'p':
9381 case 'section':
9382 case 'summary':
9383 case 'ul':
9384 case 'pre':
9385 case 'listing':
9386 case 'table':
9387 case 'hr':
9388 case 'xmp':
9389 case 'h1':
9390 case 'h2':
9391 case 'h3':
9392 case 'h4':
9393 case 'h5':
9394 case 'h6':
9395 return ancestorInfo.pTagInButtonScope;
9396
9397 case 'form':
9398 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
9399
9400 case 'li':
9401 return ancestorInfo.listItemTagAutoclosing;
9402
9403 case 'dd':
9404 case 'dt':
9405 return ancestorInfo.dlItemTagAutoclosing;
9406
9407 case 'button':
9408 return ancestorInfo.buttonTagInScope;
9409
9410 case 'a':
9411 // Spec says something about storing a list of markers, but it sounds
9412 // equivalent to this check.
9413 return ancestorInfo.aTagInScope;
9414
9415 case 'nobr':
9416 return ancestorInfo.nobrTagInScope;
9417 }
9418
9419 return null;
9420 };
9421
9422 var didWarn$1 = {};
9423
9424 validateDOMNesting = function (childTag, childText, ancestorInfo) {
9425 ancestorInfo = ancestorInfo || emptyAncestorInfo;
9426 var parentInfo = ancestorInfo.current;
9427 var parentTag = parentInfo && parentInfo.tag;
9428
9429 if (childText != null) {
9430 !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0;
9431 childTag = '#text';
9432 }
9433
9434 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
9435 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
9436 var invalidParentOrAncestor = invalidParent || invalidAncestor;
9437
9438 if (!invalidParentOrAncestor) {
9439 return;
9440 }
9441
9442 var ancestorTag = invalidParentOrAncestor.tag;
9443 var addendum = getCurrentFiberStackInDev();
9444 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
9445
9446 if (didWarn$1[warnKey]) {
9447 return;
9448 }
9449
9450 didWarn$1[warnKey] = true;
9451 var tagDisplayName = childTag;
9452 var whitespaceInfo = '';
9453
9454 if (childTag === '#text') {
9455 if (/\S/.test(childText)) {
9456 tagDisplayName = 'Text nodes';
9457 } else {
9458 tagDisplayName = 'Whitespace text nodes';
9459 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
9460 }
9461 } else {
9462 tagDisplayName = '<' + childTag + '>';
9463 }
9464
9465 if (invalidParent) {
9466 var info = '';
9467
9468 if (ancestorTag === 'table' && childTag === 'tr') {
9469 info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
9470 }
9471
9472 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum);
9473 } else {
9474 warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum);
9475 }
9476 };
9477}
9478
9479// can re-export everything from this module.
9480
9481function shim() {
9482 {
9483 {
9484 throw Error("The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.");
9485 }
9486 }
9487} // Persistence (when unsupported)
9488
9489
9490var supportsPersistence = false;
9491var cloneInstance = shim;
9492var cloneFundamentalInstance = shim;
9493var createContainerChildSet = shim;
9494var appendChildToContainerChildSet = shim;
9495var finalizeContainerChildren = shim;
9496var replaceContainerChildren = shim;
9497var cloneHiddenInstance = shim;
9498var cloneHiddenTextInstance = shim;
9499
9500var SUPPRESS_HYDRATION_WARNING;
9501
9502{
9503 SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9504}
9505
9506var SUSPENSE_START_DATA = '$';
9507var SUSPENSE_END_DATA = '/$';
9508var SUSPENSE_PENDING_START_DATA = '$?';
9509var SUSPENSE_FALLBACK_START_DATA = '$!';
9510var STYLE = 'style';
9511var eventsEnabled = null;
9512var selectionInformation = null;
9513
9514function shouldAutoFocusHostComponent(type, props) {
9515 switch (type) {
9516 case 'button':
9517 case 'input':
9518 case 'select':
9519 case 'textarea':
9520 return !!props.autoFocus;
9521 }
9522
9523 return false;
9524}
9525
9526function getRootHostContext(rootContainerInstance) {
9527 var type;
9528 var namespace;
9529 var nodeType = rootContainerInstance.nodeType;
9530
9531 switch (nodeType) {
9532 case DOCUMENT_NODE:
9533 case DOCUMENT_FRAGMENT_NODE:
9534 {
9535 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
9536 var root = rootContainerInstance.documentElement;
9537 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
9538 break;
9539 }
9540
9541 default:
9542 {
9543 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
9544 var ownNamespace = container.namespaceURI || null;
9545 type = container.tagName;
9546 namespace = getChildNamespace(ownNamespace, type);
9547 break;
9548 }
9549 }
9550
9551 {
9552 var validatedTag = type.toLowerCase();
9553 var ancestorInfo = updatedAncestorInfo(null, validatedTag);
9554 return {
9555 namespace: namespace,
9556 ancestorInfo: ancestorInfo
9557 };
9558 }
9559
9560 return namespace;
9561}
9562function getChildHostContext(parentHostContext, type, rootContainerInstance) {
9563 {
9564 var parentHostContextDev = parentHostContext;
9565 var namespace = getChildNamespace(parentHostContextDev.namespace, type);
9566 var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
9567 return {
9568 namespace: namespace,
9569 ancestorInfo: ancestorInfo
9570 };
9571 }
9572
9573 var parentNamespace = parentHostContext;
9574 return getChildNamespace(parentNamespace, type);
9575}
9576function getPublicInstance(instance) {
9577 return instance;
9578}
9579function prepareForCommit(containerInfo) {
9580 eventsEnabled = isEnabled();
9581 selectionInformation = getSelectionInformation();
9582 setEnabled(false);
9583}
9584function resetAfterCommit(containerInfo) {
9585 restoreSelection(selectionInformation);
9586 selectionInformation = null;
9587 setEnabled(eventsEnabled);
9588 eventsEnabled = null;
9589}
9590function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9591 var parentNamespace;
9592
9593 {
9594 // TODO: take namespace into account when validating.
9595 var hostContextDev = hostContext;
9596 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
9597
9598 if (typeof props.children === 'string' || typeof props.children === 'number') {
9599 var string = '' + props.children;
9600 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9601 validateDOMNesting(null, string, ownAncestorInfo);
9602 }
9603
9604 parentNamespace = hostContextDev.namespace;
9605 }
9606
9607 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
9608 precacheFiberNode(internalInstanceHandle, domElement);
9609 updateFiberProps(domElement, props);
9610 return domElement;
9611}
9612function appendInitialChild(parentInstance, child) {
9613 parentInstance.appendChild(child);
9614}
9615function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
9616 setInitialProperties(domElement, type, props, rootContainerInstance);
9617 return shouldAutoFocusHostComponent(type, props);
9618}
9619function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
9620 {
9621 var hostContextDev = hostContext;
9622
9623 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
9624 var string = '' + newProps.children;
9625 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
9626 validateDOMNesting(null, string, ownAncestorInfo);
9627 }
9628 }
9629
9630 return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
9631}
9632function shouldSetTextContent(type, props) {
9633 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;
9634}
9635function shouldDeprioritizeSubtree(type, props) {
9636 return !!props.hidden;
9637}
9638function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
9639 {
9640 var hostContextDev = hostContext;
9641 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
9642 }
9643
9644 var textNode = createTextNode(text, rootContainerInstance);
9645 precacheFiberNode(internalInstanceHandle, textNode);
9646 return textNode;
9647}
9648var isPrimaryRenderer = true;
9649var warnsIfNotActing = true; // This initialization code may run even on server environments
9650// if a component just imports ReactDOM (e.g. for findDOMNode).
9651// Some environments might not have setTimeout or clearTimeout.
9652
9653var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
9654var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
9655var noTimeout = -1; // -------------------
9656// Mutation
9657// -------------------
9658
9659var supportsMutation = true;
9660function commitMount(domElement, type, newProps, internalInstanceHandle) {
9661 // Despite the naming that might imply otherwise, this method only
9662 // fires if there is an `Update` effect scheduled during mounting.
9663 // This happens if `finalizeInitialChildren` returns `true` (which it
9664 // does to implement the `autoFocus` attribute on the client). But
9665 // there are also other cases when this might happen (such as patching
9666 // up text content during hydration mismatch). So we'll check this again.
9667 if (shouldAutoFocusHostComponent(type, newProps)) {
9668 domElement.focus();
9669 }
9670}
9671function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
9672 // Update the props handle so that we know which props are the ones with
9673 // with current event handlers.
9674 updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.
9675
9676 updateProperties(domElement, updatePayload, type, oldProps, newProps);
9677}
9678function resetTextContent(domElement) {
9679 setTextContent(domElement, '');
9680}
9681function commitTextUpdate(textInstance, oldText, newText) {
9682 textInstance.nodeValue = newText;
9683}
9684function appendChild(parentInstance, child) {
9685 parentInstance.appendChild(child);
9686}
9687function appendChildToContainer(container, child) {
9688 var parentNode;
9689
9690 if (container.nodeType === COMMENT_NODE) {
9691 parentNode = container.parentNode;
9692 parentNode.insertBefore(child, container);
9693 } else {
9694 parentNode = container;
9695 parentNode.appendChild(child);
9696 } // This container might be used for a portal.
9697 // If something inside a portal is clicked, that click should bubble
9698 // through the React tree. However, on Mobile Safari the click would
9699 // never bubble through the *DOM* tree unless an ancestor with onclick
9700 // event exists. So we wouldn't see it and dispatch it.
9701 // This is why we ensure that non React root containers have inline onclick
9702 // defined.
9703 // https://github.com/facebook/react/issues/11918
9704
9705
9706 var reactRootContainer = container._reactRootContainer;
9707
9708 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
9709 // TODO: This cast may not be sound for SVG, MathML or custom elements.
9710 trapClickOnNonInteractiveElement(parentNode);
9711 }
9712}
9713function insertBefore(parentInstance, child, beforeChild) {
9714 parentInstance.insertBefore(child, beforeChild);
9715}
9716function insertInContainerBefore(container, child, beforeChild) {
9717 if (container.nodeType === COMMENT_NODE) {
9718 container.parentNode.insertBefore(child, beforeChild);
9719 } else {
9720 container.insertBefore(child, beforeChild);
9721 }
9722}
9723function removeChild(parentInstance, child) {
9724 parentInstance.removeChild(child);
9725}
9726function removeChildFromContainer(container, child) {
9727 if (container.nodeType === COMMENT_NODE) {
9728 container.parentNode.removeChild(child);
9729 } else {
9730 container.removeChild(child);
9731 }
9732}
9733function clearSuspenseBoundary(parentInstance, suspenseInstance) {
9734 var node = suspenseInstance; // Delete all nodes within this suspense boundary.
9735 // There might be nested nodes so we need to keep track of how
9736 // deep we are and only break out when we're back on top.
9737
9738 var depth = 0;
9739
9740 do {
9741 var nextNode = node.nextSibling;
9742 parentInstance.removeChild(node);
9743
9744 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
9745 var data = nextNode.data;
9746
9747 if (data === SUSPENSE_END_DATA) {
9748 if (depth === 0) {
9749 parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
9750
9751 retryIfBlockedOn(suspenseInstance);
9752 return;
9753 } else {
9754 depth--;
9755 }
9756 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
9757 depth++;
9758 }
9759 }
9760
9761 node = nextNode;
9762 } while (node); // TODO: Warn, we didn't find the end comment boundary.
9763 // Retry if any event replaying was blocked on this.
9764
9765
9766 retryIfBlockedOn(suspenseInstance);
9767}
9768function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
9769 if (container.nodeType === COMMENT_NODE) {
9770 clearSuspenseBoundary(container.parentNode, suspenseInstance);
9771 } else if (container.nodeType === ELEMENT_NODE) {
9772 clearSuspenseBoundary(container, suspenseInstance);
9773 } else {} // Document nodes should never contain suspense boundaries.
9774 // Retry if any event replaying was blocked on this.
9775
9776
9777 retryIfBlockedOn(container);
9778}
9779function hideInstance(instance) {
9780 // TODO: Does this work for all element types? What about MathML? Should we
9781 // pass host context to this method?
9782 instance = instance;
9783 var style = instance.style;
9784
9785 if (typeof style.setProperty === 'function') {
9786 style.setProperty('display', 'none', 'important');
9787 } else {
9788 style.display = 'none';
9789 }
9790}
9791function hideTextInstance(textInstance) {
9792 textInstance.nodeValue = '';
9793}
9794function unhideInstance(instance, props) {
9795 instance = instance;
9796 var styleProp = props[STYLE];
9797 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
9798 instance.style.display = dangerousStyleValue('display', display);
9799}
9800function unhideTextInstance(textInstance, text) {
9801 textInstance.nodeValue = text;
9802} // -------------------
9803// Hydration
9804// -------------------
9805
9806var supportsHydration = true;
9807function canHydrateInstance(instance, type, props) {
9808 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
9809 return null;
9810 } // This has now been refined to an element node.
9811
9812
9813 return instance;
9814}
9815function canHydrateTextInstance(instance, text) {
9816 if (text === '' || instance.nodeType !== TEXT_NODE) {
9817 // Empty strings are not parsed by HTML so there won't be a correct match here.
9818 return null;
9819 } // This has now been refined to a text node.
9820
9821
9822 return instance;
9823}
9824function canHydrateSuspenseInstance(instance) {
9825 if (instance.nodeType !== COMMENT_NODE) {
9826 // Empty strings are not parsed by HTML so there won't be a correct match here.
9827 return null;
9828 } // This has now been refined to a suspense node.
9829
9830
9831 return instance;
9832}
9833function isSuspenseInstancePending(instance) {
9834 return instance.data === SUSPENSE_PENDING_START_DATA;
9835}
9836function isSuspenseInstanceFallback(instance) {
9837 return instance.data === SUSPENSE_FALLBACK_START_DATA;
9838}
9839function registerSuspenseInstanceRetry(instance, callback) {
9840 instance._reactRetry = callback;
9841}
9842
9843function getNextHydratable(node) {
9844 // Skip non-hydratable nodes.
9845 for (; node != null; node = node.nextSibling) {
9846 var nodeType = node.nodeType;
9847
9848 if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
9849 break;
9850 }
9851
9852 if (enableSuspenseServerRenderer) {
9853 if (nodeType === COMMENT_NODE) {
9854 var nodeData = node.data;
9855
9856 if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
9857 break;
9858 }
9859 }
9860 }
9861 }
9862
9863 return node;
9864}
9865
9866function getNextHydratableSibling(instance) {
9867 return getNextHydratable(instance.nextSibling);
9868}
9869function getFirstHydratableChild(parentInstance) {
9870 return getNextHydratable(parentInstance.firstChild);
9871}
9872function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
9873 precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
9874 // get attached.
9875
9876 updateFiberProps(instance, props);
9877 var parentNamespace;
9878
9879 {
9880 var hostContextDev = hostContext;
9881 parentNamespace = hostContextDev.namespace;
9882 }
9883
9884 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
9885}
9886function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
9887 precacheFiberNode(internalInstanceHandle, textInstance);
9888 return diffHydratedText(textInstance, text);
9889}
9890function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
9891 precacheFiberNode(internalInstanceHandle, suspenseInstance);
9892}
9893function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
9894 var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
9895 // There might be nested nodes so we need to keep track of how
9896 // deep we are and only break out when we're back on top.
9897
9898 var depth = 0;
9899
9900 while (node) {
9901 if (node.nodeType === COMMENT_NODE) {
9902 var data = node.data;
9903
9904 if (data === SUSPENSE_END_DATA) {
9905 if (depth === 0) {
9906 return getNextHydratableSibling(node);
9907 } else {
9908 depth--;
9909 }
9910 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9911 depth++;
9912 }
9913 }
9914
9915 node = node.nextSibling;
9916 } // TODO: Warn, we didn't find the end comment boundary.
9917
9918
9919 return null;
9920} // Returns the SuspenseInstance if this node is a direct child of a
9921// SuspenseInstance. I.e. if its previous sibling is a Comment with
9922// SUSPENSE_x_START_DATA. Otherwise, null.
9923
9924function getParentSuspenseInstance(targetInstance) {
9925 var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
9926 // There might be nested nodes so we need to keep track of how
9927 // deep we are and only break out when we're back on top.
9928
9929 var depth = 0;
9930
9931 while (node) {
9932 if (node.nodeType === COMMENT_NODE) {
9933 var data = node.data;
9934
9935 if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
9936 if (depth === 0) {
9937 return node;
9938 } else {
9939 depth--;
9940 }
9941 } else if (data === SUSPENSE_END_DATA) {
9942 depth++;
9943 }
9944 }
9945
9946 node = node.previousSibling;
9947 }
9948
9949 return null;
9950}
9951function commitHydratedContainer(container) {
9952 // Retry if any event replaying was blocked on this.
9953 retryIfBlockedOn(container);
9954}
9955function commitHydratedSuspenseInstance(suspenseInstance) {
9956 // Retry if any event replaying was blocked on this.
9957 retryIfBlockedOn(suspenseInstance);
9958}
9959function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
9960 {
9961 warnForUnmatchedText(textInstance, text);
9962 }
9963}
9964function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
9965 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9966 warnForUnmatchedText(textInstance, text);
9967 }
9968}
9969function didNotHydrateContainerInstance(parentContainer, instance) {
9970 {
9971 if (instance.nodeType === ELEMENT_NODE) {
9972 warnForDeletedHydratableElement(parentContainer, instance);
9973 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9974 } else {
9975 warnForDeletedHydratableText(parentContainer, instance);
9976 }
9977 }
9978}
9979function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
9980 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
9981 if (instance.nodeType === ELEMENT_NODE) {
9982 warnForDeletedHydratableElement(parentInstance, instance);
9983 } else if (instance.nodeType === COMMENT_NODE) {// TODO: warnForDeletedHydratableSuspenseBoundary
9984 } else {
9985 warnForDeletedHydratableText(parentInstance, instance);
9986 }
9987 }
9988}
9989function didNotFindHydratableContainerInstance(parentContainer, type, props) {
9990 {
9991 warnForInsertedHydratedElement(parentContainer, type, props);
9992 }
9993}
9994function didNotFindHydratableContainerTextInstance(parentContainer, text) {
9995 {
9996 warnForInsertedHydratedText(parentContainer, text);
9997 }
9998}
9999
10000function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
10001 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10002 warnForInsertedHydratedElement(parentInstance, type, props);
10003 }
10004}
10005function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
10006 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10007 warnForInsertedHydratedText(parentInstance, text);
10008 }
10009}
10010function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
10011 if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) {// TODO: warnForInsertedHydratedSuspense(parentInstance);
10012 }
10013}
10014function mountResponderInstance(responder, responderInstance, responderProps, responderState, instance) {
10015 // Listen to events
10016 var doc = instance.ownerDocument;
10017 var _ref = responder,
10018 rootEventTypes = _ref.rootEventTypes,
10019 targetEventTypes = _ref.targetEventTypes;
10020
10021 if (targetEventTypes !== null) {
10022 listenToEventResponderEventTypes(targetEventTypes, doc);
10023 }
10024
10025 if (rootEventTypes !== null) {
10026 addRootEventTypesForResponderInstance(responderInstance, rootEventTypes);
10027 listenToEventResponderEventTypes(rootEventTypes, doc);
10028 }
10029
10030 mountEventResponder(responder, responderInstance, responderProps, responderState);
10031 return responderInstance;
10032}
10033function unmountResponderInstance(responderInstance) {
10034 if (enableFlareAPI) {
10035 // TODO stop listening to targetEventTypes
10036 unmountEventResponder(responderInstance);
10037 }
10038}
10039function getFundamentalComponentInstance(fundamentalInstance) {
10040 if (enableFundamentalAPI) {
10041 var currentFiber = fundamentalInstance.currentFiber,
10042 impl = fundamentalInstance.impl,
10043 props = fundamentalInstance.props,
10044 state = fundamentalInstance.state;
10045 var instance = impl.getInstance(null, props, state);
10046 precacheFiberNode(currentFiber, instance);
10047 return instance;
10048 } // Because of the flag above, this gets around the Flow error;
10049
10050
10051 return null;
10052}
10053function mountFundamentalComponent(fundamentalInstance) {
10054 if (enableFundamentalAPI) {
10055 var impl = fundamentalInstance.impl,
10056 instance = fundamentalInstance.instance,
10057 props = fundamentalInstance.props,
10058 state = fundamentalInstance.state;
10059 var onMount = impl.onMount;
10060
10061 if (onMount !== undefined) {
10062 onMount(null, instance, props, state);
10063 }
10064 }
10065}
10066function shouldUpdateFundamentalComponent(fundamentalInstance) {
10067 if (enableFundamentalAPI) {
10068 var impl = fundamentalInstance.impl,
10069 prevProps = fundamentalInstance.prevProps,
10070 props = fundamentalInstance.props,
10071 state = fundamentalInstance.state;
10072 var shouldUpdate = impl.shouldUpdate;
10073
10074 if (shouldUpdate !== undefined) {
10075 return shouldUpdate(null, prevProps, props, state);
10076 }
10077 }
10078
10079 return true;
10080}
10081function updateFundamentalComponent(fundamentalInstance) {
10082 if (enableFundamentalAPI) {
10083 var impl = fundamentalInstance.impl,
10084 instance = fundamentalInstance.instance,
10085 prevProps = fundamentalInstance.prevProps,
10086 props = fundamentalInstance.props,
10087 state = fundamentalInstance.state;
10088 var onUpdate = impl.onUpdate;
10089
10090 if (onUpdate !== undefined) {
10091 onUpdate(null, instance, prevProps, props, state);
10092 }
10093 }
10094}
10095function unmountFundamentalComponent(fundamentalInstance) {
10096 if (enableFundamentalAPI) {
10097 var impl = fundamentalInstance.impl,
10098 instance = fundamentalInstance.instance,
10099 props = fundamentalInstance.props,
10100 state = fundamentalInstance.state;
10101 var onUnmount = impl.onUnmount;
10102
10103 if (onUnmount !== undefined) {
10104 onUnmount(null, instance, props, state);
10105 }
10106 }
10107}
10108function getInstanceFromNode$2(node) {
10109 return getClosestInstanceFromNode(node) || null;
10110}
10111
10112var randomKey = Math.random().toString(36).slice(2);
10113var internalInstanceKey = '__reactInternalInstance$' + randomKey;
10114var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
10115var internalContainerInstanceKey = '__reactContainere$' + randomKey;
10116function precacheFiberNode(hostInst, node) {
10117 node[internalInstanceKey] = hostInst;
10118}
10119function markContainerAsRoot(hostRoot, node) {
10120 node[internalContainerInstanceKey] = hostRoot;
10121} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
10122// If the target node is part of a hydrated or not yet rendered subtree, then
10123// this may also return a SuspenseComponent or HostRoot to indicate that.
10124// Conceptually the HostRoot fiber is a child of the Container node. So if you
10125// pass the Container node as the targetNode, you wiill not actually get the
10126// HostRoot back. To get to the HostRoot, you need to pass a child of it.
10127// The same thing applies to Suspense boundaries.
10128
10129function getClosestInstanceFromNode(targetNode) {
10130 var targetInst = targetNode[internalInstanceKey];
10131
10132 if (targetInst) {
10133 // Don't return HostRoot or SuspenseComponent here.
10134 return targetInst;
10135 } // If the direct event target isn't a React owned DOM node, we need to look
10136 // to see if one of its parents is a React owned DOM node.
10137
10138
10139 var parentNode = targetNode.parentNode;
10140
10141 while (parentNode) {
10142 // We'll check if this is a container root that could include
10143 // React nodes in the future. We need to check this first because
10144 // if we're a child of a dehydrated container, we need to first
10145 // find that inner container before moving on to finding the parent
10146 // instance. Note that we don't check this field on the targetNode
10147 // itself because the fibers are conceptually between the container
10148 // node and the first child. It isn't surrounding the container node.
10149 // If it's not a container, we check if it's an instance.
10150 targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
10151
10152 if (targetInst) {
10153 // Since this wasn't the direct target of the event, we might have
10154 // stepped past dehydrated DOM nodes to get here. However they could
10155 // also have been non-React nodes. We need to answer which one.
10156 // If we the instance doesn't have any children, then there can't be
10157 // a nested suspense boundary within it. So we can use this as a fast
10158 // bailout. Most of the time, when people add non-React children to
10159 // the tree, it is using a ref to a child-less DOM node.
10160 // Normally we'd only need to check one of the fibers because if it
10161 // has ever gone from having children to deleting them or vice versa
10162 // it would have deleted the dehydrated boundary nested inside already.
10163 // However, since the HostRoot starts out with an alternate it might
10164 // have one on the alternate so we need to check in case this was a
10165 // root.
10166 var alternate = targetInst.alternate;
10167
10168 if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
10169 // Next we need to figure out if the node that skipped past is
10170 // nested within a dehydrated boundary and if so, which one.
10171 var suspenseInstance = getParentSuspenseInstance(targetNode);
10172
10173 while (suspenseInstance !== null) {
10174 // We found a suspense instance. That means that we haven't
10175 // hydrated it yet. Even though we leave the comments in the
10176 // DOM after hydrating, and there are boundaries in the DOM
10177 // that could already be hydrated, we wouldn't have found them
10178 // through this pass since if the target is hydrated it would
10179 // have had an internalInstanceKey on it.
10180 // Let's get the fiber associated with the SuspenseComponent
10181 // as the deepest instance.
10182 var targetSuspenseInst = suspenseInstance[internalInstanceKey];
10183
10184 if (targetSuspenseInst) {
10185 return targetSuspenseInst;
10186 } // If we don't find a Fiber on the comment, it might be because
10187 // we haven't gotten to hydrate it yet. There might still be a
10188 // parent boundary that hasn't above this one so we need to find
10189 // the outer most that is known.
10190
10191
10192 suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
10193 // host component also hasn't hydrated yet. We can return it
10194 // below since it will bail out on the isMounted check later.
10195 }
10196 }
10197
10198 return targetInst;
10199 }
10200
10201 targetNode = parentNode;
10202 parentNode = targetNode.parentNode;
10203 }
10204
10205 return null;
10206}
10207/**
10208 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
10209 * instance, or null if the node was not rendered by this React.
10210 */
10211
10212function getInstanceFromNode$1(node) {
10213 var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
10214
10215 if (inst) {
10216 if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
10217 return inst;
10218 } else {
10219 return null;
10220 }
10221 }
10222
10223 return null;
10224}
10225/**
10226 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
10227 * DOM node.
10228 */
10229
10230function getNodeFromInstance$1(inst) {
10231 if (inst.tag === HostComponent || inst.tag === HostText) {
10232 // In Fiber this, is just the state node right now. We assume it will be
10233 // a host component or host text.
10234 return inst.stateNode;
10235 } // Without this first invariant, passing a non-DOM-component triggers the next
10236 // invariant for a missing parent, which is super confusing.
10237
10238
10239 {
10240 {
10241 throw Error("getNodeFromInstance: Invalid argument.");
10242 }
10243 }
10244}
10245function getFiberCurrentPropsFromNode$1(node) {
10246 return node[internalEventHandlersKey] || null;
10247}
10248function updateFiberProps(node, props) {
10249 node[internalEventHandlersKey] = props;
10250}
10251
10252/**
10253 * These variables store information about text content of a target node,
10254 * allowing comparison of content before and after a given event.
10255 *
10256 * Identify the node where selection currently begins, then observe
10257 * both its text content and its current position in the DOM. Since the
10258 * browser may natively replace the target node during composition, we can
10259 * use its position to find its replacement.
10260 *
10261 *
10262 */
10263var root = null;
10264var startText = null;
10265var fallbackText = null;
10266function initialize(nativeEventTarget) {
10267 root = nativeEventTarget;
10268 startText = getText();
10269 return true;
10270}
10271function reset() {
10272 root = null;
10273 startText = null;
10274 fallbackText = null;
10275}
10276function getData() {
10277 if (fallbackText) {
10278 return fallbackText;
10279 }
10280
10281 var start;
10282 var startValue = startText;
10283 var startLength = startValue.length;
10284 var end;
10285 var endValue = getText();
10286 var endLength = endValue.length;
10287
10288 for (start = 0; start < startLength; start++) {
10289 if (startValue[start] !== endValue[start]) {
10290 break;
10291 }
10292 }
10293
10294 var minEnd = startLength - start;
10295
10296 for (end = 1; end <= minEnd; end++) {
10297 if (startValue[startLength - end] !== endValue[endLength - end]) {
10298 break;
10299 }
10300 }
10301
10302 var sliceTail = end > 1 ? 1 - end : undefined;
10303 fallbackText = endValue.slice(start, sliceTail);
10304 return fallbackText;
10305}
10306function getText() {
10307 if ('value' in root) {
10308 return root.value;
10309 }
10310
10311 return root.textContent;
10312}
10313
10314/**
10315 * @interface Event
10316 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
10317 */
10318
10319var SyntheticCompositionEvent = SyntheticEvent.extend({
10320 data: null
10321});
10322
10323/**
10324 * @interface Event
10325 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
10326 * /#events-inputevents
10327 */
10328
10329var SyntheticInputEvent = SyntheticEvent.extend({
10330 data: null
10331});
10332
10333var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
10334
10335var START_KEYCODE = 229;
10336var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
10337var documentMode = null;
10338
10339if (canUseDOM && 'documentMode' in document) {
10340 documentMode = document.documentMode;
10341} // Webkit offers a very useful `textInput` event that can be used to
10342// directly represent `beforeInput`. The IE `textinput` event is not as
10343// useful, so we don't use it.
10344
10345
10346var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
10347// by the native compositionend event may be incorrect. Japanese ideographic
10348// spaces, for instance (\u3000) are not recorded correctly.
10349
10350var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
10351var SPACEBAR_CODE = 32;
10352var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.
10353
10354var eventTypes$1 = {
10355 beforeInput: {
10356 phasedRegistrationNames: {
10357 bubbled: 'onBeforeInput',
10358 captured: 'onBeforeInputCapture'
10359 },
10360 dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
10361 },
10362 compositionEnd: {
10363 phasedRegistrationNames: {
10364 bubbled: 'onCompositionEnd',
10365 captured: 'onCompositionEndCapture'
10366 },
10367 dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10368 },
10369 compositionStart: {
10370 phasedRegistrationNames: {
10371 bubbled: 'onCompositionStart',
10372 captured: 'onCompositionStartCapture'
10373 },
10374 dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10375 },
10376 compositionUpdate: {
10377 phasedRegistrationNames: {
10378 bubbled: 'onCompositionUpdate',
10379 captured: 'onCompositionUpdateCapture'
10380 },
10381 dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
10382 }
10383}; // Track whether we've ever handled a keypress on the space key.
10384
10385var hasSpaceKeypress = false;
10386/**
10387 * Return whether a native keypress event is assumed to be a command.
10388 * This is required because Firefox fires `keypress` events for key commands
10389 * (cut, copy, select-all, etc.) even though no character is inserted.
10390 */
10391
10392function isKeypressCommand(nativeEvent) {
10393 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
10394 !(nativeEvent.ctrlKey && nativeEvent.altKey);
10395}
10396/**
10397 * Translate native top level events into event types.
10398 *
10399 * @param {string} topLevelType
10400 * @return {object}
10401 */
10402
10403
10404function getCompositionEventType(topLevelType) {
10405 switch (topLevelType) {
10406 case TOP_COMPOSITION_START:
10407 return eventTypes$1.compositionStart;
10408
10409 case TOP_COMPOSITION_END:
10410 return eventTypes$1.compositionEnd;
10411
10412 case TOP_COMPOSITION_UPDATE:
10413 return eventTypes$1.compositionUpdate;
10414 }
10415}
10416/**
10417 * Does our fallback best-guess model think this event signifies that
10418 * composition has begun?
10419 *
10420 * @param {string} topLevelType
10421 * @param {object} nativeEvent
10422 * @return {boolean}
10423 */
10424
10425
10426function isFallbackCompositionStart(topLevelType, nativeEvent) {
10427 return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
10428}
10429/**
10430 * Does our fallback mode think that this event is the end of composition?
10431 *
10432 * @param {string} topLevelType
10433 * @param {object} nativeEvent
10434 * @return {boolean}
10435 */
10436
10437
10438function isFallbackCompositionEnd(topLevelType, nativeEvent) {
10439 switch (topLevelType) {
10440 case TOP_KEY_UP:
10441 // Command keys insert or clear IME input.
10442 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
10443
10444 case TOP_KEY_DOWN:
10445 // Expect IME keyCode on each keydown. If we get any other
10446 // code we must have exited earlier.
10447 return nativeEvent.keyCode !== START_KEYCODE;
10448
10449 case TOP_KEY_PRESS:
10450 case TOP_MOUSE_DOWN:
10451 case TOP_BLUR:
10452 // Events are not possible without cancelling IME.
10453 return true;
10454
10455 default:
10456 return false;
10457 }
10458}
10459/**
10460 * Google Input Tools provides composition data via a CustomEvent,
10461 * with the `data` property populated in the `detail` object. If this
10462 * is available on the event object, use it. If not, this is a plain
10463 * composition event and we have nothing special to extract.
10464 *
10465 * @param {object} nativeEvent
10466 * @return {?string}
10467 */
10468
10469
10470function getDataFromCustomEvent(nativeEvent) {
10471 var detail = nativeEvent.detail;
10472
10473 if (typeof detail === 'object' && 'data' in detail) {
10474 return detail.data;
10475 }
10476
10477 return null;
10478}
10479/**
10480 * Check if a composition event was triggered by Korean IME.
10481 * Our fallback mode does not work well with IE's Korean IME,
10482 * so just use native composition events when Korean IME is used.
10483 * Although CompositionEvent.locale property is deprecated,
10484 * it is available in IE, where our fallback mode is enabled.
10485 *
10486 * @param {object} nativeEvent
10487 * @return {boolean}
10488 */
10489
10490
10491function isUsingKoreanIME(nativeEvent) {
10492 return nativeEvent.locale === 'ko';
10493} // Track the current IME composition status, if any.
10494
10495
10496var isComposing = false;
10497/**
10498 * @return {?object} A SyntheticCompositionEvent.
10499 */
10500
10501function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10502 var eventType;
10503 var fallbackData;
10504
10505 if (canUseCompositionEvent) {
10506 eventType = getCompositionEventType(topLevelType);
10507 } else if (!isComposing) {
10508 if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
10509 eventType = eventTypes$1.compositionStart;
10510 }
10511 } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10512 eventType = eventTypes$1.compositionEnd;
10513 }
10514
10515 if (!eventType) {
10516 return null;
10517 }
10518
10519 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
10520 // The current composition is stored statically and must not be
10521 // overwritten while composition continues.
10522 if (!isComposing && eventType === eventTypes$1.compositionStart) {
10523 isComposing = initialize(nativeEventTarget);
10524 } else if (eventType === eventTypes$1.compositionEnd) {
10525 if (isComposing) {
10526 fallbackData = getData();
10527 }
10528 }
10529 }
10530
10531 var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
10532
10533 if (fallbackData) {
10534 // Inject data generated from fallback path into the synthetic event.
10535 // This matches the property of native CompositionEventInterface.
10536 event.data = fallbackData;
10537 } else {
10538 var customData = getDataFromCustomEvent(nativeEvent);
10539
10540 if (customData !== null) {
10541 event.data = customData;
10542 }
10543 }
10544
10545 accumulateTwoPhaseDispatches(event);
10546 return event;
10547}
10548/**
10549 * @param {TopLevelType} topLevelType Number from `TopLevelType`.
10550 * @param {object} nativeEvent Native browser event.
10551 * @return {?string} The string corresponding to this `beforeInput` event.
10552 */
10553
10554
10555function getNativeBeforeInputChars(topLevelType, nativeEvent) {
10556 switch (topLevelType) {
10557 case TOP_COMPOSITION_END:
10558 return getDataFromCustomEvent(nativeEvent);
10559
10560 case TOP_KEY_PRESS:
10561 /**
10562 * If native `textInput` events are available, our goal is to make
10563 * use of them. However, there is a special case: the spacebar key.
10564 * In Webkit, preventing default on a spacebar `textInput` event
10565 * cancels character insertion, but it *also* causes the browser
10566 * to fall back to its default spacebar behavior of scrolling the
10567 * page.
10568 *
10569 * Tracking at:
10570 * https://code.google.com/p/chromium/issues/detail?id=355103
10571 *
10572 * To avoid this issue, use the keypress event as if no `textInput`
10573 * event is available.
10574 */
10575 var which = nativeEvent.which;
10576
10577 if (which !== SPACEBAR_CODE) {
10578 return null;
10579 }
10580
10581 hasSpaceKeypress = true;
10582 return SPACEBAR_CHAR;
10583
10584 case TOP_TEXT_INPUT:
10585 // Record the characters to be added to the DOM.
10586 var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
10587 // it at the keypress level and bail immediately. Android Chrome
10588 // doesn't give us keycodes, so we need to ignore it.
10589
10590 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
10591 return null;
10592 }
10593
10594 return chars;
10595
10596 default:
10597 // For other native event types, do nothing.
10598 return null;
10599 }
10600}
10601/**
10602 * For browsers that do not provide the `textInput` event, extract the
10603 * appropriate string to use for SyntheticInputEvent.
10604 *
10605 * @param {number} topLevelType Number from `TopLevelEventTypes`.
10606 * @param {object} nativeEvent Native browser event.
10607 * @return {?string} The fallback string for this `beforeInput` event.
10608 */
10609
10610
10611function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
10612 // If we are currently composing (IME) and using a fallback to do so,
10613 // try to extract the composed characters from the fallback object.
10614 // If composition event is available, we extract a string only at
10615 // compositionevent, otherwise extract it at fallback events.
10616 if (isComposing) {
10617 if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
10618 var chars = getData();
10619 reset();
10620 isComposing = false;
10621 return chars;
10622 }
10623
10624 return null;
10625 }
10626
10627 switch (topLevelType) {
10628 case TOP_PASTE:
10629 // If a paste event occurs after a keypress, throw out the input
10630 // chars. Paste events should not lead to BeforeInput events.
10631 return null;
10632
10633 case TOP_KEY_PRESS:
10634 /**
10635 * As of v27, Firefox may fire keypress events even when no character
10636 * will be inserted. A few possibilities:
10637 *
10638 * - `which` is `0`. Arrow keys, Esc key, etc.
10639 *
10640 * - `which` is the pressed key code, but no char is available.
10641 * Ex: 'AltGr + d` in Polish. There is no modified character for
10642 * this key combination and no character is inserted into the
10643 * document, but FF fires the keypress for char code `100` anyway.
10644 * No `input` event will occur.
10645 *
10646 * - `which` is the pressed key code, but a command combination is
10647 * being used. Ex: `Cmd+C`. No character is inserted, and no
10648 * `input` event will occur.
10649 */
10650 if (!isKeypressCommand(nativeEvent)) {
10651 // IE fires the `keypress` event when a user types an emoji via
10652 // Touch keyboard of Windows. In such a case, the `char` property
10653 // holds an emoji character like `\uD83D\uDE0A`. Because its length
10654 // is 2, the property `which` does not represent an emoji correctly.
10655 // In such a case, we directly return the `char` property instead of
10656 // using `which`.
10657 if (nativeEvent.char && nativeEvent.char.length > 1) {
10658 return nativeEvent.char;
10659 } else if (nativeEvent.which) {
10660 return String.fromCharCode(nativeEvent.which);
10661 }
10662 }
10663
10664 return null;
10665
10666 case TOP_COMPOSITION_END:
10667 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
10668
10669 default:
10670 return null;
10671 }
10672}
10673/**
10674 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
10675 * `textInput` or fallback behavior.
10676 *
10677 * @return {?object} A SyntheticInputEvent.
10678 */
10679
10680
10681function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
10682 var chars;
10683
10684 if (canUseTextInputEvent) {
10685 chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
10686 } else {
10687 chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
10688 } // If no characters are being inserted, no BeforeInput event should
10689 // be fired.
10690
10691
10692 if (!chars) {
10693 return null;
10694 }
10695
10696 var event = SyntheticInputEvent.getPooled(eventTypes$1.beforeInput, targetInst, nativeEvent, nativeEventTarget);
10697 event.data = chars;
10698 accumulateTwoPhaseDispatches(event);
10699 return event;
10700}
10701/**
10702 * Create an `onBeforeInput` event to match
10703 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
10704 *
10705 * This event plugin is based on the native `textInput` event
10706 * available in Chrome, Safari, Opera, and IE. This event fires after
10707 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
10708 *
10709 * `beforeInput` is spec'd but not implemented in any browsers, and
10710 * the `input` event does not provide any useful information about what has
10711 * actually been added, contrary to the spec. Thus, `textInput` is the best
10712 * available event to identify the characters that have actually been inserted
10713 * into the target node.
10714 *
10715 * This plugin is also responsible for emitting `composition` events, thus
10716 * allowing us to share composition fallback code for both `beforeInput` and
10717 * `composition` event types.
10718 */
10719
10720
10721var BeforeInputEventPlugin = {
10722 eventTypes: eventTypes$1,
10723 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10724 var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10725 var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
10726
10727 if (composition === null) {
10728 return beforeInput;
10729 }
10730
10731 if (beforeInput === null) {
10732 return composition;
10733 }
10734
10735 return [composition, beforeInput];
10736 }
10737};
10738
10739/**
10740 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
10741 */
10742var supportedInputTypes = {
10743 color: true,
10744 date: true,
10745 datetime: true,
10746 'datetime-local': true,
10747 email: true,
10748 month: true,
10749 number: true,
10750 password: true,
10751 range: true,
10752 search: true,
10753 tel: true,
10754 text: true,
10755 time: true,
10756 url: true,
10757 week: true
10758};
10759
10760function isTextInputElement(elem) {
10761 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
10762
10763 if (nodeName === 'input') {
10764 return !!supportedInputTypes[elem.type];
10765 }
10766
10767 if (nodeName === 'textarea') {
10768 return true;
10769 }
10770
10771 return false;
10772}
10773
10774var eventTypes$2 = {
10775 change: {
10776 phasedRegistrationNames: {
10777 bubbled: 'onChange',
10778 captured: 'onChangeCapture'
10779 },
10780 dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
10781 }
10782};
10783
10784function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
10785 var event = SyntheticEvent.getPooled(eventTypes$2.change, inst, nativeEvent, target);
10786 event.type = 'change'; // Flag this event loop as needing state restore.
10787
10788 enqueueStateRestore(target);
10789 accumulateTwoPhaseDispatches(event);
10790 return event;
10791}
10792/**
10793 * For IE shims
10794 */
10795
10796
10797var activeElement = null;
10798var activeElementInst = null;
10799/**
10800 * SECTION: handle `change` event
10801 */
10802
10803function shouldUseChangeEvent(elem) {
10804 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
10805 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
10806}
10807
10808function manualDispatchChangeEvent(nativeEvent) {
10809 var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
10810 // other events and have it go through ReactBrowserEventEmitter. Since it
10811 // doesn't, we manually listen for the events and so we have to enqueue and
10812 // process the abstract event manually.
10813 //
10814 // Batching is necessary here in order to ensure that all event handlers run
10815 // before the next rerender (including event handlers attached to ancestor
10816 // elements instead of directly on the input). Without this, controlled
10817 // components don't work properly in conjunction with event bubbling because
10818 // the component is rerendered and the value reverted before all the event
10819 // handlers can run. See https://github.com/facebook/react/issues/708.
10820
10821 batchedUpdates(runEventInBatch, event);
10822}
10823
10824function runEventInBatch(event) {
10825 runEventsInBatch(event);
10826}
10827
10828function getInstIfValueChanged(targetInst) {
10829 var targetNode = getNodeFromInstance$1(targetInst);
10830
10831 if (updateValueIfChanged(targetNode)) {
10832 return targetInst;
10833 }
10834}
10835
10836function getTargetInstForChangeEvent(topLevelType, targetInst) {
10837 if (topLevelType === TOP_CHANGE) {
10838 return targetInst;
10839 }
10840}
10841/**
10842 * SECTION: handle `input` event
10843 */
10844
10845
10846var isInputEventSupported = false;
10847
10848if (canUseDOM) {
10849 // IE9 claims to support the input event but fails to trigger it when
10850 // deleting text, so we ignore its input events.
10851 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
10852}
10853/**
10854 * (For IE <=9) Starts tracking propertychange events on the passed-in element
10855 * and override the value property so that we can distinguish user events from
10856 * value changes in JS.
10857 */
10858
10859
10860function startWatchingForValueChange(target, targetInst) {
10861 activeElement = target;
10862 activeElementInst = targetInst;
10863 activeElement.attachEvent('onpropertychange', handlePropertyChange);
10864}
10865/**
10866 * (For IE <=9) Removes the event listeners from the currently-tracked element,
10867 * if any exists.
10868 */
10869
10870
10871function stopWatchingForValueChange() {
10872 if (!activeElement) {
10873 return;
10874 }
10875
10876 activeElement.detachEvent('onpropertychange', handlePropertyChange);
10877 activeElement = null;
10878 activeElementInst = null;
10879}
10880/**
10881 * (For IE <=9) Handles a propertychange event, sending a `change` event if
10882 * the value of the active element has changed.
10883 */
10884
10885
10886function handlePropertyChange(nativeEvent) {
10887 if (nativeEvent.propertyName !== 'value') {
10888 return;
10889 }
10890
10891 if (getInstIfValueChanged(activeElementInst)) {
10892 manualDispatchChangeEvent(nativeEvent);
10893 }
10894}
10895
10896function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
10897 if (topLevelType === TOP_FOCUS) {
10898 // In IE9, propertychange fires for most input events but is buggy and
10899 // doesn't fire when text is deleted, but conveniently, selectionchange
10900 // appears to fire in all of the remaining cases so we catch those and
10901 // forward the event if the value has changed
10902 // In either case, we don't want to call the event handler if the value
10903 // is changed from JS so we redefine a setter for `.value` that updates
10904 // our activeElementValue variable, allowing us to ignore those changes
10905 //
10906 // stopWatching() should be a noop here but we call it just in case we
10907 // missed a blur event somehow.
10908 stopWatchingForValueChange();
10909 startWatchingForValueChange(target, targetInst);
10910 } else if (topLevelType === TOP_BLUR) {
10911 stopWatchingForValueChange();
10912 }
10913} // For IE8 and IE9.
10914
10915
10916function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
10917 if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
10918 // On the selectionchange event, the target is just document which isn't
10919 // helpful for us so just check activeElement instead.
10920 //
10921 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
10922 // propertychange on the first input event after setting `value` from a
10923 // script and fires only keydown, keypress, keyup. Catching keyup usually
10924 // gets it and catching keydown lets us fire an event for the first
10925 // keystroke if user does a key repeat (it'll be a little delayed: right
10926 // before the second keystroke). Other input methods (e.g., paste) seem to
10927 // fire selectionchange normally.
10928 return getInstIfValueChanged(activeElementInst);
10929 }
10930}
10931/**
10932 * SECTION: handle `click` event
10933 */
10934
10935
10936function shouldUseClickEvent(elem) {
10937 // Use the `click` event to detect changes to checkbox and radio inputs.
10938 // This approach works across all browsers, whereas `change` does not fire
10939 // until `blur` in IE8.
10940 var nodeName = elem.nodeName;
10941 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
10942}
10943
10944function getTargetInstForClickEvent(topLevelType, targetInst) {
10945 if (topLevelType === TOP_CLICK) {
10946 return getInstIfValueChanged(targetInst);
10947 }
10948}
10949
10950function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
10951 if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
10952 return getInstIfValueChanged(targetInst);
10953 }
10954}
10955
10956function handleControlledInputBlur(node) {
10957 var state = node._wrapperState;
10958
10959 if (!state || !state.controlled || node.type !== 'number') {
10960 return;
10961 }
10962
10963 if (!disableInputAttributeSyncing) {
10964 // If controlled, assign the value attribute to the current value on blur
10965 setDefaultValue(node, 'number', node.value);
10966 }
10967}
10968/**
10969 * This plugin creates an `onChange` event that normalizes change events
10970 * across form elements. This event fires at a time when it's possible to
10971 * change the element's value without seeing a flicker.
10972 *
10973 * Supported elements are:
10974 * - input (see `isTextInputElement`)
10975 * - textarea
10976 * - select
10977 */
10978
10979
10980var ChangeEventPlugin = {
10981 eventTypes: eventTypes$2,
10982 _isInputEventSupported: isInputEventSupported,
10983 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
10984 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
10985 var getTargetInstFunc, handleEventFunc;
10986
10987 if (shouldUseChangeEvent(targetNode)) {
10988 getTargetInstFunc = getTargetInstForChangeEvent;
10989 } else if (isTextInputElement(targetNode)) {
10990 if (isInputEventSupported) {
10991 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
10992 } else {
10993 getTargetInstFunc = getTargetInstForInputEventPolyfill;
10994 handleEventFunc = handleEventsForInputEventPolyfill;
10995 }
10996 } else if (shouldUseClickEvent(targetNode)) {
10997 getTargetInstFunc = getTargetInstForClickEvent;
10998 }
10999
11000 if (getTargetInstFunc) {
11001 var inst = getTargetInstFunc(topLevelType, targetInst);
11002
11003 if (inst) {
11004 var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
11005 return event;
11006 }
11007 }
11008
11009 if (handleEventFunc) {
11010 handleEventFunc(topLevelType, targetNode, targetInst);
11011 } // When blurring, set the value attribute for number inputs
11012
11013
11014 if (topLevelType === TOP_BLUR) {
11015 handleControlledInputBlur(targetNode);
11016 }
11017 }
11018};
11019
11020/**
11021 * Module that is injectable into `EventPluginHub`, that specifies a
11022 * deterministic ordering of `EventPlugin`s. A convenient way to reason about
11023 * plugins, without having to package every one of them. This is better than
11024 * having plugins be ordered in the same order that they are injected because
11025 * that ordering would be influenced by the packaging order.
11026 * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
11027 * preventing default on events is convenient in `SimpleEventPlugin` handlers.
11028 */
11029var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
11030
11031var eventTypes$3 = {
11032 mouseEnter: {
11033 registrationName: 'onMouseEnter',
11034 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
11035 },
11036 mouseLeave: {
11037 registrationName: 'onMouseLeave',
11038 dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
11039 },
11040 pointerEnter: {
11041 registrationName: 'onPointerEnter',
11042 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
11043 },
11044 pointerLeave: {
11045 registrationName: 'onPointerLeave',
11046 dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
11047 }
11048}; // We track the lastNativeEvent to ensure that when we encounter
11049// cases where we process the same nativeEvent multiple times,
11050// which can happen when have multiple ancestors, that we don't
11051// duplicate enter
11052
11053var lastNativeEvent;
11054var EnterLeaveEventPlugin = {
11055 eventTypes: eventTypes$3,
11056
11057 /**
11058 * For almost every interaction we care about, there will be both a top-level
11059 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
11060 * we do not extract duplicate events. However, moving the mouse into the
11061 * browser from outside will not fire a `mouseout` event. In this case, we use
11062 * the `mouseover` top-level event.
11063 */
11064 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11065 var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
11066 var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
11067
11068 if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
11069 // If this is an over event with a target, then we've already dispatched
11070 // the event in the out event of the other target. If this is replayed,
11071 // then it's because we couldn't dispatch against this target previously
11072 // so we have to do it now instead.
11073 return null;
11074 }
11075
11076 if (!isOutEvent && !isOverEvent) {
11077 // Must not be a mouse or pointer in or out - ignoring.
11078 return null;
11079 }
11080
11081 var win;
11082
11083 if (nativeEventTarget.window === nativeEventTarget) {
11084 // `nativeEventTarget` is probably a window object.
11085 win = nativeEventTarget;
11086 } else {
11087 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
11088 var doc = nativeEventTarget.ownerDocument;
11089
11090 if (doc) {
11091 win = doc.defaultView || doc.parentWindow;
11092 } else {
11093 win = window;
11094 }
11095 }
11096
11097 var from;
11098 var to;
11099
11100 if (isOutEvent) {
11101 from = targetInst;
11102 var related = nativeEvent.relatedTarget || nativeEvent.toElement;
11103 to = related ? getClosestInstanceFromNode(related) : null;
11104
11105 if (to !== null) {
11106 var nearestMounted = getNearestMountedFiber(to);
11107
11108 if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
11109 to = null;
11110 }
11111 }
11112 } else {
11113 // Moving to a node from outside the window.
11114 from = null;
11115 to = targetInst;
11116 }
11117
11118 if (from === to) {
11119 // Nothing pertains to our managed components.
11120 return null;
11121 }
11122
11123 var eventInterface, leaveEventType, enterEventType, eventTypePrefix;
11124
11125 if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
11126 eventInterface = SyntheticMouseEvent;
11127 leaveEventType = eventTypes$3.mouseLeave;
11128 enterEventType = eventTypes$3.mouseEnter;
11129 eventTypePrefix = 'mouse';
11130 } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
11131 eventInterface = SyntheticPointerEvent;
11132 leaveEventType = eventTypes$3.pointerLeave;
11133 enterEventType = eventTypes$3.pointerEnter;
11134 eventTypePrefix = 'pointer';
11135 }
11136
11137 var fromNode = from == null ? win : getNodeFromInstance$1(from);
11138 var toNode = to == null ? win : getNodeFromInstance$1(to);
11139 var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
11140 leave.type = eventTypePrefix + 'leave';
11141 leave.target = fromNode;
11142 leave.relatedTarget = toNode;
11143 var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
11144 enter.type = eventTypePrefix + 'enter';
11145 enter.target = toNode;
11146 enter.relatedTarget = fromNode;
11147 accumulateEnterLeaveDispatches(leave, enter, from, to);
11148
11149 if (nativeEvent === lastNativeEvent) {
11150 lastNativeEvent = null;
11151 return [leave];
11152 }
11153
11154 lastNativeEvent = nativeEvent;
11155 return [leave, enter];
11156 }
11157};
11158
11159/**
11160 * inlined Object.is polyfill to avoid requiring consumers ship their own
11161 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
11162 */
11163function is(x, y) {
11164 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
11165 ;
11166}
11167
11168var is$1 = typeof Object.is === 'function' ? Object.is : is;
11169
11170var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
11171/**
11172 * Performs equality by iterating through keys on an object and returning false
11173 * when any key has values which are not strictly equal between the arguments.
11174 * Returns true when the values of all keys are strictly equal.
11175 */
11176
11177function shallowEqual(objA, objB) {
11178 if (is$1(objA, objB)) {
11179 return true;
11180 }
11181
11182 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
11183 return false;
11184 }
11185
11186 var keysA = Object.keys(objA);
11187 var keysB = Object.keys(objB);
11188
11189 if (keysA.length !== keysB.length) {
11190 return false;
11191 } // Test for A's keys different from B.
11192
11193
11194 for (var i = 0; i < keysA.length; i++) {
11195 if (!hasOwnProperty$2.call(objB, keysA[i]) || !is$1(objA[keysA[i]], objB[keysA[i]])) {
11196 return false;
11197 }
11198 }
11199
11200 return true;
11201}
11202
11203var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
11204var eventTypes$4 = {
11205 select: {
11206 phasedRegistrationNames: {
11207 bubbled: 'onSelect',
11208 captured: 'onSelectCapture'
11209 },
11210 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]
11211 }
11212};
11213var activeElement$1 = null;
11214var activeElementInst$1 = null;
11215var lastSelection = null;
11216var mouseDown = false;
11217/**
11218 * Get an object which is a unique representation of the current selection.
11219 *
11220 * The return value will not be consistent across nodes or browsers, but
11221 * two identical selections on the same node will return identical objects.
11222 *
11223 * @param {DOMElement} node
11224 * @return {object}
11225 */
11226
11227function getSelection$1(node) {
11228 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
11229 return {
11230 start: node.selectionStart,
11231 end: node.selectionEnd
11232 };
11233 } else {
11234 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
11235 var selection = win.getSelection();
11236 return {
11237 anchorNode: selection.anchorNode,
11238 anchorOffset: selection.anchorOffset,
11239 focusNode: selection.focusNode,
11240 focusOffset: selection.focusOffset
11241 };
11242 }
11243}
11244/**
11245 * Get document associated with the event target.
11246 *
11247 * @param {object} nativeEventTarget
11248 * @return {Document}
11249 */
11250
11251
11252function getEventTargetDocument(eventTarget) {
11253 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
11254}
11255/**
11256 * Poll selection to see whether it's changed.
11257 *
11258 * @param {object} nativeEvent
11259 * @param {object} nativeEventTarget
11260 * @return {?SyntheticEvent}
11261 */
11262
11263
11264function constructSelectEvent(nativeEvent, nativeEventTarget) {
11265 // Ensure we have the right element, and that the user is not dragging a
11266 // selection (this matches native `select` event behavior). In HTML5, select
11267 // fires only on input and textarea thus if there's no focused element we
11268 // won't dispatch.
11269 var doc = getEventTargetDocument(nativeEventTarget);
11270
11271 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
11272 return null;
11273 } // Only fire when selection has actually changed.
11274
11275
11276 var currentSelection = getSelection$1(activeElement$1);
11277
11278 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
11279 lastSelection = currentSelection;
11280 var syntheticEvent = SyntheticEvent.getPooled(eventTypes$4.select, activeElementInst$1, nativeEvent, nativeEventTarget);
11281 syntheticEvent.type = 'select';
11282 syntheticEvent.target = activeElement$1;
11283 accumulateTwoPhaseDispatches(syntheticEvent);
11284 return syntheticEvent;
11285 }
11286
11287 return null;
11288}
11289/**
11290 * This plugin creates an `onSelect` event that normalizes select events
11291 * across form elements.
11292 *
11293 * Supported elements are:
11294 * - input (see `isTextInputElement`)
11295 * - textarea
11296 * - contentEditable
11297 *
11298 * This differs from native browser implementations in the following ways:
11299 * - Fires on contentEditable fields as well as inputs.
11300 * - Fires for collapsed selection.
11301 * - Fires after user input.
11302 */
11303
11304
11305var SelectEventPlugin = {
11306 eventTypes: eventTypes$4,
11307 extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
11308 var doc = getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
11309 // not extract events. See #3639.
11310
11311 if (!doc || !isListeningToAllDependencies('onSelect', doc)) {
11312 return null;
11313 }
11314
11315 var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
11316
11317 switch (topLevelType) {
11318 // Track the input node that has focus.
11319 case TOP_FOCUS:
11320 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
11321 activeElement$1 = targetNode;
11322 activeElementInst$1 = targetInst;
11323 lastSelection = null;
11324 }
11325
11326 break;
11327
11328 case TOP_BLUR:
11329 activeElement$1 = null;
11330 activeElementInst$1 = null;
11331 lastSelection = null;
11332 break;
11333 // Don't fire the event while the user is dragging. This matches the
11334 // semantics of the native select event.
11335
11336 case TOP_MOUSE_DOWN:
11337 mouseDown = true;
11338 break;
11339
11340 case TOP_CONTEXT_MENU:
11341 case TOP_MOUSE_UP:
11342 case TOP_DRAG_END:
11343 mouseDown = false;
11344 return constructSelectEvent(nativeEvent, nativeEventTarget);
11345 // Chrome and IE fire non-standard event when selection is changed (and
11346 // sometimes when it hasn't). IE's event fires out of order with respect
11347 // to key and input events on deletion, so we discard it.
11348 //
11349 // Firefox doesn't support selectionchange, so check selection status
11350 // after each key entry. The selection changes after keydown and before
11351 // keyup, but we check on keydown as well in the case of holding down a
11352 // key, when multiple keydown events are fired but only one keyup is.
11353 // This is also our approach for IE handling, for the reason above.
11354
11355 case TOP_SELECTION_CHANGE:
11356 if (skipSelectionChangeEvent) {
11357 break;
11358 }
11359
11360 // falls through
11361
11362 case TOP_KEY_DOWN:
11363 case TOP_KEY_UP:
11364 return constructSelectEvent(nativeEvent, nativeEventTarget);
11365 }
11366
11367 return null;
11368 }
11369};
11370
11371/**
11372 * Inject modules for resolving DOM hierarchy and plugin ordering.
11373 */
11374
11375injection.injectEventPluginOrder(DOMEventPluginOrder);
11376setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
11377/**
11378 * Some important event plugins included by default (without having to require
11379 * them).
11380 */
11381
11382injection.injectEventPluginsByName({
11383 SimpleEventPlugin: SimpleEventPlugin,
11384 EnterLeaveEventPlugin: EnterLeaveEventPlugin,
11385 ChangeEventPlugin: ChangeEventPlugin,
11386 SelectEventPlugin: SelectEventPlugin,
11387 BeforeInputEventPlugin: BeforeInputEventPlugin
11388});
11389
11390// Prefix measurements so that it's possible to filter them.
11391// Longer prefixes are hard to read in DevTools.
11392var reactEmoji = "\u269B";
11393var warningEmoji = "\u26D4";
11394var 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.
11395// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
11396
11397var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
11398// Reusing `currentFiber` would be confusing for this because user code fiber
11399// can change during commit phase too, but we don't need to unwind it (since
11400// lifecycles in the commit phase don't resemble a tree).
11401
11402var currentPhase = null;
11403var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
11404// so we will keep track of it, and include it in the report.
11405// Track commits caused by cascading updates.
11406
11407var isCommitting = false;
11408var hasScheduledUpdateInCurrentCommit = false;
11409var hasScheduledUpdateInCurrentPhase = false;
11410var commitCountInCurrentWorkLoop = 0;
11411var effectCountInCurrentCommit = 0;
11412// to avoid stretch the commit phase with measurement overhead.
11413
11414var labelsInCurrentCommit = new Set();
11415
11416var formatMarkName = function (markName) {
11417 return reactEmoji + " " + markName;
11418};
11419
11420var formatLabel = function (label, warning) {
11421 var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
11422 var suffix = warning ? " Warning: " + warning : '';
11423 return "" + prefix + label + suffix;
11424};
11425
11426var beginMark = function (markName) {
11427 performance.mark(formatMarkName(markName));
11428};
11429
11430var clearMark = function (markName) {
11431 performance.clearMarks(formatMarkName(markName));
11432};
11433
11434var endMark = function (label, markName, warning) {
11435 var formattedMarkName = formatMarkName(markName);
11436 var formattedLabel = formatLabel(label, warning);
11437
11438 try {
11439 performance.measure(formattedLabel, formattedMarkName);
11440 } catch (err) {} // If previous mark was missing for some reason, this will throw.
11441 // This could only happen if React crashed in an unexpected place earlier.
11442 // Don't pile on with more errors.
11443 // Clear marks immediately to avoid growing buffer.
11444
11445
11446 performance.clearMarks(formattedMarkName);
11447 performance.clearMeasures(formattedLabel);
11448};
11449
11450var getFiberMarkName = function (label, debugID) {
11451 return label + " (#" + debugID + ")";
11452};
11453
11454var getFiberLabel = function (componentName, isMounted, phase) {
11455 if (phase === null) {
11456 // These are composite component total time measurements.
11457 return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
11458 } else {
11459 // Composite component methods.
11460 return componentName + "." + phase;
11461 }
11462};
11463
11464var beginFiberMark = function (fiber, phase) {
11465 var componentName = getComponentName(fiber.type) || 'Unknown';
11466 var debugID = fiber._debugID;
11467 var isMounted = fiber.alternate !== null;
11468 var label = getFiberLabel(componentName, isMounted, phase);
11469
11470 if (isCommitting && labelsInCurrentCommit.has(label)) {
11471 // During the commit phase, we don't show duplicate labels because
11472 // there is a fixed overhead for every measurement, and we don't
11473 // want to stretch the commit phase beyond necessary.
11474 return false;
11475 }
11476
11477 labelsInCurrentCommit.add(label);
11478 var markName = getFiberMarkName(label, debugID);
11479 beginMark(markName);
11480 return true;
11481};
11482
11483var clearFiberMark = function (fiber, phase) {
11484 var componentName = getComponentName(fiber.type) || 'Unknown';
11485 var debugID = fiber._debugID;
11486 var isMounted = fiber.alternate !== null;
11487 var label = getFiberLabel(componentName, isMounted, phase);
11488 var markName = getFiberMarkName(label, debugID);
11489 clearMark(markName);
11490};
11491
11492var endFiberMark = function (fiber, phase, warning) {
11493 var componentName = getComponentName(fiber.type) || 'Unknown';
11494 var debugID = fiber._debugID;
11495 var isMounted = fiber.alternate !== null;
11496 var label = getFiberLabel(componentName, isMounted, phase);
11497 var markName = getFiberMarkName(label, debugID);
11498 endMark(label, markName, warning);
11499};
11500
11501var shouldIgnoreFiber = function (fiber) {
11502 // Host components should be skipped in the timeline.
11503 // We could check typeof fiber.type, but does this work with RN?
11504 switch (fiber.tag) {
11505 case HostRoot:
11506 case HostComponent:
11507 case HostText:
11508 case HostPortal:
11509 case Fragment:
11510 case ContextProvider:
11511 case ContextConsumer:
11512 case Mode:
11513 return true;
11514
11515 default:
11516 return false;
11517 }
11518};
11519
11520var clearPendingPhaseMeasurement = function () {
11521 if (currentPhase !== null && currentPhaseFiber !== null) {
11522 clearFiberMark(currentPhaseFiber, currentPhase);
11523 }
11524
11525 currentPhaseFiber = null;
11526 currentPhase = null;
11527 hasScheduledUpdateInCurrentPhase = false;
11528};
11529
11530var pauseTimers = function () {
11531 // Stops all currently active measurements so that they can be resumed
11532 // if we continue in a later deferred loop from the same unit of work.
11533 var fiber = currentFiber;
11534
11535 while (fiber) {
11536 if (fiber._debugIsCurrentlyTiming) {
11537 endFiberMark(fiber, null, null);
11538 }
11539
11540 fiber = fiber.return;
11541 }
11542};
11543
11544var resumeTimersRecursively = function (fiber) {
11545 if (fiber.return !== null) {
11546 resumeTimersRecursively(fiber.return);
11547 }
11548
11549 if (fiber._debugIsCurrentlyTiming) {
11550 beginFiberMark(fiber, null);
11551 }
11552};
11553
11554var resumeTimers = function () {
11555 // Resumes all measurements that were active during the last deferred loop.
11556 if (currentFiber !== null) {
11557 resumeTimersRecursively(currentFiber);
11558 }
11559};
11560
11561function recordEffect() {
11562 if (enableUserTimingAPI) {
11563 effectCountInCurrentCommit++;
11564 }
11565}
11566function recordScheduleUpdate() {
11567 if (enableUserTimingAPI) {
11568 if (isCommitting) {
11569 hasScheduledUpdateInCurrentCommit = true;
11570 }
11571
11572 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
11573 hasScheduledUpdateInCurrentPhase = true;
11574 }
11575 }
11576}
11577
11578
11579function startWorkTimer(fiber) {
11580 if (enableUserTimingAPI) {
11581 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11582 return;
11583 } // If we pause, this is the fiber to unwind from.
11584
11585
11586 currentFiber = fiber;
11587
11588 if (!beginFiberMark(fiber, null)) {
11589 return;
11590 }
11591
11592 fiber._debugIsCurrentlyTiming = true;
11593 }
11594}
11595function cancelWorkTimer(fiber) {
11596 if (enableUserTimingAPI) {
11597 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11598 return;
11599 } // Remember we shouldn't complete measurement for this fiber.
11600 // Otherwise flamechart will be deep even for small updates.
11601
11602
11603 fiber._debugIsCurrentlyTiming = false;
11604 clearFiberMark(fiber, null);
11605 }
11606}
11607function stopWorkTimer(fiber) {
11608 if (enableUserTimingAPI) {
11609 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11610 return;
11611 } // If we pause, its parent is the fiber to unwind from.
11612
11613
11614 currentFiber = fiber.return;
11615
11616 if (!fiber._debugIsCurrentlyTiming) {
11617 return;
11618 }
11619
11620 fiber._debugIsCurrentlyTiming = false;
11621 endFiberMark(fiber, null, null);
11622 }
11623}
11624function stopFailedWorkTimer(fiber) {
11625 if (enableUserTimingAPI) {
11626 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
11627 return;
11628 } // If we pause, its parent is the fiber to unwind from.
11629
11630
11631 currentFiber = fiber.return;
11632
11633 if (!fiber._debugIsCurrentlyTiming) {
11634 return;
11635 }
11636
11637 fiber._debugIsCurrentlyTiming = false;
11638 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
11639 endFiberMark(fiber, null, warning);
11640 }
11641}
11642function startPhaseTimer(fiber, phase) {
11643 if (enableUserTimingAPI) {
11644 if (!supportsUserTiming) {
11645 return;
11646 }
11647
11648 clearPendingPhaseMeasurement();
11649
11650 if (!beginFiberMark(fiber, phase)) {
11651 return;
11652 }
11653
11654 currentPhaseFiber = fiber;
11655 currentPhase = phase;
11656 }
11657}
11658function stopPhaseTimer() {
11659 if (enableUserTimingAPI) {
11660 if (!supportsUserTiming) {
11661 return;
11662 }
11663
11664 if (currentPhase !== null && currentPhaseFiber !== null) {
11665 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
11666 endFiberMark(currentPhaseFiber, currentPhase, warning);
11667 }
11668
11669 currentPhase = null;
11670 currentPhaseFiber = null;
11671 }
11672}
11673function startWorkLoopTimer(nextUnitOfWork) {
11674 if (enableUserTimingAPI) {
11675 currentFiber = nextUnitOfWork;
11676
11677 if (!supportsUserTiming) {
11678 return;
11679 }
11680
11681 commitCountInCurrentWorkLoop = 0; // This is top level call.
11682 // Any other measurements are performed within.
11683
11684 beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.
11685
11686 resumeTimers();
11687 }
11688}
11689function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
11690 if (enableUserTimingAPI) {
11691 if (!supportsUserTiming) {
11692 return;
11693 }
11694
11695 var warning = null;
11696
11697 if (interruptedBy !== null) {
11698 if (interruptedBy.tag === HostRoot) {
11699 warning = 'A top-level update interrupted the previous render';
11700 } else {
11701 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
11702 warning = "An update to " + componentName + " interrupted the previous render";
11703 }
11704 } else if (commitCountInCurrentWorkLoop > 1) {
11705 warning = 'There were cascading updates';
11706 }
11707
11708 commitCountInCurrentWorkLoop = 0;
11709 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.
11710
11711 pauseTimers();
11712 endMark(label, '(React Tree Reconciliation)', warning);
11713 }
11714}
11715function startCommitTimer() {
11716 if (enableUserTimingAPI) {
11717 if (!supportsUserTiming) {
11718 return;
11719 }
11720
11721 isCommitting = true;
11722 hasScheduledUpdateInCurrentCommit = false;
11723 labelsInCurrentCommit.clear();
11724 beginMark('(Committing Changes)');
11725 }
11726}
11727function stopCommitTimer() {
11728 if (enableUserTimingAPI) {
11729 if (!supportsUserTiming) {
11730 return;
11731 }
11732
11733 var warning = null;
11734
11735 if (hasScheduledUpdateInCurrentCommit) {
11736 warning = 'Lifecycle hook scheduled a cascading update';
11737 } else if (commitCountInCurrentWorkLoop > 0) {
11738 warning = 'Caused by a cascading update in earlier commit';
11739 }
11740
11741 hasScheduledUpdateInCurrentCommit = false;
11742 commitCountInCurrentWorkLoop++;
11743 isCommitting = false;
11744 labelsInCurrentCommit.clear();
11745 endMark('(Committing Changes)', '(Committing Changes)', warning);
11746 }
11747}
11748function startCommitSnapshotEffectsTimer() {
11749 if (enableUserTimingAPI) {
11750 if (!supportsUserTiming) {
11751 return;
11752 }
11753
11754 effectCountInCurrentCommit = 0;
11755 beginMark('(Committing Snapshot Effects)');
11756 }
11757}
11758function stopCommitSnapshotEffectsTimer() {
11759 if (enableUserTimingAPI) {
11760 if (!supportsUserTiming) {
11761 return;
11762 }
11763
11764 var count = effectCountInCurrentCommit;
11765 effectCountInCurrentCommit = 0;
11766 endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
11767 }
11768}
11769function startCommitHostEffectsTimer() {
11770 if (enableUserTimingAPI) {
11771 if (!supportsUserTiming) {
11772 return;
11773 }
11774
11775 effectCountInCurrentCommit = 0;
11776 beginMark('(Committing Host Effects)');
11777 }
11778}
11779function stopCommitHostEffectsTimer() {
11780 if (enableUserTimingAPI) {
11781 if (!supportsUserTiming) {
11782 return;
11783 }
11784
11785 var count = effectCountInCurrentCommit;
11786 effectCountInCurrentCommit = 0;
11787 endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
11788 }
11789}
11790function startCommitLifeCyclesTimer() {
11791 if (enableUserTimingAPI) {
11792 if (!supportsUserTiming) {
11793 return;
11794 }
11795
11796 effectCountInCurrentCommit = 0;
11797 beginMark('(Calling Lifecycle Methods)');
11798 }
11799}
11800function stopCommitLifeCyclesTimer() {
11801 if (enableUserTimingAPI) {
11802 if (!supportsUserTiming) {
11803 return;
11804 }
11805
11806 var count = effectCountInCurrentCommit;
11807 effectCountInCurrentCommit = 0;
11808 endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
11809 }
11810}
11811
11812var valueStack = [];
11813var fiberStack;
11814
11815{
11816 fiberStack = [];
11817}
11818
11819var index = -1;
11820
11821function createCursor(defaultValue) {
11822 return {
11823 current: defaultValue
11824 };
11825}
11826
11827function pop(cursor, fiber) {
11828 if (index < 0) {
11829 {
11830 warningWithoutStack$1(false, 'Unexpected pop.');
11831 }
11832
11833 return;
11834 }
11835
11836 {
11837 if (fiber !== fiberStack[index]) {
11838 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
11839 }
11840 }
11841
11842 cursor.current = valueStack[index];
11843 valueStack[index] = null;
11844
11845 {
11846 fiberStack[index] = null;
11847 }
11848
11849 index--;
11850}
11851
11852function push(cursor, value, fiber) {
11853 index++;
11854 valueStack[index] = cursor.current;
11855
11856 {
11857 fiberStack[index] = fiber;
11858 }
11859
11860 cursor.current = value;
11861}
11862
11863var warnedAboutMissingGetChildContext;
11864
11865{
11866 warnedAboutMissingGetChildContext = {};
11867}
11868
11869var emptyContextObject = {};
11870
11871{
11872 Object.freeze(emptyContextObject);
11873} // A cursor to the current merged context object on the stack.
11874
11875
11876var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
11877
11878var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
11879// We use this to get access to the parent context after we have already
11880// pushed the next context provider, and now need to merge their contexts.
11881
11882var previousContext = emptyContextObject;
11883
11884function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
11885 if (disableLegacyContext) {
11886 return emptyContextObject;
11887 } else {
11888 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
11889 // If the fiber is a context provider itself, when we read its context
11890 // we may have already pushed its own child context on the stack. A context
11891 // provider should not "see" its own child context. Therefore we read the
11892 // previous (parent) context instead for a context provider.
11893 return previousContext;
11894 }
11895
11896 return contextStackCursor.current;
11897 }
11898}
11899
11900function cacheContext(workInProgress, unmaskedContext, maskedContext) {
11901 if (disableLegacyContext) {
11902 return;
11903 } else {
11904 var instance = workInProgress.stateNode;
11905 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
11906 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
11907 }
11908}
11909
11910function getMaskedContext(workInProgress, unmaskedContext) {
11911 if (disableLegacyContext) {
11912 return emptyContextObject;
11913 } else {
11914 var type = workInProgress.type;
11915 var contextTypes = type.contextTypes;
11916
11917 if (!contextTypes) {
11918 return emptyContextObject;
11919 } // Avoid recreating masked context unless unmasked context has changed.
11920 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
11921 // This may trigger infinite loops if componentWillReceiveProps calls setState.
11922
11923
11924 var instance = workInProgress.stateNode;
11925
11926 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
11927 return instance.__reactInternalMemoizedMaskedChildContext;
11928 }
11929
11930 var context = {};
11931
11932 for (var key in contextTypes) {
11933 context[key] = unmaskedContext[key];
11934 }
11935
11936 {
11937 var name = getComponentName(type) || 'Unknown';
11938 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
11939 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
11940 // Context is created before the class component is instantiated so check for instance.
11941
11942
11943 if (instance) {
11944 cacheContext(workInProgress, unmaskedContext, context);
11945 }
11946
11947 return context;
11948 }
11949}
11950
11951function hasContextChanged() {
11952 if (disableLegacyContext) {
11953 return false;
11954 } else {
11955 return didPerformWorkStackCursor.current;
11956 }
11957}
11958
11959function isContextProvider(type) {
11960 if (disableLegacyContext) {
11961 return false;
11962 } else {
11963 var childContextTypes = type.childContextTypes;
11964 return childContextTypes !== null && childContextTypes !== undefined;
11965 }
11966}
11967
11968function popContext(fiber) {
11969 if (disableLegacyContext) {
11970 return;
11971 } else {
11972 pop(didPerformWorkStackCursor, fiber);
11973 pop(contextStackCursor, fiber);
11974 }
11975}
11976
11977function popTopLevelContextObject(fiber) {
11978 if (disableLegacyContext) {
11979 return;
11980 } else {
11981 pop(didPerformWorkStackCursor, fiber);
11982 pop(contextStackCursor, fiber);
11983 }
11984}
11985
11986function pushTopLevelContextObject(fiber, context, didChange) {
11987 if (disableLegacyContext) {
11988 return;
11989 } else {
11990 if (!(contextStackCursor.current === emptyContextObject)) {
11991 {
11992 throw Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
11993 }
11994 }
11995
11996 push(contextStackCursor, context, fiber);
11997 push(didPerformWorkStackCursor, didChange, fiber);
11998 }
11999}
12000
12001function processChildContext(fiber, type, parentContext) {
12002 if (disableLegacyContext) {
12003 return parentContext;
12004 } else {
12005 var instance = fiber.stateNode;
12006 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
12007 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
12008
12009 if (typeof instance.getChildContext !== 'function') {
12010 {
12011 var componentName = getComponentName(type) || 'Unknown';
12012
12013 if (!warnedAboutMissingGetChildContext[componentName]) {
12014 warnedAboutMissingGetChildContext[componentName] = true;
12015 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);
12016 }
12017 }
12018
12019 return parentContext;
12020 }
12021
12022 var childContext;
12023
12024 {
12025 setCurrentPhase('getChildContext');
12026 }
12027
12028 startPhaseTimer(fiber, 'getChildContext');
12029 childContext = instance.getChildContext();
12030 stopPhaseTimer();
12031
12032 {
12033 setCurrentPhase(null);
12034 }
12035
12036 for (var contextKey in childContext) {
12037 if (!(contextKey in childContextTypes)) {
12038 {
12039 throw Error((getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
12040 }
12041 }
12042 }
12043
12044 {
12045 var name = getComponentName(type) || 'Unknown';
12046 checkPropTypes_1(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
12047 // somebody calls unstable_renderSubtreeIntoContainer() and we process
12048 // context from the parent component instance. The stack will be missing
12049 // because it's outside of the reconciliation, and so the pointer has not
12050 // been set. This is rare and doesn't matter. We'll also remove that API.
12051 getCurrentFiberStackInDev);
12052 }
12053
12054 return _assign({}, parentContext, {}, childContext);
12055 }
12056}
12057
12058function pushContextProvider(workInProgress) {
12059 if (disableLegacyContext) {
12060 return false;
12061 } else {
12062 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
12063 // If the instance does not exist yet, we will push null at first,
12064 // and replace it on the stack later when invalidating the context.
12065
12066 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
12067 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
12068
12069 previousContext = contextStackCursor.current;
12070 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
12071 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
12072 return true;
12073 }
12074}
12075
12076function invalidateContextProvider(workInProgress, type, didChange) {
12077 if (disableLegacyContext) {
12078 return;
12079 } else {
12080 var instance = workInProgress.stateNode;
12081
12082 if (!instance) {
12083 {
12084 throw Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
12085 }
12086 }
12087
12088 if (didChange) {
12089 // Merge parent and own context.
12090 // Skip this if we're not updating due to sCU.
12091 // This avoids unnecessarily recomputing memoized values.
12092 var mergedContext = processChildContext(workInProgress, type, previousContext);
12093 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
12094 // It is important to unwind the context in the reverse order.
12095
12096 pop(didPerformWorkStackCursor, workInProgress);
12097 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
12098
12099 push(contextStackCursor, mergedContext, workInProgress);
12100 push(didPerformWorkStackCursor, didChange, workInProgress);
12101 } else {
12102 pop(didPerformWorkStackCursor, workInProgress);
12103 push(didPerformWorkStackCursor, didChange, workInProgress);
12104 }
12105 }
12106}
12107
12108function findCurrentUnmaskedContext(fiber) {
12109 if (disableLegacyContext) {
12110 return emptyContextObject;
12111 } else {
12112 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
12113 // makes sense elsewhere
12114 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
12115 {
12116 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.");
12117 }
12118 }
12119
12120 var node = fiber;
12121
12122 do {
12123 switch (node.tag) {
12124 case HostRoot:
12125 return node.stateNode.context;
12126
12127 case ClassComponent:
12128 {
12129 var Component = node.type;
12130
12131 if (isContextProvider(Component)) {
12132 return node.stateNode.__reactInternalMemoizedMergedChildContext;
12133 }
12134
12135 break;
12136 }
12137 }
12138
12139 node = node.return;
12140 } while (node !== null);
12141
12142 {
12143 {
12144 throw Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
12145 }
12146 }
12147 }
12148}
12149
12150var LegacyRoot = 0;
12151var BatchedRoot = 1;
12152var ConcurrentRoot = 2;
12153
12154var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
12155var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
12156var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
12157var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
12158var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
12159var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
12160var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
12161var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
12162var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
12163var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
12164var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
12165
12166// Intentionally not named imports because Rollup would use dynamic dispatch for
12167// CommonJS interop named imports.
12168var Scheduler_runWithPriority = unstable_runWithPriority;
12169var Scheduler_scheduleCallback = unstable_scheduleCallback;
12170var Scheduler_cancelCallback = unstable_cancelCallback;
12171var Scheduler_shouldYield = unstable_shouldYield;
12172var Scheduler_requestPaint = unstable_requestPaint;
12173var Scheduler_now = unstable_now;
12174var Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
12175var Scheduler_ImmediatePriority = unstable_ImmediatePriority;
12176var Scheduler_UserBlockingPriority = unstable_UserBlockingPriority;
12177var Scheduler_NormalPriority = unstable_NormalPriority;
12178var Scheduler_LowPriority = unstable_LowPriority;
12179var Scheduler_IdlePriority = unstable_IdlePriority;
12180
12181if (enableSchedulerTracing) {
12182 // Provide explicit error message when production+profiling bundle of e.g.
12183 // react-dom is used with production (non-profiling) bundle of
12184 // scheduler/tracing
12185 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
12186 {
12187 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");
12188 }
12189 }
12190}
12191
12192var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
12193// ascending numbers so we can compare them like numbers. They start at 90 to
12194// avoid clashing with Scheduler's priorities.
12195
12196var ImmediatePriority = 99;
12197var UserBlockingPriority$2 = 98;
12198var NormalPriority = 97;
12199var LowPriority = 96;
12200var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
12201
12202var NoPriority = 90;
12203var shouldYield = Scheduler_shouldYield;
12204var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
12205Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
12206var syncQueue = null;
12207var immediateQueueCallbackNode = null;
12208var isFlushingSyncQueue = false;
12209var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
12210// This will be the case for modern browsers that support `performance.now`. In
12211// older browsers, Scheduler falls back to `Date.now`, which returns a Unix
12212// timestamp. In that case, subtract the module initialization time to simulate
12213// the behavior of performance.now and keep our times small enough to fit
12214// within 32 bits.
12215// TODO: Consider lifting this into Scheduler.
12216
12217var now = initialTimeMs < 10000 ? Scheduler_now : function () {
12218 return Scheduler_now() - initialTimeMs;
12219};
12220function getCurrentPriorityLevel() {
12221 switch (Scheduler_getCurrentPriorityLevel()) {
12222 case Scheduler_ImmediatePriority:
12223 return ImmediatePriority;
12224
12225 case Scheduler_UserBlockingPriority:
12226 return UserBlockingPriority$2;
12227
12228 case Scheduler_NormalPriority:
12229 return NormalPriority;
12230
12231 case Scheduler_LowPriority:
12232 return LowPriority;
12233
12234 case Scheduler_IdlePriority:
12235 return IdlePriority;
12236
12237 default:
12238 {
12239 {
12240 throw Error("Unknown priority level.");
12241 }
12242 }
12243
12244 }
12245}
12246
12247function reactPriorityToSchedulerPriority(reactPriorityLevel) {
12248 switch (reactPriorityLevel) {
12249 case ImmediatePriority:
12250 return Scheduler_ImmediatePriority;
12251
12252 case UserBlockingPriority$2:
12253 return Scheduler_UserBlockingPriority;
12254
12255 case NormalPriority:
12256 return Scheduler_NormalPriority;
12257
12258 case LowPriority:
12259 return Scheduler_LowPriority;
12260
12261 case IdlePriority:
12262 return Scheduler_IdlePriority;
12263
12264 default:
12265 {
12266 {
12267 throw Error("Unknown priority level.");
12268 }
12269 }
12270
12271 }
12272}
12273
12274function runWithPriority$2(reactPriorityLevel, fn) {
12275 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12276 return Scheduler_runWithPriority(priorityLevel, fn);
12277}
12278function scheduleCallback(reactPriorityLevel, callback, options) {
12279 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
12280 return Scheduler_scheduleCallback(priorityLevel, callback, options);
12281}
12282function scheduleSyncCallback(callback) {
12283 // Push this callback into an internal queue. We'll flush these either in
12284 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
12285 if (syncQueue === null) {
12286 syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
12287
12288 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
12289 } else {
12290 // Push onto existing queue. Don't need to schedule a callback because
12291 // we already scheduled one when we created the queue.
12292 syncQueue.push(callback);
12293 }
12294
12295 return fakeCallbackNode;
12296}
12297function cancelCallback(callbackNode) {
12298 if (callbackNode !== fakeCallbackNode) {
12299 Scheduler_cancelCallback(callbackNode);
12300 }
12301}
12302function flushSyncCallbackQueue() {
12303 if (immediateQueueCallbackNode !== null) {
12304 var node = immediateQueueCallbackNode;
12305 immediateQueueCallbackNode = null;
12306 Scheduler_cancelCallback(node);
12307 }
12308
12309 flushSyncCallbackQueueImpl();
12310}
12311
12312function flushSyncCallbackQueueImpl() {
12313 if (!isFlushingSyncQueue && syncQueue !== null) {
12314 // Prevent re-entrancy.
12315 isFlushingSyncQueue = true;
12316 var i = 0;
12317
12318 try {
12319 var _isSync = true;
12320 var queue = syncQueue;
12321 runWithPriority$2(ImmediatePriority, function () {
12322 for (; i < queue.length; i++) {
12323 var callback = queue[i];
12324
12325 do {
12326 callback = callback(_isSync);
12327 } while (callback !== null);
12328 }
12329 });
12330 syncQueue = null;
12331 } catch (error) {
12332 // If something throws, leave the remaining callbacks on the queue.
12333 if (syncQueue !== null) {
12334 syncQueue = syncQueue.slice(i + 1);
12335 } // Resume flushing in the next tick
12336
12337
12338 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
12339 throw error;
12340 } finally {
12341 isFlushingSyncQueue = false;
12342 }
12343 }
12344}
12345
12346var NoMode = 0;
12347var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root
12348// tag instead
12349
12350var BatchedMode = 2;
12351var ConcurrentMode = 4;
12352var ProfileMode = 8;
12353
12354// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
12355// Math.pow(2, 30) - 1
12356// 0b111111111111111111111111111111
12357var MAX_SIGNED_31_BIT_INT = 1073741823;
12358
12359var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
12360// Never work can be committed in an inconsistent state without tearing the UI.
12361// The main example is offscreen content, like a hidden subtree. So one possible
12362// name is Offscreen. However, it also includes dehydrated Suspense boundaries,
12363// which are inconsistent in the sense that they haven't finished yet, but
12364// aren't visibly inconsistent because the server rendered HTML matches what the
12365// hydrated tree would look like.
12366
12367var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
12368// order to be consistent.
12369
12370var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle
12371// and is used to increase priority of hover targets. It is increasing with
12372// each usage so that last always wins.
12373
12374var ContinuousHydration = 3;
12375var Sync = MAX_SIGNED_31_BIT_INT;
12376var Batched = Sync - 1;
12377var UNIT_SIZE = 10;
12378var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.
12379
12380function msToExpirationTime(ms) {
12381 // Always add an offset so that we don't clash with the magic number for NoWork.
12382 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
12383}
12384function expirationTimeToMs(expirationTime) {
12385 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
12386}
12387
12388function ceiling(num, precision) {
12389 return ((num / precision | 0) + 1) * precision;
12390}
12391
12392function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
12393 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
12394} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
12395// the names to reflect.
12396
12397
12398var LOW_PRIORITY_EXPIRATION = 5000;
12399var LOW_PRIORITY_BATCH_SIZE = 250;
12400function computeAsyncExpiration(currentTime) {
12401 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
12402}
12403function computeSuspenseExpiration(currentTime, timeoutMs) {
12404 // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
12405 return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
12406} // We intentionally set a higher expiration time for interactive updates in
12407// dev than in production.
12408//
12409// If the main thread is being blocked so long that you hit the expiration,
12410// it's a problem that could be solved with better scheduling.
12411//
12412// People will be more likely to notice this and fix it with the long
12413// expiration time in development.
12414//
12415// In production we opt for better UX at the risk of masking scheduling
12416// problems, by expiring fast.
12417
12418var HIGH_PRIORITY_EXPIRATION = 500;
12419var HIGH_PRIORITY_BATCH_SIZE = 100;
12420function computeInteractiveExpiration(currentTime) {
12421 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
12422}
12423function computeContinuousHydrationExpiration(currentTime) {
12424 // Each time we ask for a new one of these we increase the priority.
12425 // This ensures that the last one always wins since we can't deprioritize
12426 // once we've scheduled work already.
12427 return ContinuousHydration++;
12428}
12429function inferPriorityFromExpirationTime(currentTime, expirationTime) {
12430 if (expirationTime === Sync) {
12431 return ImmediatePriority;
12432 }
12433
12434 if (expirationTime === Never || expirationTime === Idle) {
12435 return IdlePriority;
12436 }
12437
12438 var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);
12439
12440 if (msUntil <= 0) {
12441 return ImmediatePriority;
12442 }
12443
12444 if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
12445 return UserBlockingPriority$2;
12446 }
12447
12448 if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
12449 return NormalPriority;
12450 } // TODO: Handle LowPriority
12451 // Assume anything lower has idle priority
12452
12453
12454 return IdlePriority;
12455}
12456
12457/**
12458 * Forked from fbjs/warning:
12459 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
12460 *
12461 * Only change is we use console.warn instead of console.error,
12462 * and do nothing when 'console' is not supported.
12463 * This really simplifies the code.
12464 * ---
12465 * Similar to invariant but only logs a warning if the condition is not met.
12466 * This can be used to log issues in development environments in critical
12467 * paths. Removing the logging code for production environments will keep the
12468 * same logic and follow the same code paths.
12469 */
12470var lowPriorityWarningWithoutStack = function () {};
12471
12472{
12473 var printWarning$1 = function (format) {
12474 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
12475 args[_key - 1] = arguments[_key];
12476 }
12477
12478 var argIndex = 0;
12479 var message = 'Warning: ' + format.replace(/%s/g, function () {
12480 return args[argIndex++];
12481 });
12482
12483 if (typeof console !== 'undefined') {
12484 console.warn(message);
12485 }
12486
12487 try {
12488 // --- Welcome to debugging React ---
12489 // This error was thrown as a convenience so that you can use this stack
12490 // to find the callsite that caused this warning to fire.
12491 throw new Error(message);
12492 } catch (x) {}
12493 };
12494
12495 lowPriorityWarningWithoutStack = function (condition, format) {
12496 if (format === undefined) {
12497 throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
12498 }
12499
12500 if (!condition) {
12501 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
12502 args[_key2 - 2] = arguments[_key2];
12503 }
12504
12505 printWarning$1.apply(void 0, [format].concat(args));
12506 }
12507 };
12508}
12509
12510var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
12511
12512var ReactStrictModeWarnings = {
12513 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
12514 flushPendingUnsafeLifecycleWarnings: function () {},
12515 recordLegacyContextWarning: function (fiber, instance) {},
12516 flushLegacyContextWarning: function () {},
12517 discardPendingWarnings: function () {}
12518};
12519
12520{
12521 var findStrictRoot = function (fiber) {
12522 var maybeStrictRoot = null;
12523 var node = fiber;
12524
12525 while (node !== null) {
12526 if (node.mode & StrictMode) {
12527 maybeStrictRoot = node;
12528 }
12529
12530 node = node.return;
12531 }
12532
12533 return maybeStrictRoot;
12534 };
12535
12536 var setToSortedString = function (set) {
12537 var array = [];
12538 set.forEach(function (value) {
12539 array.push(value);
12540 });
12541 return array.sort().join(', ');
12542 };
12543
12544 var pendingComponentWillMountWarnings = [];
12545 var pendingUNSAFE_ComponentWillMountWarnings = [];
12546 var pendingComponentWillReceivePropsWarnings = [];
12547 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12548 var pendingComponentWillUpdateWarnings = [];
12549 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
12550
12551 var didWarnAboutUnsafeLifecycles = new Set();
12552
12553 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
12554 // Dedup strategy: Warn once per component.
12555 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
12556 return;
12557 }
12558
12559 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
12560 instance.componentWillMount.__suppressDeprecationWarning !== true) {
12561 pendingComponentWillMountWarnings.push(fiber);
12562 }
12563
12564 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
12565 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
12566 }
12567
12568 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12569 pendingComponentWillReceivePropsWarnings.push(fiber);
12570 }
12571
12572 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12573 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
12574 }
12575
12576 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12577 pendingComponentWillUpdateWarnings.push(fiber);
12578 }
12579
12580 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
12581 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
12582 }
12583 };
12584
12585 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
12586 // We do an initial pass to gather component names
12587 var componentWillMountUniqueNames = new Set();
12588
12589 if (pendingComponentWillMountWarnings.length > 0) {
12590 pendingComponentWillMountWarnings.forEach(function (fiber) {
12591 componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12592 didWarnAboutUnsafeLifecycles.add(fiber.type);
12593 });
12594 pendingComponentWillMountWarnings = [];
12595 }
12596
12597 var UNSAFE_componentWillMountUniqueNames = new Set();
12598
12599 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
12600 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
12601 UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
12602 didWarnAboutUnsafeLifecycles.add(fiber.type);
12603 });
12604 pendingUNSAFE_ComponentWillMountWarnings = [];
12605 }
12606
12607 var componentWillReceivePropsUniqueNames = new Set();
12608
12609 if (pendingComponentWillReceivePropsWarnings.length > 0) {
12610 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
12611 componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12612 didWarnAboutUnsafeLifecycles.add(fiber.type);
12613 });
12614 pendingComponentWillReceivePropsWarnings = [];
12615 }
12616
12617 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
12618
12619 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
12620 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
12621 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
12622 didWarnAboutUnsafeLifecycles.add(fiber.type);
12623 });
12624 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12625 }
12626
12627 var componentWillUpdateUniqueNames = new Set();
12628
12629 if (pendingComponentWillUpdateWarnings.length > 0) {
12630 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
12631 componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12632 didWarnAboutUnsafeLifecycles.add(fiber.type);
12633 });
12634 pendingComponentWillUpdateWarnings = [];
12635 }
12636
12637 var UNSAFE_componentWillUpdateUniqueNames = new Set();
12638
12639 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
12640 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
12641 UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
12642 didWarnAboutUnsafeLifecycles.add(fiber.type);
12643 });
12644 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12645 } // Finally, we flush all the warnings
12646 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
12647
12648
12649 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
12650 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
12651 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);
12652 }
12653
12654 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
12655 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
12656
12657 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);
12658 }
12659
12660 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
12661 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
12662
12663 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);
12664 }
12665
12666 if (componentWillMountUniqueNames.size > 0) {
12667 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
12668
12669 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);
12670 }
12671
12672 if (componentWillReceivePropsUniqueNames.size > 0) {
12673 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
12674
12675 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);
12676 }
12677
12678 if (componentWillUpdateUniqueNames.size > 0) {
12679 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
12680
12681 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);
12682 }
12683 };
12684
12685 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
12686
12687 var didWarnAboutLegacyContext = new Set();
12688
12689 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
12690 var strictRoot = findStrictRoot(fiber);
12691
12692 if (strictRoot === null) {
12693 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.');
12694 return;
12695 } // Dedup strategy: Warn once per component.
12696
12697
12698 if (didWarnAboutLegacyContext.has(fiber.type)) {
12699 return;
12700 }
12701
12702 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
12703
12704 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
12705 if (warningsForRoot === undefined) {
12706 warningsForRoot = [];
12707 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
12708 }
12709
12710 warningsForRoot.push(fiber);
12711 }
12712 };
12713
12714 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
12715 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
12716 var uniqueNames = new Set();
12717 fiberArray.forEach(function (fiber) {
12718 uniqueNames.add(getComponentName(fiber.type) || 'Component');
12719 didWarnAboutLegacyContext.add(fiber.type);
12720 });
12721 var sortedNames = setToSortedString(uniqueNames);
12722 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
12723 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);
12724 });
12725 };
12726
12727 ReactStrictModeWarnings.discardPendingWarnings = function () {
12728 pendingComponentWillMountWarnings = [];
12729 pendingUNSAFE_ComponentWillMountWarnings = [];
12730 pendingComponentWillReceivePropsWarnings = [];
12731 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12732 pendingComponentWillUpdateWarnings = [];
12733 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12734 pendingLegacyContextWarning = new Map();
12735 };
12736}
12737
12738var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
12739
12740var failedBoundaries = null;
12741var setRefreshHandler = function (handler) {
12742 {
12743 resolveFamily = handler;
12744 }
12745};
12746function resolveFunctionForHotReloading(type) {
12747 {
12748 if (resolveFamily === null) {
12749 // Hot reloading is disabled.
12750 return type;
12751 }
12752
12753 var family = resolveFamily(type);
12754
12755 if (family === undefined) {
12756 return type;
12757 } // Use the latest known implementation.
12758
12759
12760 return family.current;
12761 }
12762}
12763function resolveClassForHotReloading(type) {
12764 // No implementation differences.
12765 return resolveFunctionForHotReloading(type);
12766}
12767function resolveForwardRefForHotReloading(type) {
12768 {
12769 if (resolveFamily === null) {
12770 // Hot reloading is disabled.
12771 return type;
12772 }
12773
12774 var family = resolveFamily(type);
12775
12776 if (family === undefined) {
12777 // Check if we're dealing with a real forwardRef. Don't want to crash early.
12778 if (type !== null && type !== undefined && typeof type.render === 'function') {
12779 // ForwardRef is special because its resolved .type is an object,
12780 // but it's possible that we only have its inner render function in the map.
12781 // If that inner render function is different, we'll build a new forwardRef type.
12782 var currentRender = resolveFunctionForHotReloading(type.render);
12783
12784 if (type.render !== currentRender) {
12785 var syntheticType = {
12786 $$typeof: REACT_FORWARD_REF_TYPE,
12787 render: currentRender
12788 };
12789
12790 if (type.displayName !== undefined) {
12791 syntheticType.displayName = type.displayName;
12792 }
12793
12794 return syntheticType;
12795 }
12796 }
12797
12798 return type;
12799 } // Use the latest known implementation.
12800
12801
12802 return family.current;
12803 }
12804}
12805function isCompatibleFamilyForHotReloading(fiber, element) {
12806 {
12807 if (resolveFamily === null) {
12808 // Hot reloading is disabled.
12809 return false;
12810 }
12811
12812 var prevType = fiber.elementType;
12813 var nextType = element.type; // If we got here, we know types aren't === equal.
12814
12815 var needsCompareFamilies = false;
12816 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
12817
12818 switch (fiber.tag) {
12819 case ClassComponent:
12820 {
12821 if (typeof nextType === 'function') {
12822 needsCompareFamilies = true;
12823 }
12824
12825 break;
12826 }
12827
12828 case FunctionComponent:
12829 {
12830 if (typeof nextType === 'function') {
12831 needsCompareFamilies = true;
12832 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12833 // We don't know the inner type yet.
12834 // We're going to assume that the lazy inner type is stable,
12835 // and so it is sufficient to avoid reconciling it away.
12836 // We're not going to unwrap or actually use the new lazy type.
12837 needsCompareFamilies = true;
12838 }
12839
12840 break;
12841 }
12842
12843 case ForwardRef:
12844 {
12845 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
12846 needsCompareFamilies = true;
12847 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12848 needsCompareFamilies = true;
12849 }
12850
12851 break;
12852 }
12853
12854 case MemoComponent:
12855 case SimpleMemoComponent:
12856 {
12857 if ($$typeofNextType === REACT_MEMO_TYPE) {
12858 // TODO: if it was but can no longer be simple,
12859 // we shouldn't set this.
12860 needsCompareFamilies = true;
12861 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
12862 needsCompareFamilies = true;
12863 }
12864
12865 break;
12866 }
12867
12868 default:
12869 return false;
12870 } // Check if both types have a family and it's the same one.
12871
12872
12873 if (needsCompareFamilies) {
12874 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
12875 // This means both of them need to be registered to preserve state.
12876 // If we unwrapped and compared the inner types for wrappers instead,
12877 // then we would risk falsely saying two separate memo(Foo)
12878 // calls are equivalent because they wrap the same Foo function.
12879 var prevFamily = resolveFamily(prevType);
12880
12881 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
12882 return true;
12883 }
12884 }
12885
12886 return false;
12887 }
12888}
12889function markFailedErrorBoundaryForHotReloading(fiber) {
12890 {
12891 if (resolveFamily === null) {
12892 // Hot reloading is disabled.
12893 return;
12894 }
12895
12896 if (typeof WeakSet !== 'function') {
12897 return;
12898 }
12899
12900 if (failedBoundaries === null) {
12901 failedBoundaries = new WeakSet();
12902 }
12903
12904 failedBoundaries.add(fiber);
12905 }
12906}
12907var scheduleRefresh = function (root, update) {
12908 {
12909 if (resolveFamily === null) {
12910 // Hot reloading is disabled.
12911 return;
12912 }
12913
12914 var staleFamilies = update.staleFamilies,
12915 updatedFamilies = update.updatedFamilies;
12916 flushPassiveEffects();
12917 flushSync(function () {
12918 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
12919 });
12920 }
12921};
12922var scheduleRoot = function (root, element) {
12923 {
12924 if (root.context !== emptyContextObject) {
12925 // Super edge case: root has a legacy _renderSubtree context
12926 // but we don't know the parentComponent so we can't pass it.
12927 // Just ignore. We'll delete this with _renderSubtree code path later.
12928 return;
12929 }
12930
12931 flushPassiveEffects();
12932 syncUpdates(function () {
12933 updateContainer(element, root, null, null);
12934 });
12935 }
12936};
12937
12938function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
12939 {
12940 var alternate = fiber.alternate,
12941 child = fiber.child,
12942 sibling = fiber.sibling,
12943 tag = fiber.tag,
12944 type = fiber.type;
12945 var candidateType = null;
12946
12947 switch (tag) {
12948 case FunctionComponent:
12949 case SimpleMemoComponent:
12950 case ClassComponent:
12951 candidateType = type;
12952 break;
12953
12954 case ForwardRef:
12955 candidateType = type.render;
12956 break;
12957
12958 default:
12959 break;
12960 }
12961
12962 if (resolveFamily === null) {
12963 throw new Error('Expected resolveFamily to be set during hot reload.');
12964 }
12965
12966 var needsRender = false;
12967 var needsRemount = false;
12968
12969 if (candidateType !== null) {
12970 var family = resolveFamily(candidateType);
12971
12972 if (family !== undefined) {
12973 if (staleFamilies.has(family)) {
12974 needsRemount = true;
12975 } else if (updatedFamilies.has(family)) {
12976 if (tag === ClassComponent) {
12977 needsRemount = true;
12978 } else {
12979 needsRender = true;
12980 }
12981 }
12982 }
12983 }
12984
12985 if (failedBoundaries !== null) {
12986 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
12987 needsRemount = true;
12988 }
12989 }
12990
12991 if (needsRemount) {
12992 fiber._debugNeedsRemount = true;
12993 }
12994
12995 if (needsRemount || needsRender) {
12996 scheduleWork(fiber, Sync);
12997 }
12998
12999 if (child !== null && !needsRemount) {
13000 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
13001 }
13002
13003 if (sibling !== null) {
13004 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
13005 }
13006 }
13007}
13008
13009var findHostInstancesForRefresh = function (root, families) {
13010 {
13011 var hostInstances = new Set();
13012 var types = new Set(families.map(function (family) {
13013 return family.current;
13014 }));
13015 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
13016 return hostInstances;
13017 }
13018};
13019
13020function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
13021 {
13022 var child = fiber.child,
13023 sibling = fiber.sibling,
13024 tag = fiber.tag,
13025 type = fiber.type;
13026 var candidateType = null;
13027
13028 switch (tag) {
13029 case FunctionComponent:
13030 case SimpleMemoComponent:
13031 case ClassComponent:
13032 candidateType = type;
13033 break;
13034
13035 case ForwardRef:
13036 candidateType = type.render;
13037 break;
13038
13039 default:
13040 break;
13041 }
13042
13043 var didMatch = false;
13044
13045 if (candidateType !== null) {
13046 if (types.has(candidateType)) {
13047 didMatch = true;
13048 }
13049 }
13050
13051 if (didMatch) {
13052 // We have a match. This only drills down to the closest host components.
13053 // There's no need to search deeper because for the purpose of giving
13054 // visual feedback, "flashing" outermost parent rectangles is sufficient.
13055 findHostInstancesForFiberShallowly(fiber, hostInstances);
13056 } else {
13057 // If there's no match, maybe there will be one further down in the child tree.
13058 if (child !== null) {
13059 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
13060 }
13061 }
13062
13063 if (sibling !== null) {
13064 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
13065 }
13066 }
13067}
13068
13069function findHostInstancesForFiberShallowly(fiber, hostInstances) {
13070 {
13071 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
13072
13073 if (foundHostInstances) {
13074 return;
13075 } // If we didn't find any host children, fallback to closest host parent.
13076
13077
13078 var node = fiber;
13079
13080 while (true) {
13081 switch (node.tag) {
13082 case HostComponent:
13083 hostInstances.add(node.stateNode);
13084 return;
13085
13086 case HostPortal:
13087 hostInstances.add(node.stateNode.containerInfo);
13088 return;
13089
13090 case HostRoot:
13091 hostInstances.add(node.stateNode.containerInfo);
13092 return;
13093 }
13094
13095 if (node.return === null) {
13096 throw new Error('Expected to reach root first.');
13097 }
13098
13099 node = node.return;
13100 }
13101 }
13102}
13103
13104function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
13105 {
13106 var node = fiber;
13107 var foundHostInstances = false;
13108
13109 while (true) {
13110 if (node.tag === HostComponent) {
13111 // We got a match.
13112 foundHostInstances = true;
13113 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
13114 } else if (node.child !== null) {
13115 node.child.return = node;
13116 node = node.child;
13117 continue;
13118 }
13119
13120 if (node === fiber) {
13121 return foundHostInstances;
13122 }
13123
13124 while (node.sibling === null) {
13125 if (node.return === null || node.return === fiber) {
13126 return foundHostInstances;
13127 }
13128
13129 node = node.return;
13130 }
13131
13132 node.sibling.return = node.return;
13133 node = node.sibling;
13134 }
13135 }
13136
13137 return false;
13138}
13139
13140function resolveDefaultProps(Component, baseProps) {
13141 if (Component && Component.defaultProps) {
13142 // Resolve default props. Taken from ReactElement
13143 var props = _assign({}, baseProps);
13144
13145 var defaultProps = Component.defaultProps;
13146
13147 for (var propName in defaultProps) {
13148 if (props[propName] === undefined) {
13149 props[propName] = defaultProps[propName];
13150 }
13151 }
13152
13153 return props;
13154 }
13155
13156 return baseProps;
13157}
13158function readLazyComponentType(lazyComponent) {
13159 initializeLazyComponentType(lazyComponent);
13160
13161 if (lazyComponent._status !== Resolved) {
13162 throw lazyComponent._result;
13163 }
13164
13165 return lazyComponent._result;
13166}
13167
13168var valueCursor = createCursor(null);
13169var rendererSigil;
13170
13171{
13172 // Use this to detect multiple renderers using the same context
13173 rendererSigil = {};
13174}
13175
13176var currentlyRenderingFiber = null;
13177var lastContextDependency = null;
13178var lastContextWithAllBitsObserved = null;
13179var isDisallowedContextReadInDEV = false;
13180function resetContextDependencies() {
13181 // This is called right before React yields execution, to ensure `readContext`
13182 // cannot be called outside the render phase.
13183 currentlyRenderingFiber = null;
13184 lastContextDependency = null;
13185 lastContextWithAllBitsObserved = null;
13186
13187 {
13188 isDisallowedContextReadInDEV = false;
13189 }
13190}
13191function enterDisallowedContextReadInDEV() {
13192 {
13193 isDisallowedContextReadInDEV = true;
13194 }
13195}
13196function exitDisallowedContextReadInDEV() {
13197 {
13198 isDisallowedContextReadInDEV = false;
13199 }
13200}
13201function pushProvider(providerFiber, nextValue) {
13202 var context = providerFiber.type._context;
13203
13204 if (isPrimaryRenderer) {
13205 push(valueCursor, context._currentValue, providerFiber);
13206 context._currentValue = nextValue;
13207
13208 {
13209 !(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;
13210 context._currentRenderer = rendererSigil;
13211 }
13212 } else {
13213 push(valueCursor, context._currentValue2, providerFiber);
13214 context._currentValue2 = nextValue;
13215
13216 {
13217 !(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;
13218 context._currentRenderer2 = rendererSigil;
13219 }
13220 }
13221}
13222function popProvider(providerFiber) {
13223 var currentValue = valueCursor.current;
13224 pop(valueCursor, providerFiber);
13225 var context = providerFiber.type._context;
13226
13227 if (isPrimaryRenderer) {
13228 context._currentValue = currentValue;
13229 } else {
13230 context._currentValue2 = currentValue;
13231 }
13232}
13233function calculateChangedBits(context, newValue, oldValue) {
13234 if (is$1(oldValue, newValue)) {
13235 // No change
13236 return 0;
13237 } else {
13238 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
13239
13240 {
13241 !((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;
13242 }
13243
13244 return changedBits | 0;
13245 }
13246}
13247function scheduleWorkOnParentPath(parent, renderExpirationTime) {
13248 // Update the child expiration time of all the ancestors, including
13249 // the alternates.
13250 var node = parent;
13251
13252 while (node !== null) {
13253 var alternate = node.alternate;
13254
13255 if (node.childExpirationTime < renderExpirationTime) {
13256 node.childExpirationTime = renderExpirationTime;
13257
13258 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13259 alternate.childExpirationTime = renderExpirationTime;
13260 }
13261 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
13262 alternate.childExpirationTime = renderExpirationTime;
13263 } else {
13264 // Neither alternate was updated, which means the rest of the
13265 // ancestor path already has sufficient priority.
13266 break;
13267 }
13268
13269 node = node.return;
13270 }
13271}
13272function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
13273 var fiber = workInProgress.child;
13274
13275 if (fiber !== null) {
13276 // Set the return pointer of the child to the work-in-progress fiber.
13277 fiber.return = workInProgress;
13278 }
13279
13280 while (fiber !== null) {
13281 var nextFiber = void 0; // Visit this fiber.
13282
13283 var list = fiber.dependencies;
13284
13285 if (list !== null) {
13286 nextFiber = fiber.child;
13287 var dependency = list.firstContext;
13288
13289 while (dependency !== null) {
13290 // Check if the context matches.
13291 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
13292 // Match! Schedule an update on this fiber.
13293 if (fiber.tag === ClassComponent) {
13294 // Schedule a force update on the work-in-progress.
13295 var update = createUpdate(renderExpirationTime, null);
13296 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
13297 // update to the current fiber, too, which means it will persist even if
13298 // this render is thrown away. Since it's a race condition, not sure it's
13299 // worth fixing.
13300
13301 enqueueUpdate(fiber, update);
13302 }
13303
13304 if (fiber.expirationTime < renderExpirationTime) {
13305 fiber.expirationTime = renderExpirationTime;
13306 }
13307
13308 var alternate = fiber.alternate;
13309
13310 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
13311 alternate.expirationTime = renderExpirationTime;
13312 }
13313
13314 scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.
13315
13316 if (list.expirationTime < renderExpirationTime) {
13317 list.expirationTime = renderExpirationTime;
13318 } // Since we already found a match, we can stop traversing the
13319 // dependency list.
13320
13321
13322 break;
13323 }
13324
13325 dependency = dependency.next;
13326 }
13327 } else if (fiber.tag === ContextProvider) {
13328 // Don't scan deeper if this is a matching provider
13329 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
13330 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedFragment) {
13331 // If a dehydrated suspense bounudary is in this subtree, we don't know
13332 // if it will have any context consumers in it. The best we can do is
13333 // mark it as having updates.
13334 var parentSuspense = fiber.return;
13335
13336 if (!(parentSuspense !== null)) {
13337 {
13338 throw Error("We just came from a parent so we must have had a parent. This is a bug in React.");
13339 }
13340 }
13341
13342 if (parentSuspense.expirationTime < renderExpirationTime) {
13343 parentSuspense.expirationTime = renderExpirationTime;
13344 }
13345
13346 var _alternate = parentSuspense.alternate;
13347
13348 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
13349 _alternate.expirationTime = renderExpirationTime;
13350 } // This is intentionally passing this fiber as the parent
13351 // because we want to schedule this fiber as having work
13352 // on its children. We'll use the childExpirationTime on
13353 // this fiber to indicate that a context has changed.
13354
13355
13356 scheduleWorkOnParentPath(parentSuspense, renderExpirationTime);
13357 nextFiber = fiber.sibling;
13358 } else {
13359 // Traverse down.
13360 nextFiber = fiber.child;
13361 }
13362
13363 if (nextFiber !== null) {
13364 // Set the return pointer of the child to the work-in-progress fiber.
13365 nextFiber.return = fiber;
13366 } else {
13367 // No child. Traverse to next sibling.
13368 nextFiber = fiber;
13369
13370 while (nextFiber !== null) {
13371 if (nextFiber === workInProgress) {
13372 // We're back to the root of this subtree. Exit.
13373 nextFiber = null;
13374 break;
13375 }
13376
13377 var sibling = nextFiber.sibling;
13378
13379 if (sibling !== null) {
13380 // Set the return pointer of the sibling to the work-in-progress fiber.
13381 sibling.return = nextFiber.return;
13382 nextFiber = sibling;
13383 break;
13384 } // No more siblings. Traverse up.
13385
13386
13387 nextFiber = nextFiber.return;
13388 }
13389 }
13390
13391 fiber = nextFiber;
13392 }
13393}
13394function prepareToReadContext(workInProgress, renderExpirationTime) {
13395 currentlyRenderingFiber = workInProgress;
13396 lastContextDependency = null;
13397 lastContextWithAllBitsObserved = null;
13398 var dependencies = workInProgress.dependencies;
13399
13400 if (dependencies !== null) {
13401 var firstContext = dependencies.firstContext;
13402
13403 if (firstContext !== null) {
13404 if (dependencies.expirationTime >= renderExpirationTime) {
13405 // Context list has a pending update. Mark that this fiber performed work.
13406 markWorkInProgressReceivedUpdate();
13407 } // Reset the work-in-progress list
13408
13409
13410 dependencies.firstContext = null;
13411 }
13412 }
13413}
13414function readContext(context, observedBits) {
13415 {
13416 // This warning would fire if you read context inside a Hook like useMemo.
13417 // Unlike the class check below, it's not enforced in production for perf.
13418 !!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;
13419 }
13420
13421 if (lastContextWithAllBitsObserved === context) {// Nothing to do. We already observe everything in this context.
13422 } else if (observedBits === false || observedBits === 0) {// Do not observe any updates.
13423 } else {
13424 var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
13425
13426 if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
13427 // Observe all updates.
13428 lastContextWithAllBitsObserved = context;
13429 resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
13430 } else {
13431 resolvedObservedBits = observedBits;
13432 }
13433
13434 var contextItem = {
13435 context: context,
13436 observedBits: resolvedObservedBits,
13437 next: null
13438 };
13439
13440 if (lastContextDependency === null) {
13441 if (!(currentlyRenderingFiber !== null)) {
13442 {
13443 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().");
13444 }
13445 } // This is the first dependency for this component. Create a new list.
13446
13447
13448 lastContextDependency = contextItem;
13449 currentlyRenderingFiber.dependencies = {
13450 expirationTime: NoWork,
13451 firstContext: contextItem,
13452 responders: null
13453 };
13454 } else {
13455 // Append a new context item.
13456 lastContextDependency = lastContextDependency.next = contextItem;
13457 }
13458 }
13459
13460 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
13461}
13462
13463// UpdateQueue is a linked list of prioritized updates.
13464//
13465// Like fibers, update queues come in pairs: a current queue, which represents
13466// the visible state of the screen, and a work-in-progress queue, which can be
13467// mutated and processed asynchronously before it is committed — a form of
13468// double buffering. If a work-in-progress render is discarded before finishing,
13469// we create a new work-in-progress by cloning the current queue.
13470//
13471// Both queues share a persistent, singly-linked list structure. To schedule an
13472// update, we append it to the end of both queues. Each queue maintains a
13473// pointer to first update in the persistent list that hasn't been processed.
13474// The work-in-progress pointer always has a position equal to or greater than
13475// the current queue, since we always work on that one. The current queue's
13476// pointer is only updated during the commit phase, when we swap in the
13477// work-in-progress.
13478//
13479// For example:
13480//
13481// Current pointer: A - B - C - D - E - F
13482// Work-in-progress pointer: D - E - F
13483// ^
13484// The work-in-progress queue has
13485// processed more updates than current.
13486//
13487// The reason we append to both queues is because otherwise we might drop
13488// updates without ever processing them. For example, if we only add updates to
13489// the work-in-progress queue, some updates could be lost whenever a work-in
13490// -progress render restarts by cloning from current. Similarly, if we only add
13491// updates to the current queue, the updates will be lost whenever an already
13492// in-progress queue commits and swaps with the current queue. However, by
13493// adding to both queues, we guarantee that the update will be part of the next
13494// work-in-progress. (And because the work-in-progress queue becomes the
13495// current queue once it commits, there's no danger of applying the same
13496// update twice.)
13497//
13498// Prioritization
13499// --------------
13500//
13501// Updates are not sorted by priority, but by insertion; new updates are always
13502// appended to the end of the list.
13503//
13504// The priority is still important, though. When processing the update queue
13505// during the render phase, only the updates with sufficient priority are
13506// included in the result. If we skip an update because it has insufficient
13507// priority, it remains in the queue to be processed later, during a lower
13508// priority render. Crucially, all updates subsequent to a skipped update also
13509// remain in the queue *regardless of their priority*. That means high priority
13510// updates are sometimes processed twice, at two separate priorities. We also
13511// keep track of a base state, that represents the state before the first
13512// update in the queue is applied.
13513//
13514// For example:
13515//
13516// Given a base state of '', and the following queue of updates
13517//
13518// A1 - B2 - C1 - D2
13519//
13520// where the number indicates the priority, and the update is applied to the
13521// previous state by appending a letter, React will process these updates as
13522// two separate renders, one per distinct priority level:
13523//
13524// First render, at priority 1:
13525// Base state: ''
13526// Updates: [A1, C1]
13527// Result state: 'AC'
13528//
13529// Second render, at priority 2:
13530// Base state: 'A' <- The base state does not include C1,
13531// because B2 was skipped.
13532// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
13533// Result state: 'ABCD'
13534//
13535// Because we process updates in insertion order, and rebase high priority
13536// updates when preceding updates are skipped, the final result is deterministic
13537// regardless of priority. Intermediate state may vary according to system
13538// resources, but the final state is always the same.
13539var UpdateState = 0;
13540var ReplaceState = 1;
13541var ForceUpdate = 2;
13542var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
13543// It should only be read right after calling `processUpdateQueue`, via
13544// `checkHasForceUpdateAfterProcessing`.
13545
13546var hasForceUpdate = false;
13547var didWarnUpdateInsideUpdate;
13548var currentlyProcessingQueue;
13549
13550
13551{
13552 didWarnUpdateInsideUpdate = false;
13553 currentlyProcessingQueue = null;
13554
13555
13556}
13557
13558function createUpdateQueue(baseState) {
13559 var queue = {
13560 baseState: baseState,
13561 firstUpdate: null,
13562 lastUpdate: null,
13563 firstCapturedUpdate: null,
13564 lastCapturedUpdate: null,
13565 firstEffect: null,
13566 lastEffect: null,
13567 firstCapturedEffect: null,
13568 lastCapturedEffect: null
13569 };
13570 return queue;
13571}
13572
13573function cloneUpdateQueue(currentQueue) {
13574 var queue = {
13575 baseState: currentQueue.baseState,
13576 firstUpdate: currentQueue.firstUpdate,
13577 lastUpdate: currentQueue.lastUpdate,
13578 // TODO: With resuming, if we bail out and resuse the child tree, we should
13579 // keep these effects.
13580 firstCapturedUpdate: null,
13581 lastCapturedUpdate: null,
13582 firstEffect: null,
13583 lastEffect: null,
13584 firstCapturedEffect: null,
13585 lastCapturedEffect: null
13586 };
13587 return queue;
13588}
13589
13590function createUpdate(expirationTime, suspenseConfig) {
13591 var update = {
13592 expirationTime: expirationTime,
13593 suspenseConfig: suspenseConfig,
13594 tag: UpdateState,
13595 payload: null,
13596 callback: null,
13597 next: null,
13598 nextEffect: null
13599 };
13600
13601 {
13602 update.priority = getCurrentPriorityLevel();
13603 }
13604
13605 return update;
13606}
13607
13608function appendUpdateToQueue(queue, update) {
13609 // Append the update to the end of the list.
13610 if (queue.lastUpdate === null) {
13611 // Queue is empty
13612 queue.firstUpdate = queue.lastUpdate = update;
13613 } else {
13614 queue.lastUpdate.next = update;
13615 queue.lastUpdate = update;
13616 }
13617}
13618
13619function enqueueUpdate(fiber, update) {
13620 // Update queues are created lazily.
13621 var alternate = fiber.alternate;
13622 var queue1;
13623 var queue2;
13624
13625 if (alternate === null) {
13626 // There's only one fiber.
13627 queue1 = fiber.updateQueue;
13628 queue2 = null;
13629
13630 if (queue1 === null) {
13631 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13632 }
13633 } else {
13634 // There are two owners.
13635 queue1 = fiber.updateQueue;
13636 queue2 = alternate.updateQueue;
13637
13638 if (queue1 === null) {
13639 if (queue2 === null) {
13640 // Neither fiber has an update queue. Create new ones.
13641 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
13642 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
13643 } else {
13644 // Only one fiber has an update queue. Clone to create a new one.
13645 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
13646 }
13647 } else {
13648 if (queue2 === null) {
13649 // Only one fiber has an update queue. Clone to create a new one.
13650 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
13651 } else {// Both owners have an update queue.
13652 }
13653 }
13654 }
13655
13656 if (queue2 === null || queue1 === queue2) {
13657 // There's only a single queue.
13658 appendUpdateToQueue(queue1, update);
13659 } else {
13660 // There are two queues. We need to append the update to both queues,
13661 // while accounting for the persistent structure of the list — we don't
13662 // want the same update to be added multiple times.
13663 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
13664 // One of the queues is not empty. We must add the update to both queues.
13665 appendUpdateToQueue(queue1, update);
13666 appendUpdateToQueue(queue2, update);
13667 } else {
13668 // Both queues are non-empty. The last update is the same in both lists,
13669 // because of structural sharing. So, only append to one of the lists.
13670 appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2.
13671
13672 queue2.lastUpdate = update;
13673 }
13674 }
13675
13676 {
13677 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
13678 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.');
13679 didWarnUpdateInsideUpdate = true;
13680 }
13681 }
13682}
13683function enqueueCapturedUpdate(workInProgress, update) {
13684 // Captured updates go into a separate list, and only on the work-in-
13685 // progress queue.
13686 var workInProgressQueue = workInProgress.updateQueue;
13687
13688 if (workInProgressQueue === null) {
13689 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
13690 } else {
13691 // TODO: I put this here rather than createWorkInProgress so that we don't
13692 // clone the queue unnecessarily. There's probably a better way to
13693 // structure this.
13694 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
13695 } // Append the update to the end of the list.
13696
13697
13698 if (workInProgressQueue.lastCapturedUpdate === null) {
13699 // This is the first render phase update
13700 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
13701 } else {
13702 workInProgressQueue.lastCapturedUpdate.next = update;
13703 workInProgressQueue.lastCapturedUpdate = update;
13704 }
13705}
13706
13707function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
13708 var current = workInProgress.alternate;
13709
13710 if (current !== null) {
13711 // If the work-in-progress queue is equal to the current queue,
13712 // we need to clone it first.
13713 if (queue === current.updateQueue) {
13714 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
13715 }
13716 }
13717
13718 return queue;
13719}
13720
13721function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
13722 switch (update.tag) {
13723 case ReplaceState:
13724 {
13725 var payload = update.payload;
13726
13727 if (typeof payload === 'function') {
13728 // Updater function
13729 {
13730 enterDisallowedContextReadInDEV();
13731
13732 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13733 payload.call(instance, prevState, nextProps);
13734 }
13735 }
13736
13737 var nextState = payload.call(instance, prevState, nextProps);
13738
13739 {
13740 exitDisallowedContextReadInDEV();
13741 }
13742
13743 return nextState;
13744 } // State object
13745
13746
13747 return payload;
13748 }
13749
13750 case CaptureUpdate:
13751 {
13752 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
13753 }
13754 // Intentional fallthrough
13755
13756 case UpdateState:
13757 {
13758 var _payload = update.payload;
13759 var partialState;
13760
13761 if (typeof _payload === 'function') {
13762 // Updater function
13763 {
13764 enterDisallowedContextReadInDEV();
13765
13766 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
13767 _payload.call(instance, prevState, nextProps);
13768 }
13769 }
13770
13771 partialState = _payload.call(instance, prevState, nextProps);
13772
13773 {
13774 exitDisallowedContextReadInDEV();
13775 }
13776 } else {
13777 // Partial state object
13778 partialState = _payload;
13779 }
13780
13781 if (partialState === null || partialState === undefined) {
13782 // Null and undefined are treated as no-ops.
13783 return prevState;
13784 } // Merge the partial state and the previous state.
13785
13786
13787 return _assign({}, prevState, partialState);
13788 }
13789
13790 case ForceUpdate:
13791 {
13792 hasForceUpdate = true;
13793 return prevState;
13794 }
13795 }
13796
13797 return prevState;
13798}
13799
13800function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
13801 hasForceUpdate = false;
13802 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
13803
13804 {
13805 currentlyProcessingQueue = queue;
13806 } // These values may change as we process the queue.
13807
13808
13809 var newBaseState = queue.baseState;
13810 var newFirstUpdate = null;
13811 var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result.
13812
13813 var update = queue.firstUpdate;
13814 var resultState = newBaseState;
13815
13816 while (update !== null) {
13817 var updateExpirationTime = update.expirationTime;
13818
13819 if (updateExpirationTime < renderExpirationTime) {
13820 // This update does not have sufficient priority. Skip it.
13821 if (newFirstUpdate === null) {
13822 // This is the first skipped update. It will be the first update in
13823 // the new list.
13824 newFirstUpdate = update; // Since this is the first update that was skipped, the current result
13825 // is the new base state.
13826
13827 newBaseState = resultState;
13828 } // Since this update will remain in the list, update the remaining
13829 // expiration time.
13830
13831
13832 if (newExpirationTime < updateExpirationTime) {
13833 newExpirationTime = updateExpirationTime;
13834 }
13835 } else {
13836 // This update does have sufficient priority.
13837 // Mark the event time of this update as relevant to this render pass.
13838 // TODO: This should ideally use the true event time of this update rather than
13839 // its priority which is a derived and not reverseable value.
13840 // TODO: We should skip this update if it was already committed but currently
13841 // we have no way of detecting the difference between a committed and suspended
13842 // update here.
13843 markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result.
13844
13845 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13846 var callback = update.callback;
13847
13848 if (callback !== null) {
13849 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13850
13851 update.nextEffect = null;
13852
13853 if (queue.lastEffect === null) {
13854 queue.firstEffect = queue.lastEffect = update;
13855 } else {
13856 queue.lastEffect.nextEffect = update;
13857 queue.lastEffect = update;
13858 }
13859 }
13860 } // Continue to the next update.
13861
13862
13863 update = update.next;
13864 } // Separately, iterate though the list of captured updates.
13865
13866
13867 var newFirstCapturedUpdate = null;
13868 update = queue.firstCapturedUpdate;
13869
13870 while (update !== null) {
13871 var _updateExpirationTime = update.expirationTime;
13872
13873 if (_updateExpirationTime < renderExpirationTime) {
13874 // This update does not have sufficient priority. Skip it.
13875 if (newFirstCapturedUpdate === null) {
13876 // This is the first skipped captured update. It will be the first
13877 // update in the new list.
13878 newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is
13879 // the new base state.
13880
13881 if (newFirstUpdate === null) {
13882 newBaseState = resultState;
13883 }
13884 } // Since this update will remain in the list, update the remaining
13885 // expiration time.
13886
13887
13888 if (newExpirationTime < _updateExpirationTime) {
13889 newExpirationTime = _updateExpirationTime;
13890 }
13891 } else {
13892 // This update does have sufficient priority. Process it and compute
13893 // a new result.
13894 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
13895 var _callback = update.callback;
13896
13897 if (_callback !== null) {
13898 workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render.
13899
13900 update.nextEffect = null;
13901
13902 if (queue.lastCapturedEffect === null) {
13903 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
13904 } else {
13905 queue.lastCapturedEffect.nextEffect = update;
13906 queue.lastCapturedEffect = update;
13907 }
13908 }
13909 }
13910
13911 update = update.next;
13912 }
13913
13914 if (newFirstUpdate === null) {
13915 queue.lastUpdate = null;
13916 }
13917
13918 if (newFirstCapturedUpdate === null) {
13919 queue.lastCapturedUpdate = null;
13920 } else {
13921 workInProgress.effectTag |= Callback;
13922 }
13923
13924 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
13925 // We processed every update, without skipping. That means the new base
13926 // state is the same as the result state.
13927 newBaseState = resultState;
13928 }
13929
13930 queue.baseState = newBaseState;
13931 queue.firstUpdate = newFirstUpdate;
13932 queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
13933 // This should be fine because the only two other things that contribute to
13934 // expiration time are props and context. We're already in the middle of the
13935 // begin phase by the time we start processing the queue, so we've already
13936 // dealt with the props. Context in components that specify
13937 // shouldComponentUpdate is tricky; but we'll have to account for
13938 // that regardless.
13939
13940 markUnprocessedUpdateTime(newExpirationTime);
13941 workInProgress.expirationTime = newExpirationTime;
13942 workInProgress.memoizedState = resultState;
13943
13944 {
13945 currentlyProcessingQueue = null;
13946 }
13947}
13948
13949function callCallback(callback, context) {
13950 if (!(typeof callback === 'function')) {
13951 {
13952 throw Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback);
13953 }
13954 }
13955
13956 callback.call(context);
13957}
13958
13959function resetHasForceUpdateBeforeProcessing() {
13960 hasForceUpdate = false;
13961}
13962function checkHasForceUpdateAfterProcessing() {
13963 return hasForceUpdate;
13964}
13965function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
13966 // If the finished render included captured updates, and there are still
13967 // lower priority updates left over, we need to keep the captured updates
13968 // in the queue so that they are rebased and not dropped once we process the
13969 // queue again at the lower priority.
13970 if (finishedQueue.firstCapturedUpdate !== null) {
13971 // Join the captured update list to the end of the normal list.
13972 if (finishedQueue.lastUpdate !== null) {
13973 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
13974 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
13975 } // Clear the list of captured updates.
13976
13977
13978 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
13979 } // Commit the effects
13980
13981
13982 commitUpdateEffects(finishedQueue.firstEffect, instance);
13983 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
13984 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
13985 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
13986}
13987
13988function commitUpdateEffects(effect, instance) {
13989 while (effect !== null) {
13990 var callback = effect.callback;
13991
13992 if (callback !== null) {
13993 effect.callback = null;
13994 callCallback(callback, instance);
13995 }
13996
13997 effect = effect.nextEffect;
13998 }
13999}
14000
14001var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
14002function requestCurrentSuspenseConfig() {
14003 return ReactCurrentBatchConfig.suspense;
14004}
14005
14006var fakeInternalInstance = {};
14007var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default.
14008// We'll use it to determine whether we need to initialize legacy refs.
14009
14010var emptyRefsObject = new React.Component().refs;
14011var didWarnAboutStateAssignmentForComponent;
14012var didWarnAboutUninitializedState;
14013var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
14014var didWarnAboutLegacyLifecyclesAndDerivedState;
14015var didWarnAboutUndefinedDerivedState;
14016var warnOnUndefinedDerivedState;
14017var warnOnInvalidCallback$1;
14018var didWarnAboutDirectlyAssigningPropsToState;
14019var didWarnAboutContextTypeAndContextTypes;
14020var didWarnAboutInvalidateContextType;
14021
14022{
14023 didWarnAboutStateAssignmentForComponent = new Set();
14024 didWarnAboutUninitializedState = new Set();
14025 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
14026 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
14027 didWarnAboutDirectlyAssigningPropsToState = new Set();
14028 didWarnAboutUndefinedDerivedState = new Set();
14029 didWarnAboutContextTypeAndContextTypes = new Set();
14030 didWarnAboutInvalidateContextType = new Set();
14031 var didWarnOnInvalidCallback = new Set();
14032
14033 warnOnInvalidCallback$1 = function (callback, callerName) {
14034 if (callback === null || typeof callback === 'function') {
14035 return;
14036 }
14037
14038 var key = callerName + "_" + callback;
14039
14040 if (!didWarnOnInvalidCallback.has(key)) {
14041 didWarnOnInvalidCallback.add(key);
14042 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
14043 }
14044 };
14045
14046 warnOnUndefinedDerivedState = function (type, partialState) {
14047 if (partialState === undefined) {
14048 var componentName = getComponentName(type) || 'Component';
14049
14050 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
14051 didWarnAboutUndefinedDerivedState.add(componentName);
14052 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
14053 }
14054 }
14055 }; // This is so gross but it's at least non-critical and can be removed if
14056 // it causes problems. This is meant to give a nicer error message for
14057 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
14058 // ...)) which otherwise throws a "_processChildContext is not a function"
14059 // exception.
14060
14061
14062 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
14063 enumerable: false,
14064 value: function () {
14065 {
14066 {
14067 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).");
14068 }
14069 }
14070 }
14071 });
14072 Object.freeze(fakeInternalInstance);
14073}
14074
14075function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
14076 var prevState = workInProgress.memoizedState;
14077
14078 {
14079 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14080 // Invoke the function an extra time to help detect side-effects.
14081 getDerivedStateFromProps(nextProps, prevState);
14082 }
14083 }
14084
14085 var partialState = getDerivedStateFromProps(nextProps, prevState);
14086
14087 {
14088 warnOnUndefinedDerivedState(ctor, partialState);
14089 } // Merge the partial state and the previous state.
14090
14091
14092 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
14093 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
14094 // base state.
14095
14096 var updateQueue = workInProgress.updateQueue;
14097
14098 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
14099 updateQueue.baseState = memoizedState;
14100 }
14101}
14102var classComponentUpdater = {
14103 isMounted: isMounted,
14104 enqueueSetState: function (inst, payload, callback) {
14105 var fiber = get(inst);
14106 var currentTime = requestCurrentTimeForUpdate();
14107 var suspenseConfig = requestCurrentSuspenseConfig();
14108 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14109 var update = createUpdate(expirationTime, suspenseConfig);
14110 update.payload = payload;
14111
14112 if (callback !== undefined && callback !== null) {
14113 {
14114 warnOnInvalidCallback$1(callback, 'setState');
14115 }
14116
14117 update.callback = callback;
14118 }
14119
14120 enqueueUpdate(fiber, update);
14121 scheduleWork(fiber, expirationTime);
14122 },
14123 enqueueReplaceState: function (inst, payload, callback) {
14124 var fiber = get(inst);
14125 var currentTime = requestCurrentTimeForUpdate();
14126 var suspenseConfig = requestCurrentSuspenseConfig();
14127 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14128 var update = createUpdate(expirationTime, suspenseConfig);
14129 update.tag = ReplaceState;
14130 update.payload = payload;
14131
14132 if (callback !== undefined && callback !== null) {
14133 {
14134 warnOnInvalidCallback$1(callback, 'replaceState');
14135 }
14136
14137 update.callback = callback;
14138 }
14139
14140 enqueueUpdate(fiber, update);
14141 scheduleWork(fiber, expirationTime);
14142 },
14143 enqueueForceUpdate: function (inst, callback) {
14144 var fiber = get(inst);
14145 var currentTime = requestCurrentTimeForUpdate();
14146 var suspenseConfig = requestCurrentSuspenseConfig();
14147 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
14148 var update = createUpdate(expirationTime, suspenseConfig);
14149 update.tag = ForceUpdate;
14150
14151 if (callback !== undefined && callback !== null) {
14152 {
14153 warnOnInvalidCallback$1(callback, 'forceUpdate');
14154 }
14155
14156 update.callback = callback;
14157 }
14158
14159 enqueueUpdate(fiber, update);
14160 scheduleWork(fiber, expirationTime);
14161 }
14162};
14163
14164function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
14165 var instance = workInProgress.stateNode;
14166
14167 if (typeof instance.shouldComponentUpdate === 'function') {
14168 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
14169 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
14170 stopPhaseTimer();
14171
14172 {
14173 !(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;
14174 }
14175
14176 return shouldUpdate;
14177 }
14178
14179 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
14180 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
14181 }
14182
14183 return true;
14184}
14185
14186function checkClassInstance(workInProgress, ctor, newProps) {
14187 var instance = workInProgress.stateNode;
14188
14189 {
14190 var name = getComponentName(ctor) || 'Component';
14191 var renderPresent = instance.render;
14192
14193 if (!renderPresent) {
14194 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
14195 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
14196 } else {
14197 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
14198 }
14199 }
14200
14201 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
14202 !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;
14203 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
14204 !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;
14205 var noInstancePropTypes = !instance.propTypes;
14206 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
14207 var noInstanceContextType = !instance.contextType;
14208 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
14209
14210 if (disableLegacyContext) {
14211 if (ctor.childContextTypes) {
14212 warningWithoutStack$1(false, '%s uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', name);
14213 }
14214
14215 if (ctor.contextTypes) {
14216 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', name);
14217 }
14218 } else {
14219 var noInstanceContextTypes = !instance.contextTypes;
14220 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
14221
14222 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
14223 didWarnAboutContextTypeAndContextTypes.add(ctor);
14224 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
14225 }
14226 }
14227
14228 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
14229 !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;
14230
14231 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
14232 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');
14233 }
14234
14235 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
14236 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
14237 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
14238 !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;
14239 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
14240 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
14241 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
14242 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
14243 var hasMutatedProps = instance.props !== newProps;
14244 !(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;
14245 var noInstanceDefaultProps = !instance.defaultProps;
14246 !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;
14247
14248 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
14249 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
14250 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
14251 }
14252
14253 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
14254 !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;
14255 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
14256 !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;
14257 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
14258 !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;
14259 var _state = instance.state;
14260
14261 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
14262 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
14263 }
14264
14265 if (typeof instance.getChildContext === 'function') {
14266 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
14267 }
14268 }
14269}
14270
14271function adoptClassInstance(workInProgress, instance) {
14272 instance.updater = classComponentUpdater;
14273 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
14274
14275 set(instance, workInProgress);
14276
14277 {
14278 instance._reactInternalInstance = fakeInternalInstance;
14279 }
14280}
14281
14282function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
14283 var isLegacyContextConsumer = false;
14284 var unmaskedContext = emptyContextObject;
14285 var context = emptyContextObject;
14286 var contextType = ctor.contextType;
14287
14288 {
14289 if ('contextType' in ctor) {
14290 var isValid = // Allow null for conditional declaration
14291 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
14292
14293 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
14294 didWarnAboutInvalidateContextType.add(ctor);
14295 var addendum = '';
14296
14297 if (contextType === undefined) {
14298 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.';
14299 } else if (typeof contextType !== 'object') {
14300 addendum = ' However, it is set to a ' + typeof contextType + '.';
14301 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
14302 addendum = ' Did you accidentally pass the Context.Provider instead?';
14303 } else if (contextType._context !== undefined) {
14304 // <Context.Consumer>
14305 addendum = ' Did you accidentally pass the Context.Consumer instead?';
14306 } else {
14307 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
14308 }
14309
14310 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
14311 }
14312 }
14313 }
14314
14315 if (typeof contextType === 'object' && contextType !== null) {
14316 context = readContext(contextType);
14317 } else if (!disableLegacyContext) {
14318 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14319 var contextTypes = ctor.contextTypes;
14320 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
14321 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
14322 } // Instantiate twice to help detect side-effects.
14323
14324
14325 {
14326 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
14327 new ctor(props, context); // eslint-disable-line no-new
14328 }
14329 }
14330
14331 var instance = new ctor(props, context);
14332 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
14333 adoptClassInstance(workInProgress, instance);
14334
14335 {
14336 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
14337 var componentName = getComponentName(ctor) || 'Component';
14338
14339 if (!didWarnAboutUninitializedState.has(componentName)) {
14340 didWarnAboutUninitializedState.add(componentName);
14341 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);
14342 }
14343 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
14344 // Warn about these lifecycles if they are present.
14345 // Don't warn about react-lifecycles-compat polyfilled methods though.
14346
14347
14348 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
14349 var foundWillMountName = null;
14350 var foundWillReceivePropsName = null;
14351 var foundWillUpdateName = null;
14352
14353 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
14354 foundWillMountName = 'componentWillMount';
14355 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
14356 foundWillMountName = 'UNSAFE_componentWillMount';
14357 }
14358
14359 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
14360 foundWillReceivePropsName = 'componentWillReceiveProps';
14361 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14362 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
14363 }
14364
14365 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
14366 foundWillUpdateName = 'componentWillUpdate';
14367 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14368 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
14369 }
14370
14371 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
14372 var _componentName = getComponentName(ctor) || 'Component';
14373
14374 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
14375
14376 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
14377 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
14378 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 : '');
14379 }
14380 }
14381 }
14382 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
14383 // ReactFiberContext usually updates this cache but can't for newly-created instances.
14384
14385
14386 if (isLegacyContextConsumer) {
14387 cacheContext(workInProgress, unmaskedContext, context);
14388 }
14389
14390 return instance;
14391}
14392
14393function callComponentWillMount(workInProgress, instance) {
14394 startPhaseTimer(workInProgress, 'componentWillMount');
14395 var oldState = instance.state;
14396
14397 if (typeof instance.componentWillMount === 'function') {
14398 instance.componentWillMount();
14399 }
14400
14401 if (typeof instance.UNSAFE_componentWillMount === 'function') {
14402 instance.UNSAFE_componentWillMount();
14403 }
14404
14405 stopPhaseTimer();
14406
14407 if (oldState !== instance.state) {
14408 {
14409 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');
14410 }
14411
14412 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14413 }
14414}
14415
14416function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
14417 var oldState = instance.state;
14418 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
14419
14420 if (typeof instance.componentWillReceiveProps === 'function') {
14421 instance.componentWillReceiveProps(newProps, nextContext);
14422 }
14423
14424 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
14425 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
14426 }
14427
14428 stopPhaseTimer();
14429
14430 if (instance.state !== oldState) {
14431 {
14432 var componentName = getComponentName(workInProgress.type) || 'Component';
14433
14434 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
14435 didWarnAboutStateAssignmentForComponent.add(componentName);
14436 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
14437 }
14438 }
14439
14440 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
14441 }
14442} // Invokes the mount life-cycles on a previously never rendered instance.
14443
14444
14445function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14446 {
14447 checkClassInstance(workInProgress, ctor, newProps);
14448 }
14449
14450 var instance = workInProgress.stateNode;
14451 instance.props = newProps;
14452 instance.state = workInProgress.memoizedState;
14453 instance.refs = emptyRefsObject;
14454 var contextType = ctor.contextType;
14455
14456 if (typeof contextType === 'object' && contextType !== null) {
14457 instance.context = readContext(contextType);
14458 } else if (disableLegacyContext) {
14459 instance.context = emptyContextObject;
14460 } else {
14461 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14462 instance.context = getMaskedContext(workInProgress, unmaskedContext);
14463 }
14464
14465 {
14466 if (instance.state === newProps) {
14467 var componentName = getComponentName(ctor) || 'Component';
14468
14469 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
14470 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
14471 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);
14472 }
14473 }
14474
14475 if (workInProgress.mode & StrictMode) {
14476 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
14477 }
14478
14479 if (warnAboutDeprecatedLifecycles) {
14480 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
14481 }
14482 }
14483
14484 var updateQueue = workInProgress.updateQueue;
14485
14486 if (updateQueue !== null) {
14487 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14488 instance.state = workInProgress.memoizedState;
14489 }
14490
14491 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14492
14493 if (typeof getDerivedStateFromProps === 'function') {
14494 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14495 instance.state = workInProgress.memoizedState;
14496 } // In order to support react-lifecycles-compat polyfilled components,
14497 // Unsafe lifecycles should not be invoked for components using the new APIs.
14498
14499
14500 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14501 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
14502 // process them now.
14503
14504 updateQueue = workInProgress.updateQueue;
14505
14506 if (updateQueue !== null) {
14507 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14508 instance.state = workInProgress.memoizedState;
14509 }
14510 }
14511
14512 if (typeof instance.componentDidMount === 'function') {
14513 workInProgress.effectTag |= Update;
14514 }
14515}
14516
14517function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
14518 var instance = workInProgress.stateNode;
14519 var oldProps = workInProgress.memoizedProps;
14520 instance.props = oldProps;
14521 var oldContext = instance.context;
14522 var contextType = ctor.contextType;
14523 var nextContext = emptyContextObject;
14524
14525 if (typeof contextType === 'object' && contextType !== null) {
14526 nextContext = readContext(contextType);
14527 } else if (!disableLegacyContext) {
14528 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14529 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
14530 }
14531
14532 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14533 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14534 // ever the previously attempted to render - not the "current". However,
14535 // during componentDidUpdate we pass the "current" props.
14536 // In order to support react-lifecycles-compat polyfilled components,
14537 // Unsafe lifecycles should not be invoked for components using the new APIs.
14538
14539 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14540 if (oldProps !== newProps || oldContext !== nextContext) {
14541 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14542 }
14543 }
14544
14545 resetHasForceUpdateBeforeProcessing();
14546 var oldState = workInProgress.memoizedState;
14547 var newState = instance.state = oldState;
14548 var updateQueue = workInProgress.updateQueue;
14549
14550 if (updateQueue !== null) {
14551 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14552 newState = workInProgress.memoizedState;
14553 }
14554
14555 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14556 // If an update was already in progress, we should schedule an Update
14557 // effect even though we're bailing out, so that cWU/cDU are called.
14558 if (typeof instance.componentDidMount === 'function') {
14559 workInProgress.effectTag |= Update;
14560 }
14561
14562 return false;
14563 }
14564
14565 if (typeof getDerivedStateFromProps === 'function') {
14566 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14567 newState = workInProgress.memoizedState;
14568 }
14569
14570 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14571
14572 if (shouldUpdate) {
14573 // In order to support react-lifecycles-compat polyfilled components,
14574 // Unsafe lifecycles should not be invoked for components using the new APIs.
14575 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
14576 startPhaseTimer(workInProgress, 'componentWillMount');
14577
14578 if (typeof instance.componentWillMount === 'function') {
14579 instance.componentWillMount();
14580 }
14581
14582 if (typeof instance.UNSAFE_componentWillMount === 'function') {
14583 instance.UNSAFE_componentWillMount();
14584 }
14585
14586 stopPhaseTimer();
14587 }
14588
14589 if (typeof instance.componentDidMount === 'function') {
14590 workInProgress.effectTag |= Update;
14591 }
14592 } else {
14593 // If an update was already in progress, we should schedule an Update
14594 // effect even though we're bailing out, so that cWU/cDU are called.
14595 if (typeof instance.componentDidMount === 'function') {
14596 workInProgress.effectTag |= Update;
14597 } // If shouldComponentUpdate returned false, we should still update the
14598 // memoized state to indicate that this work can be reused.
14599
14600
14601 workInProgress.memoizedProps = newProps;
14602 workInProgress.memoizedState = newState;
14603 } // Update the existing instance's state, props, and context pointers even
14604 // if shouldComponentUpdate returns false.
14605
14606
14607 instance.props = newProps;
14608 instance.state = newState;
14609 instance.context = nextContext;
14610 return shouldUpdate;
14611} // Invokes the update life-cycles and returns false if it shouldn't rerender.
14612
14613
14614function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
14615 var instance = workInProgress.stateNode;
14616 var oldProps = workInProgress.memoizedProps;
14617 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
14618 var oldContext = instance.context;
14619 var contextType = ctor.contextType;
14620 var nextContext = emptyContextObject;
14621
14622 if (typeof contextType === 'object' && contextType !== null) {
14623 nextContext = readContext(contextType);
14624 } else if (!disableLegacyContext) {
14625 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
14626 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
14627 }
14628
14629 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
14630 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
14631 // ever the previously attempted to render - not the "current". However,
14632 // during componentDidUpdate we pass the "current" props.
14633 // In order to support react-lifecycles-compat polyfilled components,
14634 // Unsafe lifecycles should not be invoked for components using the new APIs.
14635
14636 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
14637 if (oldProps !== newProps || oldContext !== nextContext) {
14638 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
14639 }
14640 }
14641
14642 resetHasForceUpdateBeforeProcessing();
14643 var oldState = workInProgress.memoizedState;
14644 var newState = instance.state = oldState;
14645 var updateQueue = workInProgress.updateQueue;
14646
14647 if (updateQueue !== null) {
14648 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
14649 newState = workInProgress.memoizedState;
14650 }
14651
14652 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
14653 // If an update was already in progress, we should schedule an Update
14654 // effect even though we're bailing out, so that cWU/cDU are called.
14655 if (typeof instance.componentDidUpdate === 'function') {
14656 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14657 workInProgress.effectTag |= Update;
14658 }
14659 }
14660
14661 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14662 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14663 workInProgress.effectTag |= Snapshot;
14664 }
14665 }
14666
14667 return false;
14668 }
14669
14670 if (typeof getDerivedStateFromProps === 'function') {
14671 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
14672 newState = workInProgress.memoizedState;
14673 }
14674
14675 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
14676
14677 if (shouldUpdate) {
14678 // In order to support react-lifecycles-compat polyfilled components,
14679 // Unsafe lifecycles should not be invoked for components using the new APIs.
14680 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
14681 startPhaseTimer(workInProgress, 'componentWillUpdate');
14682
14683 if (typeof instance.componentWillUpdate === 'function') {
14684 instance.componentWillUpdate(newProps, newState, nextContext);
14685 }
14686
14687 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
14688 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
14689 }
14690
14691 stopPhaseTimer();
14692 }
14693
14694 if (typeof instance.componentDidUpdate === 'function') {
14695 workInProgress.effectTag |= Update;
14696 }
14697
14698 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14699 workInProgress.effectTag |= Snapshot;
14700 }
14701 } else {
14702 // If an update was already in progress, we should schedule an Update
14703 // effect even though we're bailing out, so that cWU/cDU are called.
14704 if (typeof instance.componentDidUpdate === 'function') {
14705 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14706 workInProgress.effectTag |= Update;
14707 }
14708 }
14709
14710 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
14711 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
14712 workInProgress.effectTag |= Snapshot;
14713 }
14714 } // If shouldComponentUpdate returned false, we should still update the
14715 // memoized props/state to indicate that this work can be reused.
14716
14717
14718 workInProgress.memoizedProps = newProps;
14719 workInProgress.memoizedState = newState;
14720 } // Update the existing instance's state, props, and context pointers even
14721 // if shouldComponentUpdate returns false.
14722
14723
14724 instance.props = newProps;
14725 instance.state = newState;
14726 instance.context = nextContext;
14727 return shouldUpdate;
14728}
14729
14730var didWarnAboutMaps;
14731var didWarnAboutGenerators;
14732var didWarnAboutStringRefs;
14733var ownerHasKeyUseWarning;
14734var ownerHasFunctionTypeWarning;
14735
14736var warnForMissingKey = function (child) {};
14737
14738{
14739 didWarnAboutMaps = false;
14740 didWarnAboutGenerators = false;
14741 didWarnAboutStringRefs = {};
14742 /**
14743 * Warn if there's no key explicitly set on dynamic arrays of children or
14744 * object keys are not valid. This allows us to keep track of children between
14745 * updates.
14746 */
14747
14748 ownerHasKeyUseWarning = {};
14749 ownerHasFunctionTypeWarning = {};
14750
14751 warnForMissingKey = function (child) {
14752 if (child === null || typeof child !== 'object') {
14753 return;
14754 }
14755
14756 if (!child._store || child._store.validated || child.key != null) {
14757 return;
14758 }
14759
14760 if (!(typeof child._store === 'object')) {
14761 {
14762 throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
14763 }
14764 }
14765
14766 child._store.validated = true;
14767 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
14768
14769 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
14770 return;
14771 }
14772
14773 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
14774 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
14775 };
14776}
14777
14778var isArray = Array.isArray;
14779
14780function coerceRef(returnFiber, current$$1, element) {
14781 var mixedRef = element.ref;
14782
14783 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
14784 {
14785 // TODO: Clean this up once we turn on the string ref warning for
14786 // everyone, because the strict mode case will no longer be relevant
14787 if (returnFiber.mode & StrictMode || warnAboutStringRefs) {
14788 var componentName = getComponentName(returnFiber.type) || 'Component';
14789
14790 if (!didWarnAboutStringRefs[componentName]) {
14791 if (warnAboutStringRefs) {
14792 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));
14793 } else {
14794 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));
14795 }
14796
14797 didWarnAboutStringRefs[componentName] = true;
14798 }
14799 }
14800 }
14801
14802 if (element._owner) {
14803 var owner = element._owner;
14804 var inst;
14805
14806 if (owner) {
14807 var ownerFiber = owner;
14808
14809 if (!(ownerFiber.tag === ClassComponent)) {
14810 {
14811 throw Error("Function components cannot have refs. Did you mean to use React.forwardRef()?");
14812 }
14813 }
14814
14815 inst = ownerFiber.stateNode;
14816 }
14817
14818 if (!inst) {
14819 {
14820 throw Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
14821 }
14822 }
14823
14824 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
14825
14826 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
14827 return current$$1.ref;
14828 }
14829
14830 var ref = function (value) {
14831 var refs = inst.refs;
14832
14833 if (refs === emptyRefsObject) {
14834 // This is a lazy pooled frozen object, so we need to initialize.
14835 refs = inst.refs = {};
14836 }
14837
14838 if (value === null) {
14839 delete refs[stringRef];
14840 } else {
14841 refs[stringRef] = value;
14842 }
14843 };
14844
14845 ref._stringRef = stringRef;
14846 return ref;
14847 } else {
14848 if (!(typeof mixedRef === 'string')) {
14849 {
14850 throw Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
14851 }
14852 }
14853
14854 if (!element._owner) {
14855 {
14856 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.");
14857 }
14858 }
14859 }
14860 }
14861
14862 return mixedRef;
14863}
14864
14865function throwOnInvalidObjectType(returnFiber, newChild) {
14866 if (returnFiber.type !== 'textarea') {
14867 var addendum = '';
14868
14869 {
14870 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
14871 }
14872
14873 {
14874 {
14875 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);
14876 }
14877 }
14878 }
14879}
14880
14881function warnOnFunctionType() {
14882 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();
14883
14884 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
14885 return;
14886 }
14887
14888 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
14889 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.');
14890} // This wrapper function exists because I expect to clone the code in each path
14891// to be able to optimize each path individually by branching early. This needs
14892// a compiler or we can do it manually. Helpers that don't need this branching
14893// live outside of this function.
14894
14895
14896function ChildReconciler(shouldTrackSideEffects) {
14897 function deleteChild(returnFiber, childToDelete) {
14898 if (!shouldTrackSideEffects) {
14899 // Noop.
14900 return;
14901 } // Deletions are added in reversed order so we add it to the front.
14902 // At this point, the return fiber's effect list is empty except for
14903 // deletions, so we can just append the deletion to the list. The remaining
14904 // effects aren't added until the complete phase. Once we implement
14905 // resuming, this may not be true.
14906
14907
14908 var last = returnFiber.lastEffect;
14909
14910 if (last !== null) {
14911 last.nextEffect = childToDelete;
14912 returnFiber.lastEffect = childToDelete;
14913 } else {
14914 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
14915 }
14916
14917 childToDelete.nextEffect = null;
14918 childToDelete.effectTag = Deletion;
14919 }
14920
14921 function deleteRemainingChildren(returnFiber, currentFirstChild) {
14922 if (!shouldTrackSideEffects) {
14923 // Noop.
14924 return null;
14925 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
14926 // assuming that after the first child we've already added everything.
14927
14928
14929 var childToDelete = currentFirstChild;
14930
14931 while (childToDelete !== null) {
14932 deleteChild(returnFiber, childToDelete);
14933 childToDelete = childToDelete.sibling;
14934 }
14935
14936 return null;
14937 }
14938
14939 function mapRemainingChildren(returnFiber, currentFirstChild) {
14940 // Add the remaining children to a temporary map so that we can find them by
14941 // keys quickly. Implicit (null) keys get added to this set with their index
14942 // instead.
14943 var existingChildren = new Map();
14944 var existingChild = currentFirstChild;
14945
14946 while (existingChild !== null) {
14947 if (existingChild.key !== null) {
14948 existingChildren.set(existingChild.key, existingChild);
14949 } else {
14950 existingChildren.set(existingChild.index, existingChild);
14951 }
14952
14953 existingChild = existingChild.sibling;
14954 }
14955
14956 return existingChildren;
14957 }
14958
14959 function useFiber(fiber, pendingProps, expirationTime) {
14960 // We currently set sibling to null and index to 0 here because it is easy
14961 // to forget to do before returning it. E.g. for the single child case.
14962 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
14963 clone.index = 0;
14964 clone.sibling = null;
14965 return clone;
14966 }
14967
14968 function placeChild(newFiber, lastPlacedIndex, newIndex) {
14969 newFiber.index = newIndex;
14970
14971 if (!shouldTrackSideEffects) {
14972 // Noop.
14973 return lastPlacedIndex;
14974 }
14975
14976 var current$$1 = newFiber.alternate;
14977
14978 if (current$$1 !== null) {
14979 var oldIndex = current$$1.index;
14980
14981 if (oldIndex < lastPlacedIndex) {
14982 // This is a move.
14983 newFiber.effectTag = Placement;
14984 return lastPlacedIndex;
14985 } else {
14986 // This item can stay in place.
14987 return oldIndex;
14988 }
14989 } else {
14990 // This is an insertion.
14991 newFiber.effectTag = Placement;
14992 return lastPlacedIndex;
14993 }
14994 }
14995
14996 function placeSingleChild(newFiber) {
14997 // This is simpler for the single child case. We only need to do a
14998 // placement for inserting new children.
14999 if (shouldTrackSideEffects && newFiber.alternate === null) {
15000 newFiber.effectTag = Placement;
15001 }
15002
15003 return newFiber;
15004 }
15005
15006 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
15007 if (current$$1 === null || current$$1.tag !== HostText) {
15008 // Insert
15009 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15010 created.return = returnFiber;
15011 return created;
15012 } else {
15013 // Update
15014 var existing = useFiber(current$$1, textContent, expirationTime);
15015 existing.return = returnFiber;
15016 return existing;
15017 }
15018 }
15019
15020 function updateElement(returnFiber, current$$1, element, expirationTime) {
15021 if (current$$1 !== null && (current$$1.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
15022 isCompatibleFamilyForHotReloading(current$$1, element)))) {
15023 // Move based on index
15024 var existing = useFiber(current$$1, element.props, expirationTime);
15025 existing.ref = coerceRef(returnFiber, current$$1, element);
15026 existing.return = returnFiber;
15027
15028 {
15029 existing._debugSource = element._source;
15030 existing._debugOwner = element._owner;
15031 }
15032
15033 return existing;
15034 } else {
15035 // Insert
15036 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
15037 created.ref = coerceRef(returnFiber, current$$1, element);
15038 created.return = returnFiber;
15039 return created;
15040 }
15041 }
15042
15043 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
15044 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
15045 // Insert
15046 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15047 created.return = returnFiber;
15048 return created;
15049 } else {
15050 // Update
15051 var existing = useFiber(current$$1, portal.children || [], expirationTime);
15052 existing.return = returnFiber;
15053 return existing;
15054 }
15055 }
15056
15057 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
15058 if (current$$1 === null || current$$1.tag !== Fragment) {
15059 // Insert
15060 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
15061 created.return = returnFiber;
15062 return created;
15063 } else {
15064 // Update
15065 var existing = useFiber(current$$1, fragment, expirationTime);
15066 existing.return = returnFiber;
15067 return existing;
15068 }
15069 }
15070
15071 function createChild(returnFiber, newChild, expirationTime) {
15072 if (typeof newChild === 'string' || typeof newChild === 'number') {
15073 // Text nodes don't have keys. If the previous node is implicitly keyed
15074 // we can continue to replace it without aborting even if it is not a text
15075 // node.
15076 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
15077 created.return = returnFiber;
15078 return created;
15079 }
15080
15081 if (typeof newChild === 'object' && newChild !== null) {
15082 switch (newChild.$$typeof) {
15083 case REACT_ELEMENT_TYPE:
15084 {
15085 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
15086
15087 _created.ref = coerceRef(returnFiber, null, newChild);
15088 _created.return = returnFiber;
15089 return _created;
15090 }
15091
15092 case REACT_PORTAL_TYPE:
15093 {
15094 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
15095
15096 _created2.return = returnFiber;
15097 return _created2;
15098 }
15099 }
15100
15101 if (isArray(newChild) || getIteratorFn(newChild)) {
15102 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
15103
15104 _created3.return = returnFiber;
15105 return _created3;
15106 }
15107
15108 throwOnInvalidObjectType(returnFiber, newChild);
15109 }
15110
15111 {
15112 if (typeof newChild === 'function') {
15113 warnOnFunctionType();
15114 }
15115 }
15116
15117 return null;
15118 }
15119
15120 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
15121 // Update the fiber if the keys match, otherwise return null.
15122 var key = oldFiber !== null ? oldFiber.key : null;
15123
15124 if (typeof newChild === 'string' || typeof newChild === 'number') {
15125 // Text nodes don't have keys. If the previous node is implicitly keyed
15126 // we can continue to replace it without aborting even if it is not a text
15127 // node.
15128 if (key !== null) {
15129 return null;
15130 }
15131
15132 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
15133 }
15134
15135 if (typeof newChild === 'object' && newChild !== null) {
15136 switch (newChild.$$typeof) {
15137 case REACT_ELEMENT_TYPE:
15138 {
15139 if (newChild.key === key) {
15140 if (newChild.type === REACT_FRAGMENT_TYPE) {
15141 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
15142 }
15143
15144 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
15145 } else {
15146 return null;
15147 }
15148 }
15149
15150 case REACT_PORTAL_TYPE:
15151 {
15152 if (newChild.key === key) {
15153 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
15154 } else {
15155 return null;
15156 }
15157 }
15158 }
15159
15160 if (isArray(newChild) || getIteratorFn(newChild)) {
15161 if (key !== null) {
15162 return null;
15163 }
15164
15165 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
15166 }
15167
15168 throwOnInvalidObjectType(returnFiber, newChild);
15169 }
15170
15171 {
15172 if (typeof newChild === 'function') {
15173 warnOnFunctionType();
15174 }
15175 }
15176
15177 return null;
15178 }
15179
15180 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
15181 if (typeof newChild === 'string' || typeof newChild === 'number') {
15182 // Text nodes don't have keys, so we neither have to check the old nor
15183 // new node for the key. If both are text nodes, they match.
15184 var matchedFiber = existingChildren.get(newIdx) || null;
15185 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
15186 }
15187
15188 if (typeof newChild === 'object' && newChild !== null) {
15189 switch (newChild.$$typeof) {
15190 case REACT_ELEMENT_TYPE:
15191 {
15192 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15193
15194 if (newChild.type === REACT_FRAGMENT_TYPE) {
15195 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
15196 }
15197
15198 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
15199 }
15200
15201 case REACT_PORTAL_TYPE:
15202 {
15203 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
15204
15205 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
15206 }
15207 }
15208
15209 if (isArray(newChild) || getIteratorFn(newChild)) {
15210 var _matchedFiber3 = existingChildren.get(newIdx) || null;
15211
15212 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
15213 }
15214
15215 throwOnInvalidObjectType(returnFiber, newChild);
15216 }
15217
15218 {
15219 if (typeof newChild === 'function') {
15220 warnOnFunctionType();
15221 }
15222 }
15223
15224 return null;
15225 }
15226 /**
15227 * Warns if there is a duplicate or missing key
15228 */
15229
15230
15231 function warnOnInvalidKey(child, knownKeys) {
15232 {
15233 if (typeof child !== 'object' || child === null) {
15234 return knownKeys;
15235 }
15236
15237 switch (child.$$typeof) {
15238 case REACT_ELEMENT_TYPE:
15239 case REACT_PORTAL_TYPE:
15240 warnForMissingKey(child);
15241 var key = child.key;
15242
15243 if (typeof key !== 'string') {
15244 break;
15245 }
15246
15247 if (knownKeys === null) {
15248 knownKeys = new Set();
15249 knownKeys.add(key);
15250 break;
15251 }
15252
15253 if (!knownKeys.has(key)) {
15254 knownKeys.add(key);
15255 break;
15256 }
15257
15258 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);
15259 break;
15260
15261 default:
15262 break;
15263 }
15264 }
15265
15266 return knownKeys;
15267 }
15268
15269 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
15270 // This algorithm can't optimize by searching from both ends since we
15271 // don't have backpointers on fibers. I'm trying to see how far we can get
15272 // with that model. If it ends up not being worth the tradeoffs, we can
15273 // add it later.
15274 // Even with a two ended optimization, we'd want to optimize for the case
15275 // where there are few changes and brute force the comparison instead of
15276 // going for the Map. It'd like to explore hitting that path first in
15277 // forward-only mode and only go for the Map once we notice that we need
15278 // lots of look ahead. This doesn't handle reversal as well as two ended
15279 // search but that's unusual. Besides, for the two ended optimization to
15280 // work on Iterables, we'd need to copy the whole set.
15281 // In this first iteration, we'll just live with hitting the bad case
15282 // (adding everything to a Map) in for every insert/move.
15283 // If you change this code, also update reconcileChildrenIterator() which
15284 // uses the same algorithm.
15285 {
15286 // First, validate keys.
15287 var knownKeys = null;
15288
15289 for (var i = 0; i < newChildren.length; i++) {
15290 var child = newChildren[i];
15291 knownKeys = warnOnInvalidKey(child, knownKeys);
15292 }
15293 }
15294
15295 var resultingFirstChild = null;
15296 var previousNewFiber = null;
15297 var oldFiber = currentFirstChild;
15298 var lastPlacedIndex = 0;
15299 var newIdx = 0;
15300 var nextOldFiber = null;
15301
15302 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
15303 if (oldFiber.index > newIdx) {
15304 nextOldFiber = oldFiber;
15305 oldFiber = null;
15306 } else {
15307 nextOldFiber = oldFiber.sibling;
15308 }
15309
15310 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
15311
15312 if (newFiber === null) {
15313 // TODO: This breaks on empty slots like null children. That's
15314 // unfortunate because it triggers the slow path all the time. We need
15315 // a better way to communicate whether this was a miss or null,
15316 // boolean, undefined, etc.
15317 if (oldFiber === null) {
15318 oldFiber = nextOldFiber;
15319 }
15320
15321 break;
15322 }
15323
15324 if (shouldTrackSideEffects) {
15325 if (oldFiber && newFiber.alternate === null) {
15326 // We matched the slot, but we didn't reuse the existing fiber, so we
15327 // need to delete the existing child.
15328 deleteChild(returnFiber, oldFiber);
15329 }
15330 }
15331
15332 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15333
15334 if (previousNewFiber === null) {
15335 // TODO: Move out of the loop. This only happens for the first run.
15336 resultingFirstChild = newFiber;
15337 } else {
15338 // TODO: Defer siblings if we're not at the right index for this slot.
15339 // I.e. if we had null values before, then we want to defer this
15340 // for each null value. However, we also don't want to call updateSlot
15341 // with the previous one.
15342 previousNewFiber.sibling = newFiber;
15343 }
15344
15345 previousNewFiber = newFiber;
15346 oldFiber = nextOldFiber;
15347 }
15348
15349 if (newIdx === newChildren.length) {
15350 // We've reached the end of the new children. We can delete the rest.
15351 deleteRemainingChildren(returnFiber, oldFiber);
15352 return resultingFirstChild;
15353 }
15354
15355 if (oldFiber === null) {
15356 // If we don't have any more existing children we can choose a fast path
15357 // since the rest will all be insertions.
15358 for (; newIdx < newChildren.length; newIdx++) {
15359 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
15360
15361 if (_newFiber === null) {
15362 continue;
15363 }
15364
15365 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
15366
15367 if (previousNewFiber === null) {
15368 // TODO: Move out of the loop. This only happens for the first run.
15369 resultingFirstChild = _newFiber;
15370 } else {
15371 previousNewFiber.sibling = _newFiber;
15372 }
15373
15374 previousNewFiber = _newFiber;
15375 }
15376
15377 return resultingFirstChild;
15378 } // Add all children to a key map for quick lookups.
15379
15380
15381 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15382
15383 for (; newIdx < newChildren.length; newIdx++) {
15384 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
15385
15386 if (_newFiber2 !== null) {
15387 if (shouldTrackSideEffects) {
15388 if (_newFiber2.alternate !== null) {
15389 // The new fiber is a work in progress, but if there exists a
15390 // current, that means that we reused the fiber. We need to delete
15391 // it from the child list so that we don't add it to the deletion
15392 // list.
15393 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
15394 }
15395 }
15396
15397 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
15398
15399 if (previousNewFiber === null) {
15400 resultingFirstChild = _newFiber2;
15401 } else {
15402 previousNewFiber.sibling = _newFiber2;
15403 }
15404
15405 previousNewFiber = _newFiber2;
15406 }
15407 }
15408
15409 if (shouldTrackSideEffects) {
15410 // Any existing children that weren't consumed above were deleted. We need
15411 // to add them to the deletion list.
15412 existingChildren.forEach(function (child) {
15413 return deleteChild(returnFiber, child);
15414 });
15415 }
15416
15417 return resultingFirstChild;
15418 }
15419
15420 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
15421 // This is the same implementation as reconcileChildrenArray(),
15422 // but using the iterator instead.
15423 var iteratorFn = getIteratorFn(newChildrenIterable);
15424
15425 if (!(typeof iteratorFn === 'function')) {
15426 {
15427 throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
15428 }
15429 }
15430
15431 {
15432 // We don't support rendering Generators because it's a mutation.
15433 // See https://github.com/facebook/react/issues/12995
15434 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
15435 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
15436 !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;
15437 didWarnAboutGenerators = true;
15438 } // Warn about using Maps as children
15439
15440
15441 if (newChildrenIterable.entries === iteratorFn) {
15442 !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;
15443 didWarnAboutMaps = true;
15444 } // First, validate keys.
15445 // We'll get a different iterator later for the main pass.
15446
15447
15448 var _newChildren = iteratorFn.call(newChildrenIterable);
15449
15450 if (_newChildren) {
15451 var knownKeys = null;
15452
15453 var _step = _newChildren.next();
15454
15455 for (; !_step.done; _step = _newChildren.next()) {
15456 var child = _step.value;
15457 knownKeys = warnOnInvalidKey(child, knownKeys);
15458 }
15459 }
15460 }
15461
15462 var newChildren = iteratorFn.call(newChildrenIterable);
15463
15464 if (!(newChildren != null)) {
15465 {
15466 throw Error("An iterable object provided no iterator.");
15467 }
15468 }
15469
15470 var resultingFirstChild = null;
15471 var previousNewFiber = null;
15472 var oldFiber = currentFirstChild;
15473 var lastPlacedIndex = 0;
15474 var newIdx = 0;
15475 var nextOldFiber = null;
15476 var step = newChildren.next();
15477
15478 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
15479 if (oldFiber.index > newIdx) {
15480 nextOldFiber = oldFiber;
15481 oldFiber = null;
15482 } else {
15483 nextOldFiber = oldFiber.sibling;
15484 }
15485
15486 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
15487
15488 if (newFiber === null) {
15489 // TODO: This breaks on empty slots like null children. That's
15490 // unfortunate because it triggers the slow path all the time. We need
15491 // a better way to communicate whether this was a miss or null,
15492 // boolean, undefined, etc.
15493 if (oldFiber === null) {
15494 oldFiber = nextOldFiber;
15495 }
15496
15497 break;
15498 }
15499
15500 if (shouldTrackSideEffects) {
15501 if (oldFiber && newFiber.alternate === null) {
15502 // We matched the slot, but we didn't reuse the existing fiber, so we
15503 // need to delete the existing child.
15504 deleteChild(returnFiber, oldFiber);
15505 }
15506 }
15507
15508 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
15509
15510 if (previousNewFiber === null) {
15511 // TODO: Move out of the loop. This only happens for the first run.
15512 resultingFirstChild = newFiber;
15513 } else {
15514 // TODO: Defer siblings if we're not at the right index for this slot.
15515 // I.e. if we had null values before, then we want to defer this
15516 // for each null value. However, we also don't want to call updateSlot
15517 // with the previous one.
15518 previousNewFiber.sibling = newFiber;
15519 }
15520
15521 previousNewFiber = newFiber;
15522 oldFiber = nextOldFiber;
15523 }
15524
15525 if (step.done) {
15526 // We've reached the end of the new children. We can delete the rest.
15527 deleteRemainingChildren(returnFiber, oldFiber);
15528 return resultingFirstChild;
15529 }
15530
15531 if (oldFiber === null) {
15532 // If we don't have any more existing children we can choose a fast path
15533 // since the rest will all be insertions.
15534 for (; !step.done; newIdx++, step = newChildren.next()) {
15535 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
15536
15537 if (_newFiber3 === null) {
15538 continue;
15539 }
15540
15541 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
15542
15543 if (previousNewFiber === null) {
15544 // TODO: Move out of the loop. This only happens for the first run.
15545 resultingFirstChild = _newFiber3;
15546 } else {
15547 previousNewFiber.sibling = _newFiber3;
15548 }
15549
15550 previousNewFiber = _newFiber3;
15551 }
15552
15553 return resultingFirstChild;
15554 } // Add all children to a key map for quick lookups.
15555
15556
15557 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
15558
15559 for (; !step.done; newIdx++, step = newChildren.next()) {
15560 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
15561
15562 if (_newFiber4 !== null) {
15563 if (shouldTrackSideEffects) {
15564 if (_newFiber4.alternate !== null) {
15565 // The new fiber is a work in progress, but if there exists a
15566 // current, that means that we reused the fiber. We need to delete
15567 // it from the child list so that we don't add it to the deletion
15568 // list.
15569 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
15570 }
15571 }
15572
15573 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
15574
15575 if (previousNewFiber === null) {
15576 resultingFirstChild = _newFiber4;
15577 } else {
15578 previousNewFiber.sibling = _newFiber4;
15579 }
15580
15581 previousNewFiber = _newFiber4;
15582 }
15583 }
15584
15585 if (shouldTrackSideEffects) {
15586 // Any existing children that weren't consumed above were deleted. We need
15587 // to add them to the deletion list.
15588 existingChildren.forEach(function (child) {
15589 return deleteChild(returnFiber, child);
15590 });
15591 }
15592
15593 return resultingFirstChild;
15594 }
15595
15596 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
15597 // There's no need to check for keys on text nodes since we don't have a
15598 // way to define them.
15599 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
15600 // We already have an existing node so let's just update it and delete
15601 // the rest.
15602 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
15603 var existing = useFiber(currentFirstChild, textContent, expirationTime);
15604 existing.return = returnFiber;
15605 return existing;
15606 } // The existing first child is not a text node so we need to create one
15607 // and delete the existing ones.
15608
15609
15610 deleteRemainingChildren(returnFiber, currentFirstChild);
15611 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
15612 created.return = returnFiber;
15613 return created;
15614 }
15615
15616 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
15617 var key = element.key;
15618 var child = currentFirstChild;
15619
15620 while (child !== null) {
15621 // TODO: If key === null and child.key === null, then this only applies to
15622 // the first item in the list.
15623 if (child.key === key) {
15624 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:
15625 isCompatibleFamilyForHotReloading(child, element))) {
15626 deleteRemainingChildren(returnFiber, child.sibling);
15627 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
15628 existing.ref = coerceRef(returnFiber, child, element);
15629 existing.return = returnFiber;
15630
15631 {
15632 existing._debugSource = element._source;
15633 existing._debugOwner = element._owner;
15634 }
15635
15636 return existing;
15637 } else {
15638 deleteRemainingChildren(returnFiber, child);
15639 break;
15640 }
15641 } else {
15642 deleteChild(returnFiber, child);
15643 }
15644
15645 child = child.sibling;
15646 }
15647
15648 if (element.type === REACT_FRAGMENT_TYPE) {
15649 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
15650 created.return = returnFiber;
15651 return created;
15652 } else {
15653 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
15654
15655 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
15656 _created4.return = returnFiber;
15657 return _created4;
15658 }
15659 }
15660
15661 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
15662 var key = portal.key;
15663 var child = currentFirstChild;
15664
15665 while (child !== null) {
15666 // TODO: If key === null and child.key === null, then this only applies to
15667 // the first item in the list.
15668 if (child.key === key) {
15669 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
15670 deleteRemainingChildren(returnFiber, child.sibling);
15671 var existing = useFiber(child, portal.children || [], expirationTime);
15672 existing.return = returnFiber;
15673 return existing;
15674 } else {
15675 deleteRemainingChildren(returnFiber, child);
15676 break;
15677 }
15678 } else {
15679 deleteChild(returnFiber, child);
15680 }
15681
15682 child = child.sibling;
15683 }
15684
15685 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
15686 created.return = returnFiber;
15687 return created;
15688 } // This API will tag the children with the side-effect of the reconciliation
15689 // itself. They will be added to the side-effect list as we pass through the
15690 // children and the parent.
15691
15692
15693 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
15694 // This function is not recursive.
15695 // If the top level item is an array, we treat it as a set of children,
15696 // not as a fragment. Nested arrays on the other hand will be treated as
15697 // fragment nodes. Recursion happens at the normal flow.
15698 // Handle top level unkeyed fragments as if they were arrays.
15699 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
15700 // We treat the ambiguous cases above the same.
15701 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
15702
15703 if (isUnkeyedTopLevelFragment) {
15704 newChild = newChild.props.children;
15705 } // Handle object types
15706
15707
15708 var isObject = typeof newChild === 'object' && newChild !== null;
15709
15710 if (isObject) {
15711 switch (newChild.$$typeof) {
15712 case REACT_ELEMENT_TYPE:
15713 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
15714
15715 case REACT_PORTAL_TYPE:
15716 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
15717 }
15718 }
15719
15720 if (typeof newChild === 'string' || typeof newChild === 'number') {
15721 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
15722 }
15723
15724 if (isArray(newChild)) {
15725 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
15726 }
15727
15728 if (getIteratorFn(newChild)) {
15729 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
15730 }
15731
15732 if (isObject) {
15733 throwOnInvalidObjectType(returnFiber, newChild);
15734 }
15735
15736 {
15737 if (typeof newChild === 'function') {
15738 warnOnFunctionType();
15739 }
15740 }
15741
15742 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
15743 // If the new child is undefined, and the return fiber is a composite
15744 // component, throw an error. If Fiber return types are disabled,
15745 // we already threw above.
15746 switch (returnFiber.tag) {
15747 case ClassComponent:
15748 {
15749 {
15750 var instance = returnFiber.stateNode;
15751
15752 if (instance.render._isMockFunction) {
15753 // We allow auto-mocks to proceed as if they're returning null.
15754 break;
15755 }
15756 }
15757 }
15758 // Intentionally fall through to the next case, which handles both
15759 // functions and classes
15760 // eslint-disable-next-lined no-fallthrough
15761
15762 case FunctionComponent:
15763 {
15764 var Component = returnFiber.type;
15765
15766 {
15767 {
15768 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.");
15769 }
15770 }
15771 }
15772 }
15773 } // Remaining cases are all treated as empty.
15774
15775
15776 return deleteRemainingChildren(returnFiber, currentFirstChild);
15777 }
15778
15779 return reconcileChildFibers;
15780}
15781
15782var reconcileChildFibers = ChildReconciler(true);
15783var mountChildFibers = ChildReconciler(false);
15784function cloneChildFibers(current$$1, workInProgress) {
15785 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
15786 {
15787 throw Error("Resuming work not yet implemented.");
15788 }
15789 }
15790
15791 if (workInProgress.child === null) {
15792 return;
15793 }
15794
15795 var currentChild = workInProgress.child;
15796 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15797 workInProgress.child = newChild;
15798 newChild.return = workInProgress;
15799
15800 while (currentChild.sibling !== null) {
15801 currentChild = currentChild.sibling;
15802 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
15803 newChild.return = workInProgress;
15804 }
15805
15806 newChild.sibling = null;
15807} // Reset a workInProgress child set to prepare it for a second pass.
15808
15809function resetChildFibers(workInProgress, renderExpirationTime) {
15810 var child = workInProgress.child;
15811
15812 while (child !== null) {
15813 resetWorkInProgress(child, renderExpirationTime);
15814 child = child.sibling;
15815 }
15816}
15817
15818var NO_CONTEXT = {};
15819var contextStackCursor$1 = createCursor(NO_CONTEXT);
15820var contextFiberStackCursor = createCursor(NO_CONTEXT);
15821var rootInstanceStackCursor = createCursor(NO_CONTEXT);
15822
15823function requiredContext(c) {
15824 if (!(c !== NO_CONTEXT)) {
15825 {
15826 throw Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
15827 }
15828 }
15829
15830 return c;
15831}
15832
15833function getRootHostContainer() {
15834 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15835 return rootInstance;
15836}
15837
15838function pushHostContainer(fiber, nextRootInstance) {
15839 // Push current root instance onto the stack;
15840 // This allows us to reset root when portals are popped.
15841 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
15842 // This enables us to pop only Fibers that provide unique contexts.
15843
15844 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
15845 // However, we can't just call getRootHostContext() and push it because
15846 // we'd have a different number of entries on the stack depending on
15847 // whether getRootHostContext() throws somewhere in renderer code or not.
15848 // So we push an empty value first. This lets us safely unwind on errors.
15849
15850 push(contextStackCursor$1, NO_CONTEXT, fiber);
15851 var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
15852
15853 pop(contextStackCursor$1, fiber);
15854 push(contextStackCursor$1, nextRootContext, fiber);
15855}
15856
15857function popHostContainer(fiber) {
15858 pop(contextStackCursor$1, fiber);
15859 pop(contextFiberStackCursor, fiber);
15860 pop(rootInstanceStackCursor, fiber);
15861}
15862
15863function getHostContext() {
15864 var context = requiredContext(contextStackCursor$1.current);
15865 return context;
15866}
15867
15868function pushHostContext(fiber) {
15869 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15870 var context = requiredContext(contextStackCursor$1.current);
15871 var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique.
15872
15873 if (context === nextContext) {
15874 return;
15875 } // Track the context and the Fiber that provided it.
15876 // This enables us to pop only Fibers that provide unique contexts.
15877
15878
15879 push(contextFiberStackCursor, fiber, fiber);
15880 push(contextStackCursor$1, nextContext, fiber);
15881}
15882
15883function popHostContext(fiber) {
15884 // Do not pop unless this Fiber provided the current context.
15885 // pushHostContext() only pushes Fibers that provide unique contexts.
15886 if (contextFiberStackCursor.current !== fiber) {
15887 return;
15888 }
15889
15890 pop(contextStackCursor$1, fiber);
15891 pop(contextFiberStackCursor, fiber);
15892}
15893
15894var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
15895// inherited deeply down the subtree. The upper bits only affect
15896// this immediate suspense boundary and gets reset each new
15897// boundary or suspense list.
15898
15899var SubtreeSuspenseContextMask = 1; // Subtree Flags:
15900// InvisibleParentSuspenseContext indicates that one of our parent Suspense
15901// boundaries is not currently showing visible main content.
15902// Either because it is already showing a fallback or is not mounted at all.
15903// We can use this to determine if it is desirable to trigger a fallback at
15904// the parent. If not, then we might need to trigger undesirable boundaries
15905// and/or suspend the commit to avoid hiding the parent content.
15906
15907var InvisibleParentSuspenseContext = 1; // Shallow Flags:
15908// ForceSuspenseFallback can be used by SuspenseList to force newly added
15909// items into their fallback state during one of the render passes.
15910
15911var ForceSuspenseFallback = 2;
15912var suspenseStackCursor = createCursor(DefaultSuspenseContext);
15913function hasSuspenseContext(parentContext, flag) {
15914 return (parentContext & flag) !== 0;
15915}
15916function setDefaultShallowSuspenseContext(parentContext) {
15917 return parentContext & SubtreeSuspenseContextMask;
15918}
15919function setShallowSuspenseContext(parentContext, shallowContext) {
15920 return parentContext & SubtreeSuspenseContextMask | shallowContext;
15921}
15922function addSubtreeSuspenseContext(parentContext, subtreeContext) {
15923 return parentContext | subtreeContext;
15924}
15925function pushSuspenseContext(fiber, newContext) {
15926 push(suspenseStackCursor, newContext, fiber);
15927}
15928function popSuspenseContext(fiber) {
15929 pop(suspenseStackCursor, fiber);
15930}
15931
15932function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
15933 // If it was the primary children that just suspended, capture and render the
15934 // fallback. Otherwise, don't capture and bubble to the next boundary.
15935 var nextState = workInProgress.memoizedState;
15936
15937 if (nextState !== null) {
15938 if (nextState.dehydrated !== null) {
15939 // A dehydrated boundary always captures.
15940 return true;
15941 }
15942
15943 return false;
15944 }
15945
15946 var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
15947
15948 if (props.fallback === undefined) {
15949 return false;
15950 } // Regular boundaries always capture.
15951
15952
15953 if (props.unstable_avoidThisFallback !== true) {
15954 return true;
15955 } // If it's a boundary we should avoid, then we prefer to bubble up to the
15956 // parent boundary if it is currently invisible.
15957
15958
15959 if (hasInvisibleParent) {
15960 return false;
15961 } // If the parent is not able to handle it, we must handle it.
15962
15963
15964 return true;
15965}
15966function findFirstSuspended(row) {
15967 var node = row;
15968
15969 while (node !== null) {
15970 if (node.tag === SuspenseComponent) {
15971 var state = node.memoizedState;
15972
15973 if (state !== null) {
15974 var dehydrated = state.dehydrated;
15975
15976 if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
15977 return node;
15978 }
15979 }
15980 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
15981 // keep track of whether it suspended or not.
15982 node.memoizedProps.revealOrder !== undefined) {
15983 var didSuspend = (node.effectTag & DidCapture) !== NoEffect;
15984
15985 if (didSuspend) {
15986 return node;
15987 }
15988 } else if (node.child !== null) {
15989 node.child.return = node;
15990 node = node.child;
15991 continue;
15992 }
15993
15994 if (node === row) {
15995 return null;
15996 }
15997
15998 while (node.sibling === null) {
15999 if (node.return === null || node.return === row) {
16000 return null;
16001 }
16002
16003 node = node.return;
16004 }
16005
16006 node.sibling.return = node.return;
16007 node = node.sibling;
16008 }
16009
16010 return null;
16011}
16012
16013var emptyObject = {};
16014var isArray$2 = Array.isArray;
16015function createResponderInstance(responder, responderProps, responderState, fiber) {
16016 return {
16017 fiber: fiber,
16018 props: responderProps,
16019 responder: responder,
16020 rootEventTypes: null,
16021 state: responderState
16022 };
16023}
16024
16025function mountEventResponder$1(responder, responderProps, fiber, respondersMap, rootContainerInstance) {
16026 var responderState = emptyObject;
16027 var getInitialState = responder.getInitialState;
16028
16029 if (getInitialState !== null) {
16030 responderState = getInitialState(responderProps);
16031 }
16032
16033 var responderInstance = createResponderInstance(responder, responderProps, responderState, fiber);
16034
16035 if (!rootContainerInstance) {
16036 var node = fiber;
16037
16038 while (node !== null) {
16039 var tag = node.tag;
16040
16041 if (tag === HostComponent) {
16042 rootContainerInstance = node.stateNode;
16043 break;
16044 } else if (tag === HostRoot) {
16045 rootContainerInstance = node.stateNode.containerInfo;
16046 break;
16047 }
16048
16049 node = node.return;
16050 }
16051 }
16052
16053 mountResponderInstance(responder, responderInstance, responderProps, responderState, rootContainerInstance);
16054 respondersMap.set(responder, responderInstance);
16055}
16056
16057function updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance) {
16058 var responder;
16059 var props;
16060
16061 if (listener) {
16062 responder = listener.responder;
16063 props = listener.props;
16064 }
16065
16066 if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) {
16067 {
16068 throw Error("An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder().");
16069 }
16070 }
16071
16072 var listenerProps = props;
16073
16074 if (visistedResponders.has(responder)) {
16075 // show warning
16076 {
16077 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);
16078 }
16079
16080 return;
16081 }
16082
16083 visistedResponders.add(responder);
16084 var responderInstance = respondersMap.get(responder);
16085
16086 if (responderInstance === undefined) {
16087 // Mount (happens in either complete or commit phase)
16088 mountEventResponder$1(responder, listenerProps, fiber, respondersMap, rootContainerInstance);
16089 } else {
16090 // Update (happens during commit phase only)
16091 responderInstance.props = listenerProps;
16092 responderInstance.fiber = fiber;
16093 }
16094}
16095
16096function updateEventListeners(listeners, fiber, rootContainerInstance) {
16097 var visistedResponders = new Set();
16098 var dependencies = fiber.dependencies;
16099
16100 if (listeners != null) {
16101 if (dependencies === null) {
16102 dependencies = fiber.dependencies = {
16103 expirationTime: NoWork,
16104 firstContext: null,
16105 responders: new Map()
16106 };
16107 }
16108
16109 var respondersMap = dependencies.responders;
16110
16111 if (respondersMap === null) {
16112 respondersMap = new Map();
16113 }
16114
16115 if (isArray$2(listeners)) {
16116 for (var i = 0, length = listeners.length; i < length; i++) {
16117 var listener = listeners[i];
16118 updateEventListener(listener, fiber, visistedResponders, respondersMap, rootContainerInstance);
16119 }
16120 } else {
16121 updateEventListener(listeners, fiber, visistedResponders, respondersMap, rootContainerInstance);
16122 }
16123 }
16124
16125 if (dependencies !== null) {
16126 var _respondersMap = dependencies.responders;
16127
16128 if (_respondersMap !== null) {
16129 // Unmount
16130 var mountedResponders = Array.from(_respondersMap.keys());
16131
16132 for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) {
16133 var mountedResponder = mountedResponders[_i];
16134
16135 if (!visistedResponders.has(mountedResponder)) {
16136 var responderInstance = _respondersMap.get(mountedResponder);
16137
16138 unmountResponderInstance(responderInstance);
16139
16140 _respondersMap.delete(mountedResponder);
16141 }
16142 }
16143 }
16144 }
16145}
16146function createResponderListener(responder, props) {
16147 var eventResponderListener = {
16148 responder: responder,
16149 props: props
16150 };
16151
16152 {
16153 Object.freeze(eventResponderListener);
16154 }
16155
16156 return eventResponderListener;
16157}
16158
16159var NoEffect$1 =
16160/* */
161610;
16162var UnmountSnapshot =
16163/* */
161642;
16165var UnmountMutation =
16166/* */
161674;
16168var MountMutation =
16169/* */
161708;
16171var UnmountLayout =
16172/* */
1617316;
16174var MountLayout =
16175/* */
1617632;
16177var MountPassive =
16178/* */
1617964;
16180var UnmountPassive =
16181/* */
16182128;
16183
16184var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
16185var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
16186var didWarnAboutMismatchedHooksForComponent;
16187
16188{
16189 didWarnAboutMismatchedHooksForComponent = new Set();
16190}
16191
16192// These are set right before calling the component.
16193var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
16194// the work-in-progress hook.
16195
16196var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
16197// current hook list is the list that belongs to the current fiber. The
16198// work-in-progress hook list is a new list that will be added to the
16199// work-in-progress fiber.
16200
16201var currentHook = null;
16202var nextCurrentHook = null;
16203var firstWorkInProgressHook = null;
16204var workInProgressHook = null;
16205var nextWorkInProgressHook = null;
16206var remainingExpirationTime = NoWork;
16207var componentUpdateQueue = null;
16208var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the
16209// end of the current pass. We can't store these updates on the normal queue,
16210// because if the work is aborted, they should be discarded. Because this is
16211// a relatively rare case, we also don't want to add an additional field to
16212// either the hook or queue object types. So we store them in a lazily create
16213// map of queue -> render-phase updates, which are discarded once the component
16214// completes without re-rendering.
16215// Whether an update was scheduled during the currently executing render pass.
16216
16217var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates
16218
16219var renderPhaseUpdates = null; // Counter to prevent infinite loops.
16220
16221var numberOfReRenders = 0;
16222var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
16223
16224var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
16225// The list stores the order of hooks used during the initial render (mount).
16226// Subsequent renders (updates) reference this list.
16227
16228var hookTypesDev = null;
16229var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
16230// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
16231// When true, such Hooks will always be "remounted". Only used during hot reload.
16232
16233var ignorePreviousDependencies = false;
16234
16235function mountHookTypesDev() {
16236 {
16237 var hookName = currentHookNameInDev;
16238
16239 if (hookTypesDev === null) {
16240 hookTypesDev = [hookName];
16241 } else {
16242 hookTypesDev.push(hookName);
16243 }
16244 }
16245}
16246
16247function updateHookTypesDev() {
16248 {
16249 var hookName = currentHookNameInDev;
16250
16251 if (hookTypesDev !== null) {
16252 hookTypesUpdateIndexDev++;
16253
16254 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
16255 warnOnHookMismatchInDev(hookName);
16256 }
16257 }
16258 }
16259}
16260
16261function checkDepsAreArrayDev(deps) {
16262 {
16263 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
16264 // Verify deps, but only on mount to avoid extra checks.
16265 // It's unlikely their type would change as usually you define them inline.
16266 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);
16267 }
16268 }
16269}
16270
16271function warnOnHookMismatchInDev(currentHookName) {
16272 {
16273 var componentName = getComponentName(currentlyRenderingFiber$1.type);
16274
16275 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
16276 didWarnAboutMismatchedHooksForComponent.add(componentName);
16277
16278 if (hookTypesDev !== null) {
16279 var table = '';
16280 var secondColumnStart = 30;
16281
16282 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
16283 var oldHookName = hookTypesDev[i];
16284 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
16285 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
16286 // lol @ IE not supporting String#repeat
16287
16288 while (row.length < secondColumnStart) {
16289 row += ' ';
16290 }
16291
16292 row += newHookName + '\n';
16293 table += row;
16294 }
16295
16296 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);
16297 }
16298 }
16299 }
16300}
16301
16302function throwInvalidHookError() {
16303 {
16304 {
16305 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.");
16306 }
16307 }
16308}
16309
16310function areHookInputsEqual(nextDeps, prevDeps) {
16311 {
16312 if (ignorePreviousDependencies) {
16313 // Only true when this component is being hot reloaded.
16314 return false;
16315 }
16316 }
16317
16318 if (prevDeps === null) {
16319 {
16320 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);
16321 }
16322
16323 return false;
16324 }
16325
16326 {
16327 // Don't bother comparing lengths in prod because these arrays should be
16328 // passed inline.
16329 if (nextDeps.length !== prevDeps.length) {
16330 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(', ') + "]");
16331 }
16332 }
16333
16334 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
16335 if (is$1(nextDeps[i], prevDeps[i])) {
16336 continue;
16337 }
16338
16339 return false;
16340 }
16341
16342 return true;
16343}
16344
16345function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
16346 renderExpirationTime$1 = nextRenderExpirationTime;
16347 currentlyRenderingFiber$1 = workInProgress;
16348 nextCurrentHook = current !== null ? current.memoizedState : null;
16349
16350 {
16351 hookTypesDev = current !== null ? current._debugHookTypes : null;
16352 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
16353
16354 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
16355 } // The following should have already been reset
16356 // currentHook = null;
16357 // workInProgressHook = null;
16358 // remainingExpirationTime = NoWork;
16359 // componentUpdateQueue = null;
16360 // didScheduleRenderPhaseUpdate = false;
16361 // renderPhaseUpdates = null;
16362 // numberOfReRenders = 0;
16363 // sideEffectTag = 0;
16364 // TODO Warn if no hooks are used at all during mount, then some are used during update.
16365 // Currently we will identify the update render as a mount because nextCurrentHook === null.
16366 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
16367 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
16368 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
16369 // so nextCurrentHook would be null during updates and mounts.
16370
16371
16372 {
16373 if (nextCurrentHook !== null) {
16374 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16375 } else if (hookTypesDev !== null) {
16376 // This dispatcher handles an edge case where a component is updating,
16377 // but no stateful hooks have been used.
16378 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
16379 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
16380 // This dispatcher does that.
16381 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
16382 } else {
16383 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
16384 }
16385 }
16386
16387 var children = Component(props, refOrContext);
16388
16389 if (didScheduleRenderPhaseUpdate) {
16390 do {
16391 didScheduleRenderPhaseUpdate = false;
16392 numberOfReRenders += 1;
16393
16394 {
16395 // Even when hot reloading, allow dependencies to stabilize
16396 // after first render to prevent infinite render phase updates.
16397 ignorePreviousDependencies = false;
16398 } // Start over from the beginning of the list
16399
16400
16401 nextCurrentHook = current !== null ? current.memoizedState : null;
16402 nextWorkInProgressHook = firstWorkInProgressHook;
16403 currentHook = null;
16404 workInProgressHook = null;
16405 componentUpdateQueue = null;
16406
16407 {
16408 // Also validate hook order for cascading updates.
16409 hookTypesUpdateIndexDev = -1;
16410 }
16411
16412 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
16413 children = Component(props, refOrContext);
16414 } while (didScheduleRenderPhaseUpdate);
16415
16416 renderPhaseUpdates = null;
16417 numberOfReRenders = 0;
16418 } // We can assume the previous dispatcher is always this one, since we set it
16419 // at the beginning of the render phase and there's no re-entrancy.
16420
16421
16422 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
16423 var renderedWork = currentlyRenderingFiber$1;
16424 renderedWork.memoizedState = firstWorkInProgressHook;
16425 renderedWork.expirationTime = remainingExpirationTime;
16426 renderedWork.updateQueue = componentUpdateQueue;
16427 renderedWork.effectTag |= sideEffectTag;
16428
16429 {
16430 renderedWork._debugHookTypes = hookTypesDev;
16431 } // This check uses currentHook so that it works the same in DEV and prod bundles.
16432 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
16433
16434
16435 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
16436 renderExpirationTime$1 = NoWork;
16437 currentlyRenderingFiber$1 = null;
16438 currentHook = null;
16439 nextCurrentHook = null;
16440 firstWorkInProgressHook = null;
16441 workInProgressHook = null;
16442 nextWorkInProgressHook = null;
16443
16444 {
16445 currentHookNameInDev = null;
16446 hookTypesDev = null;
16447 hookTypesUpdateIndexDev = -1;
16448 }
16449
16450 remainingExpirationTime = NoWork;
16451 componentUpdateQueue = null;
16452 sideEffectTag = 0; // These were reset above
16453 // didScheduleRenderPhaseUpdate = false;
16454 // renderPhaseUpdates = null;
16455 // numberOfReRenders = 0;
16456
16457 if (!!didRenderTooFewHooks) {
16458 {
16459 throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
16460 }
16461 }
16462
16463 return children;
16464}
16465function bailoutHooks(current, workInProgress, expirationTime) {
16466 workInProgress.updateQueue = current.updateQueue;
16467 workInProgress.effectTag &= ~(Passive | Update);
16468
16469 if (current.expirationTime <= expirationTime) {
16470 current.expirationTime = NoWork;
16471 }
16472}
16473function resetHooks() {
16474 // We can assume the previous dispatcher is always this one, since we set it
16475 // at the beginning of the render phase and there's no re-entrancy.
16476 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws.
16477 // It's also called inside mountIndeterminateComponent if we determine the
16478 // component is a module-style component.
16479
16480 renderExpirationTime$1 = NoWork;
16481 currentlyRenderingFiber$1 = null;
16482 currentHook = null;
16483 nextCurrentHook = null;
16484 firstWorkInProgressHook = null;
16485 workInProgressHook = null;
16486 nextWorkInProgressHook = null;
16487
16488 {
16489 hookTypesDev = null;
16490 hookTypesUpdateIndexDev = -1;
16491 currentHookNameInDev = null;
16492 }
16493
16494 remainingExpirationTime = NoWork;
16495 componentUpdateQueue = null;
16496 sideEffectTag = 0;
16497 didScheduleRenderPhaseUpdate = false;
16498 renderPhaseUpdates = null;
16499 numberOfReRenders = 0;
16500}
16501
16502function mountWorkInProgressHook() {
16503 var hook = {
16504 memoizedState: null,
16505 baseState: null,
16506 queue: null,
16507 baseUpdate: null,
16508 next: null
16509 };
16510
16511 if (workInProgressHook === null) {
16512 // This is the first hook in the list
16513 firstWorkInProgressHook = workInProgressHook = hook;
16514 } else {
16515 // Append to the end of the list
16516 workInProgressHook = workInProgressHook.next = hook;
16517 }
16518
16519 return workInProgressHook;
16520}
16521
16522function updateWorkInProgressHook() {
16523 // This function is used both for updates and for re-renders triggered by a
16524 // render phase update. It assumes there is either a current hook we can
16525 // clone, or a work-in-progress hook from a previous render pass that we can
16526 // use as a base. When we reach the end of the base list, we must switch to
16527 // the dispatcher used for mounts.
16528 if (nextWorkInProgressHook !== null) {
16529 // There's already a work-in-progress. Reuse it.
16530 workInProgressHook = nextWorkInProgressHook;
16531 nextWorkInProgressHook = workInProgressHook.next;
16532 currentHook = nextCurrentHook;
16533 nextCurrentHook = currentHook !== null ? currentHook.next : null;
16534 } else {
16535 // Clone from the current hook.
16536 if (!(nextCurrentHook !== null)) {
16537 {
16538 throw Error("Rendered more hooks than during the previous render.");
16539 }
16540 }
16541
16542 currentHook = nextCurrentHook;
16543 var newHook = {
16544 memoizedState: currentHook.memoizedState,
16545 baseState: currentHook.baseState,
16546 queue: currentHook.queue,
16547 baseUpdate: currentHook.baseUpdate,
16548 next: null
16549 };
16550
16551 if (workInProgressHook === null) {
16552 // This is the first hook in the list.
16553 workInProgressHook = firstWorkInProgressHook = newHook;
16554 } else {
16555 // Append to the end of the list.
16556 workInProgressHook = workInProgressHook.next = newHook;
16557 }
16558
16559 nextCurrentHook = currentHook.next;
16560 }
16561
16562 return workInProgressHook;
16563}
16564
16565function createFunctionComponentUpdateQueue() {
16566 return {
16567 lastEffect: null
16568 };
16569}
16570
16571function basicStateReducer(state, action) {
16572 return typeof action === 'function' ? action(state) : action;
16573}
16574
16575function mountReducer(reducer, initialArg, init) {
16576 var hook = mountWorkInProgressHook();
16577 var initialState;
16578
16579 if (init !== undefined) {
16580 initialState = init(initialArg);
16581 } else {
16582 initialState = initialArg;
16583 }
16584
16585 hook.memoizedState = hook.baseState = initialState;
16586 var queue = hook.queue = {
16587 last: null,
16588 dispatch: null,
16589 lastRenderedReducer: reducer,
16590 lastRenderedState: initialState
16591 };
16592 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16593 currentlyRenderingFiber$1, queue);
16594 return [hook.memoizedState, dispatch];
16595}
16596
16597function updateReducer(reducer, initialArg, init) {
16598 var hook = updateWorkInProgressHook();
16599 var queue = hook.queue;
16600
16601 if (!(queue !== null)) {
16602 {
16603 throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
16604 }
16605 }
16606
16607 queue.lastRenderedReducer = reducer;
16608
16609 if (numberOfReRenders > 0) {
16610 // This is a re-render. Apply the new render phase updates to the previous
16611 // work-in-progress hook.
16612 var _dispatch = queue.dispatch;
16613
16614 if (renderPhaseUpdates !== null) {
16615 // Render phase updates are stored in a map of queue -> linked list
16616 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
16617
16618 if (firstRenderPhaseUpdate !== undefined) {
16619 renderPhaseUpdates.delete(queue);
16620 var newState = hook.memoizedState;
16621 var update = firstRenderPhaseUpdate;
16622
16623 do {
16624 // Process this render phase update. We don't have to check the
16625 // priority because it will always be the same as the current
16626 // render's.
16627 var action = update.action;
16628 newState = reducer(newState, action);
16629 update = update.next;
16630 } while (update !== null); // Mark that the fiber performed work, but only if the new state is
16631 // different from the current state.
16632
16633
16634 if (!is$1(newState, hook.memoizedState)) {
16635 markWorkInProgressReceivedUpdate();
16636 }
16637
16638 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
16639 // the base state unless the queue is empty.
16640 // TODO: Not sure if this is the desired semantics, but it's what we
16641 // do for gDSFP. I can't remember why.
16642
16643 if (hook.baseUpdate === queue.last) {
16644 hook.baseState = newState;
16645 }
16646
16647 queue.lastRenderedState = newState;
16648 return [newState, _dispatch];
16649 }
16650 }
16651
16652 return [hook.memoizedState, _dispatch];
16653 } // The last update in the entire queue
16654
16655
16656 var last = queue.last; // The last update that is part of the base state.
16657
16658 var baseUpdate = hook.baseUpdate;
16659 var baseState = hook.baseState; // Find the first unprocessed update.
16660
16661 var first;
16662
16663 if (baseUpdate !== null) {
16664 if (last !== null) {
16665 // For the first update, the queue is a circular linked list where
16666 // `queue.last.next = queue.first`. Once the first update commits, and
16667 // the `baseUpdate` is no longer empty, we can unravel the list.
16668 last.next = null;
16669 }
16670
16671 first = baseUpdate.next;
16672 } else {
16673 first = last !== null ? last.next : null;
16674 }
16675
16676 if (first !== null) {
16677 var _newState = baseState;
16678 var newBaseState = null;
16679 var newBaseUpdate = null;
16680 var prevUpdate = baseUpdate;
16681 var _update = first;
16682 var didSkip = false;
16683
16684 do {
16685 var updateExpirationTime = _update.expirationTime;
16686
16687 if (updateExpirationTime < renderExpirationTime$1) {
16688 // Priority is insufficient. Skip this update. If this is the first
16689 // skipped update, the previous update/state is the new base
16690 // update/state.
16691 if (!didSkip) {
16692 didSkip = true;
16693 newBaseUpdate = prevUpdate;
16694 newBaseState = _newState;
16695 } // Update the remaining priority in the queue.
16696
16697
16698 if (updateExpirationTime > remainingExpirationTime) {
16699 remainingExpirationTime = updateExpirationTime;
16700 markUnprocessedUpdateTime(remainingExpirationTime);
16701 }
16702 } else {
16703 // This update does have sufficient priority.
16704 // Mark the event time of this update as relevant to this render pass.
16705 // TODO: This should ideally use the true event time of this update rather than
16706 // its priority which is a derived and not reverseable value.
16707 // TODO: We should skip this update if it was already committed but currently
16708 // we have no way of detecting the difference between a committed and suspended
16709 // update here.
16710 markRenderEventTimeAndConfig(updateExpirationTime, _update.suspenseConfig); // Process this update.
16711
16712 if (_update.eagerReducer === reducer) {
16713 // If this update was processed eagerly, and its reducer matches the
16714 // current reducer, we can use the eagerly computed state.
16715 _newState = _update.eagerState;
16716 } else {
16717 var _action = _update.action;
16718 _newState = reducer(_newState, _action);
16719 }
16720 }
16721
16722 prevUpdate = _update;
16723 _update = _update.next;
16724 } while (_update !== null && _update !== first);
16725
16726 if (!didSkip) {
16727 newBaseUpdate = prevUpdate;
16728 newBaseState = _newState;
16729 } // Mark that the fiber performed work, but only if the new state is
16730 // different from the current state.
16731
16732
16733 if (!is$1(_newState, hook.memoizedState)) {
16734 markWorkInProgressReceivedUpdate();
16735 }
16736
16737 hook.memoizedState = _newState;
16738 hook.baseUpdate = newBaseUpdate;
16739 hook.baseState = newBaseState;
16740 queue.lastRenderedState = _newState;
16741 }
16742
16743 var dispatch = queue.dispatch;
16744 return [hook.memoizedState, dispatch];
16745}
16746
16747function mountState(initialState) {
16748 var hook = mountWorkInProgressHook();
16749
16750 if (typeof initialState === 'function') {
16751 initialState = initialState();
16752 }
16753
16754 hook.memoizedState = hook.baseState = initialState;
16755 var queue = hook.queue = {
16756 last: null,
16757 dispatch: null,
16758 lastRenderedReducer: basicStateReducer,
16759 lastRenderedState: initialState
16760 };
16761 var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do.
16762 currentlyRenderingFiber$1, queue);
16763 return [hook.memoizedState, dispatch];
16764}
16765
16766function updateState(initialState) {
16767 return updateReducer(basicStateReducer, initialState);
16768}
16769
16770function pushEffect(tag, create, destroy, deps) {
16771 var effect = {
16772 tag: tag,
16773 create: create,
16774 destroy: destroy,
16775 deps: deps,
16776 // Circular
16777 next: null
16778 };
16779
16780 if (componentUpdateQueue === null) {
16781 componentUpdateQueue = createFunctionComponentUpdateQueue();
16782 componentUpdateQueue.lastEffect = effect.next = effect;
16783 } else {
16784 var lastEffect = componentUpdateQueue.lastEffect;
16785
16786 if (lastEffect === null) {
16787 componentUpdateQueue.lastEffect = effect.next = effect;
16788 } else {
16789 var firstEffect = lastEffect.next;
16790 lastEffect.next = effect;
16791 effect.next = firstEffect;
16792 componentUpdateQueue.lastEffect = effect;
16793 }
16794 }
16795
16796 return effect;
16797}
16798
16799function mountRef(initialValue) {
16800 var hook = mountWorkInProgressHook();
16801 var ref = {
16802 current: initialValue
16803 };
16804
16805 {
16806 Object.seal(ref);
16807 }
16808
16809 hook.memoizedState = ref;
16810 return ref;
16811}
16812
16813function updateRef(initialValue) {
16814 var hook = updateWorkInProgressHook();
16815 return hook.memoizedState;
16816}
16817
16818function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16819 var hook = mountWorkInProgressHook();
16820 var nextDeps = deps === undefined ? null : deps;
16821 sideEffectTag |= fiberEffectTag;
16822 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
16823}
16824
16825function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
16826 var hook = updateWorkInProgressHook();
16827 var nextDeps = deps === undefined ? null : deps;
16828 var destroy = undefined;
16829
16830 if (currentHook !== null) {
16831 var prevEffect = currentHook.memoizedState;
16832 destroy = prevEffect.destroy;
16833
16834 if (nextDeps !== null) {
16835 var prevDeps = prevEffect.deps;
16836
16837 if (areHookInputsEqual(nextDeps, prevDeps)) {
16838 pushEffect(NoEffect$1, create, destroy, nextDeps);
16839 return;
16840 }
16841 }
16842 }
16843
16844 sideEffectTag |= fiberEffectTag;
16845 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
16846}
16847
16848function mountEffect(create, deps) {
16849 {
16850 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16851 if ('undefined' !== typeof jest) {
16852 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16853 }
16854 }
16855
16856 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16857}
16858
16859function updateEffect(create, deps) {
16860 {
16861 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16862 if ('undefined' !== typeof jest) {
16863 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
16864 }
16865 }
16866
16867 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
16868}
16869
16870function mountLayoutEffect(create, deps) {
16871 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16872}
16873
16874function updateLayoutEffect(create, deps) {
16875 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
16876}
16877
16878function imperativeHandleEffect(create, ref) {
16879 if (typeof ref === 'function') {
16880 var refCallback = ref;
16881
16882 var _inst = create();
16883
16884 refCallback(_inst);
16885 return function () {
16886 refCallback(null);
16887 };
16888 } else if (ref !== null && ref !== undefined) {
16889 var refObject = ref;
16890
16891 {
16892 !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;
16893 }
16894
16895 var _inst2 = create();
16896
16897 refObject.current = _inst2;
16898 return function () {
16899 refObject.current = null;
16900 };
16901 }
16902}
16903
16904function mountImperativeHandle(ref, create, deps) {
16905 {
16906 !(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;
16907 } // TODO: If deps are provided, should we skip comparing the ref itself?
16908
16909
16910 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16911 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16912}
16913
16914function updateImperativeHandle(ref, create, deps) {
16915 {
16916 !(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;
16917 } // TODO: If deps are provided, should we skip comparing the ref itself?
16918
16919
16920 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16921 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16922}
16923
16924function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
16925 // The react-debug-hooks package injects its own implementation
16926 // so that e.g. DevTools can display custom hook values.
16927}
16928
16929var updateDebugValue = mountDebugValue;
16930
16931function mountCallback(callback, deps) {
16932 var hook = mountWorkInProgressHook();
16933 var nextDeps = deps === undefined ? null : deps;
16934 hook.memoizedState = [callback, nextDeps];
16935 return callback;
16936}
16937
16938function updateCallback(callback, deps) {
16939 var hook = updateWorkInProgressHook();
16940 var nextDeps = deps === undefined ? null : deps;
16941 var prevState = hook.memoizedState;
16942
16943 if (prevState !== null) {
16944 if (nextDeps !== null) {
16945 var prevDeps = prevState[1];
16946
16947 if (areHookInputsEqual(nextDeps, prevDeps)) {
16948 return prevState[0];
16949 }
16950 }
16951 }
16952
16953 hook.memoizedState = [callback, nextDeps];
16954 return callback;
16955}
16956
16957function mountMemo(nextCreate, deps) {
16958 var hook = mountWorkInProgressHook();
16959 var nextDeps = deps === undefined ? null : deps;
16960 var nextValue = nextCreate();
16961 hook.memoizedState = [nextValue, nextDeps];
16962 return nextValue;
16963}
16964
16965function updateMemo(nextCreate, deps) {
16966 var hook = updateWorkInProgressHook();
16967 var nextDeps = deps === undefined ? null : deps;
16968 var prevState = hook.memoizedState;
16969
16970 if (prevState !== null) {
16971 // Assume these are defined. If they're not, areHookInputsEqual will warn.
16972 if (nextDeps !== null) {
16973 var prevDeps = prevState[1];
16974
16975 if (areHookInputsEqual(nextDeps, prevDeps)) {
16976 return prevState[0];
16977 }
16978 }
16979 }
16980
16981 var nextValue = nextCreate();
16982 hook.memoizedState = [nextValue, nextDeps];
16983 return nextValue;
16984}
16985
16986function mountDeferredValue(value, config) {
16987 var _mountState = mountState(value),
16988 prevValue = _mountState[0],
16989 setValue = _mountState[1];
16990
16991 mountEffect(function () {
16992 unstable_next(function () {
16993 var previousConfig = ReactCurrentBatchConfig$1.suspense;
16994 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
16995
16996 try {
16997 setValue(value);
16998 } finally {
16999 ReactCurrentBatchConfig$1.suspense = previousConfig;
17000 }
17001 });
17002 }, [value, config]);
17003 return prevValue;
17004}
17005
17006function updateDeferredValue(value, config) {
17007 var _updateState = updateState(value),
17008 prevValue = _updateState[0],
17009 setValue = _updateState[1];
17010
17011 updateEffect(function () {
17012 unstable_next(function () {
17013 var previousConfig = ReactCurrentBatchConfig$1.suspense;
17014 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
17015
17016 try {
17017 setValue(value);
17018 } finally {
17019 ReactCurrentBatchConfig$1.suspense = previousConfig;
17020 }
17021 });
17022 }, [value, config]);
17023 return prevValue;
17024}
17025
17026function mountTransition(config) {
17027 var _mountState2 = mountState(false),
17028 isPending = _mountState2[0],
17029 setPending = _mountState2[1];
17030
17031 var startTransition = mountCallback(function (callback) {
17032 setPending(true);
17033 unstable_next(function () {
17034 var previousConfig = ReactCurrentBatchConfig$1.suspense;
17035 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
17036
17037 try {
17038 setPending(false);
17039 callback();
17040 } finally {
17041 ReactCurrentBatchConfig$1.suspense = previousConfig;
17042 }
17043 });
17044 }, [config, isPending]);
17045 return [startTransition, isPending];
17046}
17047
17048function updateTransition(config) {
17049 var _updateState2 = updateState(false),
17050 isPending = _updateState2[0],
17051 setPending = _updateState2[1];
17052
17053 var startTransition = updateCallback(function (callback) {
17054 setPending(true);
17055 unstable_next(function () {
17056 var previousConfig = ReactCurrentBatchConfig$1.suspense;
17057 ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
17058
17059 try {
17060 setPending(false);
17061 callback();
17062 } finally {
17063 ReactCurrentBatchConfig$1.suspense = previousConfig;
17064 }
17065 });
17066 }, [config, isPending]);
17067 return [startTransition, isPending];
17068}
17069
17070function dispatchAction(fiber, queue, action) {
17071 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
17072 {
17073 throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
17074 }
17075 }
17076
17077 {
17078 !(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;
17079 }
17080
17081 var alternate = fiber.alternate;
17082
17083 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
17084 // This is a render phase update. Stash it in a lazily-created map of
17085 // queue -> linked list of updates. After this render pass, we'll restart
17086 // and apply the stashed updates on top of the work-in-progress hook.
17087 didScheduleRenderPhaseUpdate = true;
17088 var update = {
17089 expirationTime: renderExpirationTime$1,
17090 suspenseConfig: null,
17091 action: action,
17092 eagerReducer: null,
17093 eagerState: null,
17094 next: null
17095 };
17096
17097 {
17098 update.priority = getCurrentPriorityLevel();
17099 }
17100
17101 if (renderPhaseUpdates === null) {
17102 renderPhaseUpdates = new Map();
17103 }
17104
17105 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
17106
17107 if (firstRenderPhaseUpdate === undefined) {
17108 renderPhaseUpdates.set(queue, update);
17109 } else {
17110 // Append the update to the end of the list.
17111 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
17112
17113 while (lastRenderPhaseUpdate.next !== null) {
17114 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
17115 }
17116
17117 lastRenderPhaseUpdate.next = update;
17118 }
17119 } else {
17120 var currentTime = requestCurrentTimeForUpdate();
17121 var suspenseConfig = requestCurrentSuspenseConfig();
17122 var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
17123 var _update2 = {
17124 expirationTime: expirationTime,
17125 suspenseConfig: suspenseConfig,
17126 action: action,
17127 eagerReducer: null,
17128 eagerState: null,
17129 next: null
17130 };
17131
17132 {
17133 _update2.priority = getCurrentPriorityLevel();
17134 } // Append the update to the end of the list.
17135
17136
17137 var last = queue.last;
17138
17139 if (last === null) {
17140 // This is the first update. Create a circular list.
17141 _update2.next = _update2;
17142 } else {
17143 var first = last.next;
17144
17145 if (first !== null) {
17146 // Still circular.
17147 _update2.next = first;
17148 }
17149
17150 last.next = _update2;
17151 }
17152
17153 queue.last = _update2;
17154
17155 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
17156 // The queue is currently empty, which means we can eagerly compute the
17157 // next state before entering the render phase. If the new state is the
17158 // same as the current state, we may be able to bail out entirely.
17159 var lastRenderedReducer = queue.lastRenderedReducer;
17160
17161 if (lastRenderedReducer !== null) {
17162 var prevDispatcher;
17163
17164 {
17165 prevDispatcher = ReactCurrentDispatcher$1.current;
17166 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17167 }
17168
17169 try {
17170 var currentState = queue.lastRenderedState;
17171 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
17172 // it, on the update object. If the reducer hasn't changed by the
17173 // time we enter the render phase, then the eager state can be used
17174 // without calling the reducer again.
17175
17176 _update2.eagerReducer = lastRenderedReducer;
17177 _update2.eagerState = eagerState;
17178
17179 if (is$1(eagerState, currentState)) {
17180 // Fast path. We can bail out without scheduling React to re-render.
17181 // It's still possible that we'll need to rebase this update later,
17182 // if the component re-renders for a different reason and by that
17183 // time the reducer has changed.
17184 return;
17185 }
17186 } catch (error) {// Suppress the error. It will throw again in the render phase.
17187 } finally {
17188 {
17189 ReactCurrentDispatcher$1.current = prevDispatcher;
17190 }
17191 }
17192 }
17193 }
17194
17195 {
17196 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
17197 if ('undefined' !== typeof jest) {
17198 warnIfNotScopedWithMatchingAct(fiber);
17199 warnIfNotCurrentlyActingUpdatesInDev(fiber);
17200 }
17201 }
17202
17203 scheduleWork(fiber, expirationTime);
17204 }
17205}
17206
17207var ContextOnlyDispatcher = {
17208 readContext: readContext,
17209 useCallback: throwInvalidHookError,
17210 useContext: throwInvalidHookError,
17211 useEffect: throwInvalidHookError,
17212 useImperativeHandle: throwInvalidHookError,
17213 useLayoutEffect: throwInvalidHookError,
17214 useMemo: throwInvalidHookError,
17215 useReducer: throwInvalidHookError,
17216 useRef: throwInvalidHookError,
17217 useState: throwInvalidHookError,
17218 useDebugValue: throwInvalidHookError,
17219 useResponder: throwInvalidHookError,
17220 useDeferredValue: throwInvalidHookError,
17221 useTransition: throwInvalidHookError
17222};
17223var HooksDispatcherOnMountInDEV = null;
17224var HooksDispatcherOnMountWithHookTypesInDEV = null;
17225var HooksDispatcherOnUpdateInDEV = null;
17226var InvalidNestedHooksDispatcherOnMountInDEV = null;
17227var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
17228
17229{
17230 var warnInvalidContextAccess = function () {
17231 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().');
17232 };
17233
17234 var warnInvalidHookAccess = function () {
17235 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');
17236 };
17237
17238 HooksDispatcherOnMountInDEV = {
17239 readContext: function (context, observedBits) {
17240 return readContext(context, observedBits);
17241 },
17242 useCallback: function (callback, deps) {
17243 currentHookNameInDev = 'useCallback';
17244 mountHookTypesDev();
17245 checkDepsAreArrayDev(deps);
17246 return mountCallback(callback, deps);
17247 },
17248 useContext: function (context, observedBits) {
17249 currentHookNameInDev = 'useContext';
17250 mountHookTypesDev();
17251 return readContext(context, observedBits);
17252 },
17253 useEffect: function (create, deps) {
17254 currentHookNameInDev = 'useEffect';
17255 mountHookTypesDev();
17256 checkDepsAreArrayDev(deps);
17257 return mountEffect(create, deps);
17258 },
17259 useImperativeHandle: function (ref, create, deps) {
17260 currentHookNameInDev = 'useImperativeHandle';
17261 mountHookTypesDev();
17262 checkDepsAreArrayDev(deps);
17263 return mountImperativeHandle(ref, create, deps);
17264 },
17265 useLayoutEffect: function (create, deps) {
17266 currentHookNameInDev = 'useLayoutEffect';
17267 mountHookTypesDev();
17268 checkDepsAreArrayDev(deps);
17269 return mountLayoutEffect(create, deps);
17270 },
17271 useMemo: function (create, deps) {
17272 currentHookNameInDev = 'useMemo';
17273 mountHookTypesDev();
17274 checkDepsAreArrayDev(deps);
17275 var prevDispatcher = ReactCurrentDispatcher$1.current;
17276 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17277
17278 try {
17279 return mountMemo(create, deps);
17280 } finally {
17281 ReactCurrentDispatcher$1.current = prevDispatcher;
17282 }
17283 },
17284 useReducer: function (reducer, initialArg, init) {
17285 currentHookNameInDev = 'useReducer';
17286 mountHookTypesDev();
17287 var prevDispatcher = ReactCurrentDispatcher$1.current;
17288 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17289
17290 try {
17291 return mountReducer(reducer, initialArg, init);
17292 } finally {
17293 ReactCurrentDispatcher$1.current = prevDispatcher;
17294 }
17295 },
17296 useRef: function (initialValue) {
17297 currentHookNameInDev = 'useRef';
17298 mountHookTypesDev();
17299 return mountRef(initialValue);
17300 },
17301 useState: function (initialState) {
17302 currentHookNameInDev = 'useState';
17303 mountHookTypesDev();
17304 var prevDispatcher = ReactCurrentDispatcher$1.current;
17305 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17306
17307 try {
17308 return mountState(initialState);
17309 } finally {
17310 ReactCurrentDispatcher$1.current = prevDispatcher;
17311 }
17312 },
17313 useDebugValue: function (value, formatterFn) {
17314 currentHookNameInDev = 'useDebugValue';
17315 mountHookTypesDev();
17316 return mountDebugValue(value, formatterFn);
17317 },
17318 useResponder: function (responder, props) {
17319 currentHookNameInDev = 'useResponder';
17320 mountHookTypesDev();
17321 return createResponderListener(responder, props);
17322 },
17323 useDeferredValue: function (value, config) {
17324 currentHookNameInDev = 'useDeferredValue';
17325 mountHookTypesDev();
17326 return mountDeferredValue(value, config);
17327 },
17328 useTransition: function (config) {
17329 currentHookNameInDev = 'useTransition';
17330 mountHookTypesDev();
17331 return mountTransition(config);
17332 }
17333 };
17334 HooksDispatcherOnMountWithHookTypesInDEV = {
17335 readContext: function (context, observedBits) {
17336 return readContext(context, observedBits);
17337 },
17338 useCallback: function (callback, deps) {
17339 currentHookNameInDev = 'useCallback';
17340 updateHookTypesDev();
17341 return mountCallback(callback, deps);
17342 },
17343 useContext: function (context, observedBits) {
17344 currentHookNameInDev = 'useContext';
17345 updateHookTypesDev();
17346 return readContext(context, observedBits);
17347 },
17348 useEffect: function (create, deps) {
17349 currentHookNameInDev = 'useEffect';
17350 updateHookTypesDev();
17351 return mountEffect(create, deps);
17352 },
17353 useImperativeHandle: function (ref, create, deps) {
17354 currentHookNameInDev = 'useImperativeHandle';
17355 updateHookTypesDev();
17356 return mountImperativeHandle(ref, create, deps);
17357 },
17358 useLayoutEffect: function (create, deps) {
17359 currentHookNameInDev = 'useLayoutEffect';
17360 updateHookTypesDev();
17361 return mountLayoutEffect(create, deps);
17362 },
17363 useMemo: function (create, deps) {
17364 currentHookNameInDev = 'useMemo';
17365 updateHookTypesDev();
17366 var prevDispatcher = ReactCurrentDispatcher$1.current;
17367 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17368
17369 try {
17370 return mountMemo(create, deps);
17371 } finally {
17372 ReactCurrentDispatcher$1.current = prevDispatcher;
17373 }
17374 },
17375 useReducer: function (reducer, initialArg, init) {
17376 currentHookNameInDev = 'useReducer';
17377 updateHookTypesDev();
17378 var prevDispatcher = ReactCurrentDispatcher$1.current;
17379 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17380
17381 try {
17382 return mountReducer(reducer, initialArg, init);
17383 } finally {
17384 ReactCurrentDispatcher$1.current = prevDispatcher;
17385 }
17386 },
17387 useRef: function (initialValue) {
17388 currentHookNameInDev = 'useRef';
17389 updateHookTypesDev();
17390 return mountRef(initialValue);
17391 },
17392 useState: function (initialState) {
17393 currentHookNameInDev = 'useState';
17394 updateHookTypesDev();
17395 var prevDispatcher = ReactCurrentDispatcher$1.current;
17396 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17397
17398 try {
17399 return mountState(initialState);
17400 } finally {
17401 ReactCurrentDispatcher$1.current = prevDispatcher;
17402 }
17403 },
17404 useDebugValue: function (value, formatterFn) {
17405 currentHookNameInDev = 'useDebugValue';
17406 updateHookTypesDev();
17407 return mountDebugValue(value, formatterFn);
17408 },
17409 useResponder: function (responder, props) {
17410 currentHookNameInDev = 'useResponder';
17411 updateHookTypesDev();
17412 return createResponderListener(responder, props);
17413 },
17414 useDeferredValue: function (value, config) {
17415 currentHookNameInDev = 'useDeferredValue';
17416 updateHookTypesDev();
17417 return mountDeferredValue(value, config);
17418 },
17419 useTransition: function (config) {
17420 currentHookNameInDev = 'useTransition';
17421 updateHookTypesDev();
17422 return mountTransition(config);
17423 }
17424 };
17425 HooksDispatcherOnUpdateInDEV = {
17426 readContext: function (context, observedBits) {
17427 return readContext(context, observedBits);
17428 },
17429 useCallback: function (callback, deps) {
17430 currentHookNameInDev = 'useCallback';
17431 updateHookTypesDev();
17432 return updateCallback(callback, deps);
17433 },
17434 useContext: function (context, observedBits) {
17435 currentHookNameInDev = 'useContext';
17436 updateHookTypesDev();
17437 return readContext(context, observedBits);
17438 },
17439 useEffect: function (create, deps) {
17440 currentHookNameInDev = 'useEffect';
17441 updateHookTypesDev();
17442 return updateEffect(create, deps);
17443 },
17444 useImperativeHandle: function (ref, create, deps) {
17445 currentHookNameInDev = 'useImperativeHandle';
17446 updateHookTypesDev();
17447 return updateImperativeHandle(ref, create, deps);
17448 },
17449 useLayoutEffect: function (create, deps) {
17450 currentHookNameInDev = 'useLayoutEffect';
17451 updateHookTypesDev();
17452 return updateLayoutEffect(create, deps);
17453 },
17454 useMemo: function (create, deps) {
17455 currentHookNameInDev = 'useMemo';
17456 updateHookTypesDev();
17457 var prevDispatcher = ReactCurrentDispatcher$1.current;
17458 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17459
17460 try {
17461 return updateMemo(create, deps);
17462 } finally {
17463 ReactCurrentDispatcher$1.current = prevDispatcher;
17464 }
17465 },
17466 useReducer: function (reducer, initialArg, init) {
17467 currentHookNameInDev = 'useReducer';
17468 updateHookTypesDev();
17469 var prevDispatcher = ReactCurrentDispatcher$1.current;
17470 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17471
17472 try {
17473 return updateReducer(reducer, initialArg, init);
17474 } finally {
17475 ReactCurrentDispatcher$1.current = prevDispatcher;
17476 }
17477 },
17478 useRef: function (initialValue) {
17479 currentHookNameInDev = 'useRef';
17480 updateHookTypesDev();
17481 return updateRef(initialValue);
17482 },
17483 useState: function (initialState) {
17484 currentHookNameInDev = 'useState';
17485 updateHookTypesDev();
17486 var prevDispatcher = ReactCurrentDispatcher$1.current;
17487 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17488
17489 try {
17490 return updateState(initialState);
17491 } finally {
17492 ReactCurrentDispatcher$1.current = prevDispatcher;
17493 }
17494 },
17495 useDebugValue: function (value, formatterFn) {
17496 currentHookNameInDev = 'useDebugValue';
17497 updateHookTypesDev();
17498 return updateDebugValue(value, formatterFn);
17499 },
17500 useResponder: function (responder, props) {
17501 currentHookNameInDev = 'useResponder';
17502 updateHookTypesDev();
17503 return createResponderListener(responder, props);
17504 },
17505 useDeferredValue: function (value, config) {
17506 currentHookNameInDev = 'useDeferredValue';
17507 updateHookTypesDev();
17508 return updateDeferredValue(value, config);
17509 },
17510 useTransition: function (config) {
17511 currentHookNameInDev = 'useTransition';
17512 updateHookTypesDev();
17513 return updateTransition(config);
17514 }
17515 };
17516 InvalidNestedHooksDispatcherOnMountInDEV = {
17517 readContext: function (context, observedBits) {
17518 warnInvalidContextAccess();
17519 return readContext(context, observedBits);
17520 },
17521 useCallback: function (callback, deps) {
17522 currentHookNameInDev = 'useCallback';
17523 warnInvalidHookAccess();
17524 mountHookTypesDev();
17525 return mountCallback(callback, deps);
17526 },
17527 useContext: function (context, observedBits) {
17528 currentHookNameInDev = 'useContext';
17529 warnInvalidHookAccess();
17530 mountHookTypesDev();
17531 return readContext(context, observedBits);
17532 },
17533 useEffect: function (create, deps) {
17534 currentHookNameInDev = 'useEffect';
17535 warnInvalidHookAccess();
17536 mountHookTypesDev();
17537 return mountEffect(create, deps);
17538 },
17539 useImperativeHandle: function (ref, create, deps) {
17540 currentHookNameInDev = 'useImperativeHandle';
17541 warnInvalidHookAccess();
17542 mountHookTypesDev();
17543 return mountImperativeHandle(ref, create, deps);
17544 },
17545 useLayoutEffect: function (create, deps) {
17546 currentHookNameInDev = 'useLayoutEffect';
17547 warnInvalidHookAccess();
17548 mountHookTypesDev();
17549 return mountLayoutEffect(create, deps);
17550 },
17551 useMemo: function (create, deps) {
17552 currentHookNameInDev = 'useMemo';
17553 warnInvalidHookAccess();
17554 mountHookTypesDev();
17555 var prevDispatcher = ReactCurrentDispatcher$1.current;
17556 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17557
17558 try {
17559 return mountMemo(create, deps);
17560 } finally {
17561 ReactCurrentDispatcher$1.current = prevDispatcher;
17562 }
17563 },
17564 useReducer: function (reducer, initialArg, init) {
17565 currentHookNameInDev = 'useReducer';
17566 warnInvalidHookAccess();
17567 mountHookTypesDev();
17568 var prevDispatcher = ReactCurrentDispatcher$1.current;
17569 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17570
17571 try {
17572 return mountReducer(reducer, initialArg, init);
17573 } finally {
17574 ReactCurrentDispatcher$1.current = prevDispatcher;
17575 }
17576 },
17577 useRef: function (initialValue) {
17578 currentHookNameInDev = 'useRef';
17579 warnInvalidHookAccess();
17580 mountHookTypesDev();
17581 return mountRef(initialValue);
17582 },
17583 useState: function (initialState) {
17584 currentHookNameInDev = 'useState';
17585 warnInvalidHookAccess();
17586 mountHookTypesDev();
17587 var prevDispatcher = ReactCurrentDispatcher$1.current;
17588 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17589
17590 try {
17591 return mountState(initialState);
17592 } finally {
17593 ReactCurrentDispatcher$1.current = prevDispatcher;
17594 }
17595 },
17596 useDebugValue: function (value, formatterFn) {
17597 currentHookNameInDev = 'useDebugValue';
17598 warnInvalidHookAccess();
17599 mountHookTypesDev();
17600 return mountDebugValue(value, formatterFn);
17601 },
17602 useResponder: function (responder, props) {
17603 currentHookNameInDev = 'useResponder';
17604 warnInvalidHookAccess();
17605 mountHookTypesDev();
17606 return createResponderListener(responder, props);
17607 },
17608 useDeferredValue: function (value, config) {
17609 currentHookNameInDev = 'useDeferredValue';
17610 warnInvalidHookAccess();
17611 mountHookTypesDev();
17612 return mountDeferredValue(value, config);
17613 },
17614 useTransition: function (config) {
17615 currentHookNameInDev = 'useTransition';
17616 warnInvalidHookAccess();
17617 mountHookTypesDev();
17618 return mountTransition(config);
17619 }
17620 };
17621 InvalidNestedHooksDispatcherOnUpdateInDEV = {
17622 readContext: function (context, observedBits) {
17623 warnInvalidContextAccess();
17624 return readContext(context, observedBits);
17625 },
17626 useCallback: function (callback, deps) {
17627 currentHookNameInDev = 'useCallback';
17628 warnInvalidHookAccess();
17629 updateHookTypesDev();
17630 return updateCallback(callback, deps);
17631 },
17632 useContext: function (context, observedBits) {
17633 currentHookNameInDev = 'useContext';
17634 warnInvalidHookAccess();
17635 updateHookTypesDev();
17636 return readContext(context, observedBits);
17637 },
17638 useEffect: function (create, deps) {
17639 currentHookNameInDev = 'useEffect';
17640 warnInvalidHookAccess();
17641 updateHookTypesDev();
17642 return updateEffect(create, deps);
17643 },
17644 useImperativeHandle: function (ref, create, deps) {
17645 currentHookNameInDev = 'useImperativeHandle';
17646 warnInvalidHookAccess();
17647 updateHookTypesDev();
17648 return updateImperativeHandle(ref, create, deps);
17649 },
17650 useLayoutEffect: function (create, deps) {
17651 currentHookNameInDev = 'useLayoutEffect';
17652 warnInvalidHookAccess();
17653 updateHookTypesDev();
17654 return updateLayoutEffect(create, deps);
17655 },
17656 useMemo: function (create, deps) {
17657 currentHookNameInDev = 'useMemo';
17658 warnInvalidHookAccess();
17659 updateHookTypesDev();
17660 var prevDispatcher = ReactCurrentDispatcher$1.current;
17661 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17662
17663 try {
17664 return updateMemo(create, deps);
17665 } finally {
17666 ReactCurrentDispatcher$1.current = prevDispatcher;
17667 }
17668 },
17669 useReducer: function (reducer, initialArg, init) {
17670 currentHookNameInDev = 'useReducer';
17671 warnInvalidHookAccess();
17672 updateHookTypesDev();
17673 var prevDispatcher = ReactCurrentDispatcher$1.current;
17674 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17675
17676 try {
17677 return updateReducer(reducer, initialArg, init);
17678 } finally {
17679 ReactCurrentDispatcher$1.current = prevDispatcher;
17680 }
17681 },
17682 useRef: function (initialValue) {
17683 currentHookNameInDev = 'useRef';
17684 warnInvalidHookAccess();
17685 updateHookTypesDev();
17686 return updateRef(initialValue);
17687 },
17688 useState: function (initialState) {
17689 currentHookNameInDev = 'useState';
17690 warnInvalidHookAccess();
17691 updateHookTypesDev();
17692 var prevDispatcher = ReactCurrentDispatcher$1.current;
17693 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17694
17695 try {
17696 return updateState(initialState);
17697 } finally {
17698 ReactCurrentDispatcher$1.current = prevDispatcher;
17699 }
17700 },
17701 useDebugValue: function (value, formatterFn) {
17702 currentHookNameInDev = 'useDebugValue';
17703 warnInvalidHookAccess();
17704 updateHookTypesDev();
17705 return updateDebugValue(value, formatterFn);
17706 },
17707 useResponder: function (responder, props) {
17708 currentHookNameInDev = 'useResponder';
17709 warnInvalidHookAccess();
17710 updateHookTypesDev();
17711 return createResponderListener(responder, props);
17712 },
17713 useDeferredValue: function (value, config) {
17714 currentHookNameInDev = 'useDeferredValue';
17715 warnInvalidHookAccess();
17716 updateHookTypesDev();
17717 return updateDeferredValue(value, config);
17718 },
17719 useTransition: function (config) {
17720 currentHookNameInDev = 'useTransition';
17721 warnInvalidHookAccess();
17722 updateHookTypesDev();
17723 return updateTransition(config);
17724 }
17725 };
17726}
17727
17728// CommonJS interop named imports.
17729
17730var now$1 = unstable_now;
17731var commitTime = 0;
17732var profilerStartTime = -1;
17733
17734function getCommitTime() {
17735 return commitTime;
17736}
17737
17738function recordCommitTime() {
17739 if (!enableProfilerTimer) {
17740 return;
17741 }
17742
17743 commitTime = now$1();
17744}
17745
17746function startProfilerTimer(fiber) {
17747 if (!enableProfilerTimer) {
17748 return;
17749 }
17750
17751 profilerStartTime = now$1();
17752
17753 if (fiber.actualStartTime < 0) {
17754 fiber.actualStartTime = now$1();
17755 }
17756}
17757
17758function stopProfilerTimerIfRunning(fiber) {
17759 if (!enableProfilerTimer) {
17760 return;
17761 }
17762
17763 profilerStartTime = -1;
17764}
17765
17766function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
17767 if (!enableProfilerTimer) {
17768 return;
17769 }
17770
17771 if (profilerStartTime >= 0) {
17772 var elapsedTime = now$1() - profilerStartTime;
17773 fiber.actualDuration += elapsedTime;
17774
17775 if (overrideBaseTime) {
17776 fiber.selfBaseDuration = elapsedTime;
17777 }
17778
17779 profilerStartTime = -1;
17780 }
17781}
17782
17783// This may have been an insertion or a hydration.
17784
17785var hydrationParentFiber = null;
17786var nextHydratableInstance = null;
17787var isHydrating = false;
17788
17789function warnIfHydrating() {
17790 {
17791 !!isHydrating ? warning$1(false, 'We should not be hydrating here. This is a bug in React. Please file a bug.') : void 0;
17792 }
17793}
17794
17795function enterHydrationState(fiber) {
17796 if (!supportsHydration) {
17797 return false;
17798 }
17799
17800 var parentInstance = fiber.stateNode.containerInfo;
17801 nextHydratableInstance = getFirstHydratableChild(parentInstance);
17802 hydrationParentFiber = fiber;
17803 isHydrating = true;
17804 return true;
17805}
17806
17807function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance) {
17808 if (!supportsHydration) {
17809 return false;
17810 }
17811
17812 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
17813 popToNextHostParent(fiber);
17814 isHydrating = true;
17815 return true;
17816}
17817
17818function deleteHydratableInstance(returnFiber, instance) {
17819 {
17820 switch (returnFiber.tag) {
17821 case HostRoot:
17822 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
17823 break;
17824
17825 case HostComponent:
17826 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
17827 break;
17828 }
17829 }
17830
17831 var childToDelete = createFiberFromHostInstanceForDeletion();
17832 childToDelete.stateNode = instance;
17833 childToDelete.return = returnFiber;
17834 childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
17835 // these children are not part of the reconciliation list of children.
17836 // Even if we abort and rereconcile the children, that will try to hydrate
17837 // again and the nodes are still in the host tree so these will be
17838 // recreated.
17839
17840 if (returnFiber.lastEffect !== null) {
17841 returnFiber.lastEffect.nextEffect = childToDelete;
17842 returnFiber.lastEffect = childToDelete;
17843 } else {
17844 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
17845 }
17846}
17847
17848function insertNonHydratedInstance(returnFiber, fiber) {
17849 fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
17850
17851 {
17852 switch (returnFiber.tag) {
17853 case HostRoot:
17854 {
17855 var parentContainer = returnFiber.stateNode.containerInfo;
17856
17857 switch (fiber.tag) {
17858 case HostComponent:
17859 var type = fiber.type;
17860 var props = fiber.pendingProps;
17861 didNotFindHydratableContainerInstance(parentContainer, type, props);
17862 break;
17863
17864 case HostText:
17865 var text = fiber.pendingProps;
17866 didNotFindHydratableContainerTextInstance(parentContainer, text);
17867 break;
17868
17869 case SuspenseComponent:
17870
17871 break;
17872 }
17873
17874 break;
17875 }
17876
17877 case HostComponent:
17878 {
17879 var parentType = returnFiber.type;
17880 var parentProps = returnFiber.memoizedProps;
17881 var parentInstance = returnFiber.stateNode;
17882
17883 switch (fiber.tag) {
17884 case HostComponent:
17885 var _type = fiber.type;
17886 var _props = fiber.pendingProps;
17887 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
17888 break;
17889
17890 case HostText:
17891 var _text = fiber.pendingProps;
17892 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
17893 break;
17894
17895 case SuspenseComponent:
17896 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
17897 break;
17898 }
17899
17900 break;
17901 }
17902
17903 default:
17904 return;
17905 }
17906 }
17907}
17908
17909function tryHydrate(fiber, nextInstance) {
17910 switch (fiber.tag) {
17911 case HostComponent:
17912 {
17913 var type = fiber.type;
17914 var props = fiber.pendingProps;
17915 var instance = canHydrateInstance(nextInstance, type, props);
17916
17917 if (instance !== null) {
17918 fiber.stateNode = instance;
17919 return true;
17920 }
17921
17922 return false;
17923 }
17924
17925 case HostText:
17926 {
17927 var text = fiber.pendingProps;
17928 var textInstance = canHydrateTextInstance(nextInstance, text);
17929
17930 if (textInstance !== null) {
17931 fiber.stateNode = textInstance;
17932 return true;
17933 }
17934
17935 return false;
17936 }
17937
17938 case SuspenseComponent:
17939 {
17940 if (enableSuspenseServerRenderer) {
17941 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
17942
17943 if (suspenseInstance !== null) {
17944 var suspenseState = {
17945 dehydrated: suspenseInstance,
17946 retryTime: Never
17947 };
17948 fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
17949 // This simplifies the code for getHostSibling and deleting nodes,
17950 // since it doesn't have to consider all Suspense boundaries and
17951 // check if they're dehydrated ones or not.
17952
17953 var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
17954 dehydratedFragment.return = fiber;
17955 fiber.child = dehydratedFragment;
17956 return true;
17957 }
17958 }
17959
17960 return false;
17961 }
17962
17963 default:
17964 return false;
17965 }
17966}
17967
17968function tryToClaimNextHydratableInstance(fiber) {
17969 if (!isHydrating) {
17970 return;
17971 }
17972
17973 var nextInstance = nextHydratableInstance;
17974
17975 if (!nextInstance) {
17976 // Nothing to hydrate. Make it an insertion.
17977 insertNonHydratedInstance(hydrationParentFiber, fiber);
17978 isHydrating = false;
17979 hydrationParentFiber = fiber;
17980 return;
17981 }
17982
17983 var firstAttemptedInstance = nextInstance;
17984
17985 if (!tryHydrate(fiber, nextInstance)) {
17986 // If we can't hydrate this instance let's try the next one.
17987 // We use this as a heuristic. It's based on intuition and not data so it
17988 // might be flawed or unnecessary.
17989 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
17990
17991 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
17992 // Nothing to hydrate. Make it an insertion.
17993 insertNonHydratedInstance(hydrationParentFiber, fiber);
17994 isHydrating = false;
17995 hydrationParentFiber = fiber;
17996 return;
17997 } // We matched the next one, we'll now assume that the first one was
17998 // superfluous and we'll delete it. Since we can't eagerly delete it
17999 // we'll have to schedule a deletion. To do that, this node needs a dummy
18000 // fiber associated with it.
18001
18002
18003 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
18004 }
18005
18006 hydrationParentFiber = fiber;
18007 nextHydratableInstance = getFirstHydratableChild(nextInstance);
18008}
18009
18010function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
18011 if (!supportsHydration) {
18012 {
18013 {
18014 throw Error("Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
18015 }
18016 }
18017 }
18018
18019 var instance = fiber.stateNode;
18020 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.
18021
18022 fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
18023 // is a new ref we mark this as an update.
18024
18025 if (updatePayload !== null) {
18026 return true;
18027 }
18028
18029 return false;
18030}
18031
18032function prepareToHydrateHostTextInstance(fiber) {
18033 if (!supportsHydration) {
18034 {
18035 {
18036 throw Error("Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
18037 }
18038 }
18039 }
18040
18041 var textInstance = fiber.stateNode;
18042 var textContent = fiber.memoizedProps;
18043 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
18044
18045 {
18046 if (shouldUpdate) {
18047 // We assume that prepareToHydrateHostTextInstance is called in a context where the
18048 // hydration parent is the parent host component of this host text.
18049 var returnFiber = hydrationParentFiber;
18050
18051 if (returnFiber !== null) {
18052 switch (returnFiber.tag) {
18053 case HostRoot:
18054 {
18055 var parentContainer = returnFiber.stateNode.containerInfo;
18056 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
18057 break;
18058 }
18059
18060 case HostComponent:
18061 {
18062 var parentType = returnFiber.type;
18063 var parentProps = returnFiber.memoizedProps;
18064 var parentInstance = returnFiber.stateNode;
18065 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
18066 break;
18067 }
18068 }
18069 }
18070 }
18071 }
18072
18073 return shouldUpdate;
18074}
18075
18076function prepareToHydrateHostSuspenseInstance(fiber) {
18077 if (!supportsHydration) {
18078 {
18079 {
18080 throw Error("Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
18081 }
18082 }
18083 }
18084
18085 var suspenseState = fiber.memoizedState;
18086 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
18087
18088 if (!suspenseInstance) {
18089 {
18090 throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
18091 }
18092 }
18093
18094 hydrateSuspenseInstance(suspenseInstance, fiber);
18095}
18096
18097function skipPastDehydratedSuspenseInstance(fiber) {
18098 if (!supportsHydration) {
18099 {
18100 {
18101 throw Error("Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");
18102 }
18103 }
18104 }
18105
18106 var suspenseState = fiber.memoizedState;
18107 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
18108
18109 if (!suspenseInstance) {
18110 {
18111 throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
18112 }
18113 }
18114
18115 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
18116}
18117
18118function popToNextHostParent(fiber) {
18119 var parent = fiber.return;
18120
18121 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
18122 parent = parent.return;
18123 }
18124
18125 hydrationParentFiber = parent;
18126}
18127
18128function popHydrationState(fiber) {
18129 if (!supportsHydration) {
18130 return false;
18131 }
18132
18133 if (fiber !== hydrationParentFiber) {
18134 // We're deeper than the current hydration context, inside an inserted
18135 // tree.
18136 return false;
18137 }
18138
18139 if (!isHydrating) {
18140 // If we're not currently hydrating but we're in a hydration context, then
18141 // we were an insertion and now need to pop up reenter hydration of our
18142 // siblings.
18143 popToNextHostParent(fiber);
18144 isHydrating = true;
18145 return false;
18146 }
18147
18148 var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
18149 // We only do this deeper than head and body since they tend to have random
18150 // other nodes in them. We also ignore components with pure text content in
18151 // side of them.
18152 // TODO: Better heuristic.
18153
18154 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
18155 var nextInstance = nextHydratableInstance;
18156
18157 while (nextInstance) {
18158 deleteHydratableInstance(fiber, nextInstance);
18159 nextInstance = getNextHydratableSibling(nextInstance);
18160 }
18161 }
18162
18163 popToNextHostParent(fiber);
18164
18165 if (fiber.tag === SuspenseComponent) {
18166 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
18167 } else {
18168 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
18169 }
18170
18171 return true;
18172}
18173
18174function resetHydrationState() {
18175 if (!supportsHydration) {
18176 return;
18177 }
18178
18179 hydrationParentFiber = null;
18180 nextHydratableInstance = null;
18181 isHydrating = false;
18182}
18183
18184var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
18185var didReceiveUpdate = false;
18186var didWarnAboutBadClass;
18187var didWarnAboutModulePatternComponent;
18188var didWarnAboutContextTypeOnFunctionComponent;
18189var didWarnAboutGetDerivedStateOnFunctionComponent;
18190var didWarnAboutFunctionRefs;
18191var didWarnAboutReassigningProps;
18192var didWarnAboutMaxDuration;
18193var didWarnAboutRevealOrder;
18194var didWarnAboutTailOptions;
18195var didWarnAboutDefaultPropsOnFunctionComponent;
18196
18197{
18198 didWarnAboutBadClass = {};
18199 didWarnAboutModulePatternComponent = {};
18200 didWarnAboutContextTypeOnFunctionComponent = {};
18201 didWarnAboutGetDerivedStateOnFunctionComponent = {};
18202 didWarnAboutFunctionRefs = {};
18203 didWarnAboutReassigningProps = false;
18204 didWarnAboutMaxDuration = false;
18205 didWarnAboutRevealOrder = {};
18206 didWarnAboutTailOptions = {};
18207 didWarnAboutDefaultPropsOnFunctionComponent = {};
18208}
18209
18210function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18211 if (current$$1 === null) {
18212 // If this is a fresh new component that hasn't been rendered yet, we
18213 // won't update its child set by applying minimal side-effects. Instead,
18214 // we will add them all to the child before it gets rendered. That means
18215 // we can optimize this reconciliation pass by not tracking side-effects.
18216 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18217 } else {
18218 // If the current child is the same as the work in progress, it means that
18219 // we haven't yet started any work on these children. Therefore, we use
18220 // the clone algorithm to create a copy of all the current children.
18221 // If we had any progressed work already, that is invalid at this point so
18222 // let's throw it out.
18223 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
18224 }
18225}
18226
18227function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
18228 // This function is fork of reconcileChildren. It's used in cases where we
18229 // want to reconcile without matching against the existing set. This has the
18230 // effect of all current children being unmounted; even if the type and key
18231 // are the same, the old child is unmounted and a new child is created.
18232 //
18233 // To do this, we're going to go through the reconcile algorithm twice. In
18234 // the first pass, we schedule a deletion for all the current children by
18235 // passing null.
18236 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
18237 // pass null in place of where we usually pass the current child set. This has
18238 // the effect of remounting all children regardless of whether their their
18239 // identity matches.
18240
18241 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18242}
18243
18244function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18245 // TODO: current can be non-null here even if the component
18246 // hasn't yet mounted. This happens after the first render suspends.
18247 // We'll need to figure out if this is fine or can cause issues.
18248 {
18249 if (workInProgress.type !== workInProgress.elementType) {
18250 // Lazy component props can't be validated in createElement
18251 // because they're only guaranteed to be resolved here.
18252 var innerPropTypes = Component.propTypes;
18253
18254 if (innerPropTypes) {
18255 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18256 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18257 }
18258 }
18259 }
18260
18261 var render = Component.render;
18262 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
18263
18264 var nextChildren;
18265 prepareToReadContext(workInProgress, renderExpirationTime);
18266
18267 {
18268 ReactCurrentOwner$3.current = workInProgress;
18269 setCurrentPhase('render');
18270 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18271
18272 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18273 // Only double-render components with Hooks
18274 if (workInProgress.memoizedState !== null) {
18275 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
18276 }
18277 }
18278
18279 setCurrentPhase(null);
18280 }
18281
18282 if (current$$1 !== null && !didReceiveUpdate) {
18283 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18284 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18285 } // React DevTools reads this flag.
18286
18287
18288 workInProgress.effectTag |= PerformedWork;
18289 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18290 return workInProgress.child;
18291}
18292
18293function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18294 if (current$$1 === null) {
18295 var type = Component.type;
18296
18297 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
18298 Component.defaultProps === undefined) {
18299 var resolvedType = type;
18300
18301 {
18302 resolvedType = resolveFunctionForHotReloading(type);
18303 } // If this is a plain function component without default props,
18304 // and with only the default shallow comparison, we upgrade it
18305 // to a SimpleMemoComponent to allow fast path updates.
18306
18307
18308 workInProgress.tag = SimpleMemoComponent;
18309 workInProgress.type = resolvedType;
18310
18311 {
18312 validateFunctionComponentInDev(workInProgress, type);
18313 }
18314
18315 return updateSimpleMemoComponent(current$$1, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
18316 }
18317
18318 {
18319 var innerPropTypes = type.propTypes;
18320
18321 if (innerPropTypes) {
18322 // Inner memo component props aren't currently validated in createElement.
18323 // We could move it there, but we'd still need this for lazy code path.
18324 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18325 'prop', getComponentName(type), getCurrentFiberStackInDev);
18326 }
18327 }
18328
18329 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
18330 child.ref = workInProgress.ref;
18331 child.return = workInProgress;
18332 workInProgress.child = child;
18333 return child;
18334 }
18335
18336 {
18337 var _type = Component.type;
18338 var _innerPropTypes = _type.propTypes;
18339
18340 if (_innerPropTypes) {
18341 // Inner memo component props aren't currently validated in createElement.
18342 // We could move it there, but we'd still need this for lazy code path.
18343 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
18344 'prop', getComponentName(_type), getCurrentFiberStackInDev);
18345 }
18346 }
18347
18348 var currentChild = current$$1.child; // This is always exactly one child
18349
18350 if (updateExpirationTime < renderExpirationTime) {
18351 // This will be the props with resolved defaultProps,
18352 // unlike current.memoizedProps which will be the unresolved ones.
18353 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
18354
18355 var compare = Component.compare;
18356 compare = compare !== null ? compare : shallowEqual;
18357
18358 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
18359 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18360 }
18361 } // React DevTools reads this flag.
18362
18363
18364 workInProgress.effectTag |= PerformedWork;
18365 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
18366 newChild.ref = workInProgress.ref;
18367 newChild.return = workInProgress;
18368 workInProgress.child = newChild;
18369 return newChild;
18370}
18371
18372function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
18373 // TODO: current can be non-null here even if the component
18374 // hasn't yet mounted. This happens when the inner render suspends.
18375 // We'll need to figure out if this is fine or can cause issues.
18376 {
18377 if (workInProgress.type !== workInProgress.elementType) {
18378 // Lazy component props can't be validated in createElement
18379 // because they're only guaranteed to be resolved here.
18380 var outerMemoType = workInProgress.elementType;
18381
18382 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
18383 // We warn when you define propTypes on lazy()
18384 // so let's just skip over it to find memo() outer wrapper.
18385 // Inner props for memo are validated later.
18386 outerMemoType = refineResolvedLazyComponent(outerMemoType);
18387 }
18388
18389 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
18390
18391 if (outerPropTypes) {
18392 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
18393 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
18394 } // Inner propTypes will be validated in the function component path.
18395
18396 }
18397 }
18398
18399 if (current$$1 !== null) {
18400 var prevProps = current$$1.memoizedProps;
18401
18402 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload:
18403 workInProgress.type === current$$1.type)) {
18404 didReceiveUpdate = false;
18405
18406 if (updateExpirationTime < renderExpirationTime) {
18407 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18408 }
18409 }
18410 }
18411
18412 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18413}
18414
18415function updateFragment(current$$1, workInProgress, renderExpirationTime) {
18416 var nextChildren = workInProgress.pendingProps;
18417 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18418 return workInProgress.child;
18419}
18420
18421function updateMode(current$$1, workInProgress, renderExpirationTime) {
18422 var nextChildren = workInProgress.pendingProps.children;
18423 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18424 return workInProgress.child;
18425}
18426
18427function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
18428 if (enableProfilerTimer) {
18429 workInProgress.effectTag |= Update;
18430 }
18431
18432 var nextProps = workInProgress.pendingProps;
18433 var nextChildren = nextProps.children;
18434 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18435 return workInProgress.child;
18436}
18437
18438function markRef(current$$1, workInProgress) {
18439 var ref = workInProgress.ref;
18440
18441 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
18442 // Schedule a Ref effect
18443 workInProgress.effectTag |= Ref;
18444 }
18445}
18446
18447function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18448 {
18449 if (workInProgress.type !== workInProgress.elementType) {
18450 // Lazy component props can't be validated in createElement
18451 // because they're only guaranteed to be resolved here.
18452 var innerPropTypes = Component.propTypes;
18453
18454 if (innerPropTypes) {
18455 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18456 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18457 }
18458 }
18459 }
18460
18461 var context;
18462
18463 if (!disableLegacyContext) {
18464 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
18465 context = getMaskedContext(workInProgress, unmaskedContext);
18466 }
18467
18468 var nextChildren;
18469 prepareToReadContext(workInProgress, renderExpirationTime);
18470
18471 {
18472 ReactCurrentOwner$3.current = workInProgress;
18473 setCurrentPhase('render');
18474 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18475
18476 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18477 // Only double-render components with Hooks
18478 if (workInProgress.memoizedState !== null) {
18479 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
18480 }
18481 }
18482
18483 setCurrentPhase(null);
18484 }
18485
18486 if (current$$1 !== null && !didReceiveUpdate) {
18487 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
18488 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18489 } // React DevTools reads this flag.
18490
18491
18492 workInProgress.effectTag |= PerformedWork;
18493 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18494 return workInProgress.child;
18495}
18496
18497function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
18498 {
18499 if (workInProgress.type !== workInProgress.elementType) {
18500 // Lazy component props can't be validated in createElement
18501 // because they're only guaranteed to be resolved here.
18502 var innerPropTypes = Component.propTypes;
18503
18504 if (innerPropTypes) {
18505 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
18506 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18507 }
18508 }
18509 } // Push context providers early to prevent context stack mismatches.
18510 // During mounting we don't know the child context yet as the instance doesn't exist.
18511 // We will invalidate the child context in finishClassComponent() right after rendering.
18512
18513
18514 var hasContext;
18515
18516 if (isContextProvider(Component)) {
18517 hasContext = true;
18518 pushContextProvider(workInProgress);
18519 } else {
18520 hasContext = false;
18521 }
18522
18523 prepareToReadContext(workInProgress, renderExpirationTime);
18524 var instance = workInProgress.stateNode;
18525 var shouldUpdate;
18526
18527 if (instance === null) {
18528 if (current$$1 !== null) {
18529 // An class component without an instance only mounts if it suspended
18530 // inside a non- concurrent tree, in an inconsistent state. We want to
18531 // tree it like a new mount, even though an empty version of it already
18532 // committed. Disconnect the alternate pointers.
18533 current$$1.alternate = null;
18534 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18535
18536 workInProgress.effectTag |= Placement;
18537 } // In the initial pass we might need to construct the instance.
18538
18539
18540 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18541 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18542 shouldUpdate = true;
18543 } else if (current$$1 === null) {
18544 // In a resume, we'll already have an instance we can reuse.
18545 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18546 } else {
18547 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
18548 }
18549
18550 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
18551
18552 {
18553 var inst = workInProgress.stateNode;
18554
18555 if (inst.props !== nextProps) {
18556 !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;
18557 didWarnAboutReassigningProps = true;
18558 }
18559 }
18560
18561 return nextUnitOfWork;
18562}
18563
18564function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
18565 // Refs should update even if shouldComponentUpdate returns false
18566 markRef(current$$1, workInProgress);
18567 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
18568
18569 if (!shouldUpdate && !didCaptureError) {
18570 // Context providers should defer to sCU for rendering
18571 if (hasContext) {
18572 invalidateContextProvider(workInProgress, Component, false);
18573 }
18574
18575 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18576 }
18577
18578 var instance = workInProgress.stateNode; // Rerender
18579
18580 ReactCurrentOwner$3.current = workInProgress;
18581 var nextChildren;
18582
18583 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
18584 // If we captured an error, but getDerivedStateFrom catch is not defined,
18585 // unmount all the children. componentDidCatch will schedule an update to
18586 // re-render a fallback. This is temporary until we migrate everyone to
18587 // the new API.
18588 // TODO: Warn in a future release.
18589 nextChildren = null;
18590
18591 if (enableProfilerTimer) {
18592 stopProfilerTimerIfRunning(workInProgress);
18593 }
18594 } else {
18595 {
18596 setCurrentPhase('render');
18597 nextChildren = instance.render();
18598
18599 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18600 instance.render();
18601 }
18602
18603 setCurrentPhase(null);
18604 }
18605 } // React DevTools reads this flag.
18606
18607
18608 workInProgress.effectTag |= PerformedWork;
18609
18610 if (current$$1 !== null && didCaptureError) {
18611 // If we're recovering from an error, reconcile without reusing any of
18612 // the existing children. Conceptually, the normal children and the children
18613 // that are shown on error are two different sets, so we shouldn't reuse
18614 // normal children even if their identities match.
18615 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
18616 } else {
18617 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18618 } // Memoize state using the values we just used to render.
18619 // TODO: Restructure so we never read values from the instance.
18620
18621
18622 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
18623
18624 if (hasContext) {
18625 invalidateContextProvider(workInProgress, Component, true);
18626 }
18627
18628 return workInProgress.child;
18629}
18630
18631function pushHostRootContext(workInProgress) {
18632 var root = workInProgress.stateNode;
18633
18634 if (root.pendingContext) {
18635 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
18636 } else if (root.context) {
18637 // Should always be set
18638 pushTopLevelContextObject(workInProgress, root.context, false);
18639 }
18640
18641 pushHostContainer(workInProgress, root.containerInfo);
18642}
18643
18644function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
18645 pushHostRootContext(workInProgress);
18646 var updateQueue = workInProgress.updateQueue;
18647
18648 if (!(updateQueue !== null)) {
18649 {
18650 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.");
18651 }
18652 }
18653
18654 var nextProps = workInProgress.pendingProps;
18655 var prevState = workInProgress.memoizedState;
18656 var prevChildren = prevState !== null ? prevState.element : null;
18657 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
18658 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
18659 // being called "element".
18660
18661 var nextChildren = nextState.element;
18662
18663 if (nextChildren === prevChildren) {
18664 // If the state is the same as before, that's a bailout because we had
18665 // no work that expires at this time.
18666 resetHydrationState();
18667 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
18668 }
18669
18670 var root = workInProgress.stateNode;
18671
18672 if (root.hydrate && enterHydrationState(workInProgress)) {
18673 // If we don't have any current children this might be the first pass.
18674 // We always try to hydrate. If this isn't a hydration pass there won't
18675 // be any children to hydrate which is effectively the same thing as
18676 // not hydrating.
18677 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
18678 workInProgress.child = child;
18679 var node = child;
18680
18681 while (node) {
18682 // Mark each child as hydrating. This is a fast path to know whether this
18683 // tree is part of a hydrating tree. This is used to determine if a child
18684 // node has fully mounted yet, and for scheduling event replaying.
18685 // Conceptually this is similar to Placement in that a new subtree is
18686 // inserted into the React tree here. It just happens to not need DOM
18687 // mutations because it already exists.
18688 node.effectTag = node.effectTag & ~Placement | Hydrating;
18689 node = node.sibling;
18690 }
18691 } else {
18692 // Otherwise reset hydration state in case we aborted and resumed another
18693 // root.
18694 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18695 resetHydrationState();
18696 }
18697
18698 return workInProgress.child;
18699}
18700
18701function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
18702 pushHostContext(workInProgress);
18703
18704 if (current$$1 === null) {
18705 tryToClaimNextHydratableInstance(workInProgress);
18706 }
18707
18708 var type = workInProgress.type;
18709 var nextProps = workInProgress.pendingProps;
18710 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
18711 var nextChildren = nextProps.children;
18712 var isDirectTextChild = shouldSetTextContent(type, nextProps);
18713
18714 if (isDirectTextChild) {
18715 // We special case a direct text child of a host node. This is a common
18716 // case. We won't handle it as a reified child. We will instead handle
18717 // this in the host environment that also have access to this prop. That
18718 // avoids allocating another HostText fiber and traversing it.
18719 nextChildren = null;
18720 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
18721 // If we're switching from a direct text child to a normal child, or to
18722 // empty, we need to schedule the text content to be reset.
18723 workInProgress.effectTag |= ContentReset;
18724 }
18725
18726 markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden.
18727
18728 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
18729 if (enableSchedulerTracing) {
18730 markSpawnedWork(Never);
18731 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
18732
18733
18734 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
18735 return null;
18736 }
18737
18738 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
18739 return workInProgress.child;
18740}
18741
18742function updateHostText(current$$1, workInProgress) {
18743 if (current$$1 === null) {
18744 tryToClaimNextHydratableInstance(workInProgress);
18745 } // Nothing to do here. This is terminal. We'll do the completion step
18746 // immediately after.
18747
18748
18749 return null;
18750}
18751
18752function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
18753 if (_current !== null) {
18754 // An lazy component only mounts if it suspended inside a non-
18755 // concurrent tree, in an inconsistent state. We want to treat it like
18756 // a new mount, even though an empty version of it already committed.
18757 // Disconnect the alternate pointers.
18758 _current.alternate = null;
18759 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18760
18761 workInProgress.effectTag |= Placement;
18762 }
18763
18764 var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
18765 // Cancel and resume right after we know the tag.
18766
18767 cancelWorkTimer(workInProgress);
18768 var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
18769
18770 workInProgress.type = Component;
18771 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
18772 startWorkTimer(workInProgress);
18773 var resolvedProps = resolveDefaultProps(Component, props);
18774 var child;
18775
18776 switch (resolvedTag) {
18777 case FunctionComponent:
18778 {
18779 {
18780 validateFunctionComponentInDev(workInProgress, Component);
18781 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
18782 }
18783
18784 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18785 break;
18786 }
18787
18788 case ClassComponent:
18789 {
18790 {
18791 workInProgress.type = Component = resolveClassForHotReloading(Component);
18792 }
18793
18794 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18795 break;
18796 }
18797
18798 case ForwardRef:
18799 {
18800 {
18801 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
18802 }
18803
18804 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
18805 break;
18806 }
18807
18808 case MemoComponent:
18809 {
18810 {
18811 if (workInProgress.type !== workInProgress.elementType) {
18812 var outerPropTypes = Component.propTypes;
18813
18814 if (outerPropTypes) {
18815 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
18816 'prop', getComponentName(Component), getCurrentFiberStackInDev);
18817 }
18818 }
18819 }
18820
18821 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
18822 updateExpirationTime, renderExpirationTime);
18823 break;
18824 }
18825
18826 default:
18827 {
18828 var hint = '';
18829
18830 {
18831 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
18832 hint = ' Did you wrap a component in React.lazy() more than once?';
18833 }
18834 } // This message intentionally doesn't mention ForwardRef or MemoComponent
18835 // because the fact that it's a separate type of work is an
18836 // implementation detail.
18837
18838
18839 {
18840 {
18841 throw Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint);
18842 }
18843 }
18844 }
18845 }
18846
18847 return child;
18848}
18849
18850function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
18851 if (_current !== null) {
18852 // An incomplete component only mounts if it suspended inside a non-
18853 // concurrent tree, in an inconsistent state. We want to treat it like
18854 // a new mount, even though an empty version of it already committed.
18855 // Disconnect the alternate pointers.
18856 _current.alternate = null;
18857 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18858
18859 workInProgress.effectTag |= Placement;
18860 } // Promote the fiber to a class and try rendering again.
18861
18862
18863 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
18864 // Push context providers early to prevent context stack mismatches.
18865 // During mounting we don't know the child context yet as the instance doesn't exist.
18866 // We will invalidate the child context in finishClassComponent() right after rendering.
18867
18868 var hasContext;
18869
18870 if (isContextProvider(Component)) {
18871 hasContext = true;
18872 pushContextProvider(workInProgress);
18873 } else {
18874 hasContext = false;
18875 }
18876
18877 prepareToReadContext(workInProgress, renderExpirationTime);
18878 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18879 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
18880 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18881}
18882
18883function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
18884 if (_current !== null) {
18885 // An indeterminate component only mounts if it suspended inside a non-
18886 // concurrent tree, in an inconsistent state. We want to treat it like
18887 // a new mount, even though an empty version of it already committed.
18888 // Disconnect the alternate pointers.
18889 _current.alternate = null;
18890 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
18891
18892 workInProgress.effectTag |= Placement;
18893 }
18894
18895 var props = workInProgress.pendingProps;
18896 var context;
18897
18898 if (!disableLegacyContext) {
18899 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
18900 context = getMaskedContext(workInProgress, unmaskedContext);
18901 }
18902
18903 prepareToReadContext(workInProgress, renderExpirationTime);
18904 var value;
18905
18906 {
18907 if (Component.prototype && typeof Component.prototype.render === 'function') {
18908 var componentName = getComponentName(Component) || 'Unknown';
18909
18910 if (!didWarnAboutBadClass[componentName]) {
18911 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);
18912 didWarnAboutBadClass[componentName] = true;
18913 }
18914 }
18915
18916 if (workInProgress.mode & StrictMode) {
18917 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
18918 }
18919
18920 ReactCurrentOwner$3.current = workInProgress;
18921 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18922 } // React DevTools reads this flag.
18923
18924
18925 workInProgress.effectTag |= PerformedWork;
18926
18927 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
18928 {
18929 var _componentName = getComponentName(Component) || 'Unknown';
18930
18931 if (!didWarnAboutModulePatternComponent[_componentName]) {
18932 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);
18933 didWarnAboutModulePatternComponent[_componentName] = true;
18934 }
18935 } // Proceed under the assumption that this is a class instance
18936
18937
18938 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
18939
18940 resetHooks(); // Push context providers early to prevent context stack mismatches.
18941 // During mounting we don't know the child context yet as the instance doesn't exist.
18942 // We will invalidate the child context in finishClassComponent() right after rendering.
18943
18944 var hasContext = false;
18945
18946 if (isContextProvider(Component)) {
18947 hasContext = true;
18948 pushContextProvider(workInProgress);
18949 } else {
18950 hasContext = false;
18951 }
18952
18953 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
18954 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
18955
18956 if (typeof getDerivedStateFromProps === 'function') {
18957 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
18958 }
18959
18960 adoptClassInstance(workInProgress, value);
18961 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
18962 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
18963 } else {
18964 // Proceed under the assumption that this is a function component
18965 workInProgress.tag = FunctionComponent;
18966
18967 {
18968 if (disableLegacyContext && Component.contextTypes) {
18969 warningWithoutStack$1(false, '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', getComponentName(Component) || 'Unknown');
18970 }
18971
18972 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
18973 // Only double-render components with Hooks
18974 if (workInProgress.memoizedState !== null) {
18975 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
18976 }
18977 }
18978 }
18979
18980 reconcileChildren(null, workInProgress, value, renderExpirationTime);
18981
18982 {
18983 validateFunctionComponentInDev(workInProgress, Component);
18984 }
18985
18986 return workInProgress.child;
18987 }
18988}
18989
18990function validateFunctionComponentInDev(workInProgress, Component) {
18991 if (Component) {
18992 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
18993 }
18994
18995 if (workInProgress.ref !== null) {
18996 var info = '';
18997 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
18998
18999 if (ownerName) {
19000 info += '\n\nCheck the render method of `' + ownerName + '`.';
19001 }
19002
19003 var warningKey = ownerName || workInProgress._debugID || '';
19004 var debugSource = workInProgress._debugSource;
19005
19006 if (debugSource) {
19007 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
19008 }
19009
19010 if (!didWarnAboutFunctionRefs[warningKey]) {
19011 didWarnAboutFunctionRefs[warningKey] = true;
19012 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);
19013 }
19014 }
19015
19016 if (warnAboutDefaultPropsOnFunctionComponents && Component.defaultProps !== undefined) {
19017 var componentName = getComponentName(Component) || 'Unknown';
19018
19019 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
19020 warningWithoutStack$1(false, '%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
19021 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
19022 }
19023 }
19024
19025 if (typeof Component.getDerivedStateFromProps === 'function') {
19026 var _componentName2 = getComponentName(Component) || 'Unknown';
19027
19028 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
19029 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', _componentName2);
19030 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
19031 }
19032 }
19033
19034 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
19035 var _componentName3 = getComponentName(Component) || 'Unknown';
19036
19037 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
19038 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName3);
19039 didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
19040 }
19041 }
19042}
19043
19044var SUSPENDED_MARKER = {
19045 dehydrated: null,
19046 retryTime: NoWork
19047};
19048
19049function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) {
19050 // If the context is telling us that we should show a fallback, and we're not
19051 // already showing content, then we should show the fallback instead.
19052 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current$$1 === null || current$$1.memoizedState !== null);
19053}
19054
19055function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
19056 var mode = workInProgress.mode;
19057 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
19058
19059 {
19060 if (shouldSuspend(workInProgress)) {
19061 workInProgress.effectTag |= DidCapture;
19062 }
19063 }
19064
19065 var suspenseContext = suspenseStackCursor.current;
19066 var nextDidTimeout = false;
19067 var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
19068
19069 if (didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress)) {
19070 // Something in this boundary's subtree already suspended. Switch to
19071 // rendering the fallback children.
19072 nextDidTimeout = true;
19073 workInProgress.effectTag &= ~DidCapture;
19074 } else {
19075 // Attempting the main content
19076 if (current$$1 === null || current$$1.memoizedState !== null) {
19077 // This is a new mount or this boundary is already showing a fallback state.
19078 // Mark this subtree context as having at least one invisible parent that could
19079 // handle the fallback state.
19080 // Boundaries without fallbacks or should be avoided are not considered since
19081 // they cannot handle preferred fallback states.
19082 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
19083 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
19084 }
19085 }
19086 }
19087
19088 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19089 pushSuspenseContext(workInProgress, suspenseContext);
19090
19091 {
19092 if ('maxDuration' in nextProps) {
19093 if (!didWarnAboutMaxDuration) {
19094 didWarnAboutMaxDuration = true;
19095 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
19096 }
19097 }
19098 } // This next part is a bit confusing. If the children timeout, we switch to
19099 // showing the fallback children in place of the "primary" children.
19100 // However, we don't want to delete the primary children because then their
19101 // state will be lost (both the React state and the host state, e.g.
19102 // uncontrolled form inputs). Instead we keep them mounted and hide them.
19103 // Both the fallback children AND the primary children are rendered at the
19104 // same time. Once the primary children are un-suspended, we can delete
19105 // the fallback children — don't need to preserve their state.
19106 //
19107 // The two sets of children are siblings in the host environment, but
19108 // semantically, for purposes of reconciliation, they are two separate sets.
19109 // So we store them using two fragment fibers.
19110 //
19111 // However, we want to avoid allocating extra fibers for every placeholder.
19112 // They're only necessary when the children time out, because that's the
19113 // only time when both sets are mounted.
19114 //
19115 // So, the extra fragment fibers are only used if the children time out.
19116 // Otherwise, we render the primary children directly. This requires some
19117 // custom reconciliation logic to preserve the state of the primary
19118 // children. It's essentially a very basic form of re-parenting.
19119
19120
19121 if (current$$1 === null) {
19122 // If we're currently hydrating, try to hydrate this boundary.
19123 // But only if this has a fallback.
19124 if (nextProps.fallback !== undefined) {
19125 tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
19126
19127 if (enableSuspenseServerRenderer) {
19128 var suspenseState = workInProgress.memoizedState;
19129
19130 if (suspenseState !== null) {
19131 var dehydrated = suspenseState.dehydrated;
19132
19133 if (dehydrated !== null) {
19134 return mountDehydratedSuspenseComponent(workInProgress, dehydrated, renderExpirationTime);
19135 }
19136 }
19137 }
19138 } // This is the initial mount. This branch is pretty simple because there's
19139 // no previous state that needs to be preserved.
19140
19141
19142 if (nextDidTimeout) {
19143 // Mount separate fragments for primary and fallback children.
19144 var nextFallbackChildren = nextProps.fallback;
19145 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
19146 primaryChildFragment.return = workInProgress;
19147
19148 if ((workInProgress.mode & BatchedMode) === NoMode) {
19149 // Outside of batched mode, we commit the effects from the
19150 // partially completed, timed-out tree, too.
19151 var progressedState = workInProgress.memoizedState;
19152 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
19153 primaryChildFragment.child = progressedPrimaryChild;
19154 var progressedChild = progressedPrimaryChild;
19155
19156 while (progressedChild !== null) {
19157 progressedChild.return = primaryChildFragment;
19158 progressedChild = progressedChild.sibling;
19159 }
19160 }
19161
19162 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
19163 fallbackChildFragment.return = workInProgress;
19164 primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
19165 // fallback children.
19166
19167 workInProgress.memoizedState = SUSPENDED_MARKER;
19168 workInProgress.child = primaryChildFragment;
19169 return fallbackChildFragment;
19170 } else {
19171 // Mount the primary children without an intermediate fragment fiber.
19172 var nextPrimaryChildren = nextProps.children;
19173 workInProgress.memoizedState = null;
19174 return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
19175 }
19176 } else {
19177 // This is an update. This branch is more complicated because we need to
19178 // ensure the state of the primary children is preserved.
19179 var prevState = current$$1.memoizedState;
19180
19181 if (prevState !== null) {
19182 if (enableSuspenseServerRenderer) {
19183 var _dehydrated = prevState.dehydrated;
19184
19185 if (_dehydrated !== null) {
19186 if (!didSuspend) {
19187 return updateDehydratedSuspenseComponent(current$$1, workInProgress, _dehydrated, prevState, renderExpirationTime);
19188 } else if (workInProgress.memoizedState !== null) {
19189 // Something suspended and we should still be in dehydrated mode.
19190 // Leave the existing child in place.
19191 workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there
19192 // but the normal suspense pass doesn't.
19193
19194 workInProgress.effectTag |= DidCapture;
19195 return null;
19196 } else {
19197 // Suspended but we should no longer be in dehydrated mode.
19198 // Therefore we now have to render the fallback. Wrap the children
19199 // in a fragment fiber to keep them separate from the fallback
19200 // children.
19201 var _nextFallbackChildren = nextProps.fallback;
19202
19203 var _primaryChildFragment = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19204 // going to render this fragment.
19205 null, mode, NoWork, null);
19206
19207 _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child
19208 // that we're not going to hydrate.
19209
19210 _primaryChildFragment.child = null;
19211
19212 if ((workInProgress.mode & BatchedMode) === NoMode) {
19213 // Outside of batched mode, we commit the effects from the
19214 // partially completed, timed-out tree, too.
19215 var _progressedChild = _primaryChildFragment.child = workInProgress.child;
19216
19217 while (_progressedChild !== null) {
19218 _progressedChild.return = _primaryChildFragment;
19219 _progressedChild = _progressedChild.sibling;
19220 }
19221 } else {
19222 // We will have dropped the effect list which contains the deletion.
19223 // We need to reconcile to delete the current child.
19224 reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
19225 } // Because primaryChildFragment is a new fiber that we're inserting as the
19226 // parent of a new tree, we need to set its treeBaseDuration.
19227
19228
19229 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19230 // treeBaseDuration is the sum of all the child tree base durations.
19231 var treeBaseDuration = 0;
19232 var hiddenChild = _primaryChildFragment.child;
19233
19234 while (hiddenChild !== null) {
19235 treeBaseDuration += hiddenChild.treeBaseDuration;
19236 hiddenChild = hiddenChild.sibling;
19237 }
19238
19239 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
19240 } // Create a fragment from the fallback children, too.
19241
19242
19243 var _fallbackChildFragment = createFiberFromFragment(_nextFallbackChildren, mode, renderExpirationTime, null);
19244
19245 _fallbackChildFragment.return = workInProgress;
19246 _primaryChildFragment.sibling = _fallbackChildFragment;
19247 _fallbackChildFragment.effectTag |= Placement;
19248 _primaryChildFragment.childExpirationTime = NoWork;
19249 workInProgress.memoizedState = SUSPENDED_MARKER;
19250 workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the
19251 // fallback children.
19252
19253 return _fallbackChildFragment;
19254 }
19255 }
19256 } // The current tree already timed out. That means each child set is
19257 // wrapped in a fragment fiber.
19258
19259
19260 var currentPrimaryChildFragment = current$$1.child;
19261 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
19262
19263 if (nextDidTimeout) {
19264 // Still timed out. Reuse the current primary children by cloning
19265 // its fragment. We're going to skip over these entirely.
19266 var _nextFallbackChildren2 = nextProps.fallback;
19267
19268 var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
19269
19270 _primaryChildFragment2.return = workInProgress;
19271
19272 if ((workInProgress.mode & BatchedMode) === NoMode) {
19273 // Outside of batched mode, we commit the effects from the
19274 // partially completed, timed-out tree, too.
19275 var _progressedState = workInProgress.memoizedState;
19276
19277 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
19278
19279 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
19280 _primaryChildFragment2.child = _progressedPrimaryChild;
19281 var _progressedChild2 = _progressedPrimaryChild;
19282
19283 while (_progressedChild2 !== null) {
19284 _progressedChild2.return = _primaryChildFragment2;
19285 _progressedChild2 = _progressedChild2.sibling;
19286 }
19287 }
19288 } // Because primaryChildFragment is a new fiber that we're inserting as the
19289 // parent of a new tree, we need to set its treeBaseDuration.
19290
19291
19292 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19293 // treeBaseDuration is the sum of all the child tree base durations.
19294 var _treeBaseDuration = 0;
19295 var _hiddenChild = _primaryChildFragment2.child;
19296
19297 while (_hiddenChild !== null) {
19298 _treeBaseDuration += _hiddenChild.treeBaseDuration;
19299 _hiddenChild = _hiddenChild.sibling;
19300 }
19301
19302 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
19303 } // Clone the fallback child fragment, too. These we'll continue
19304 // working on.
19305
19306
19307 var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2, currentFallbackChildFragment.expirationTime);
19308
19309 _fallbackChildFragment2.return = workInProgress;
19310 _primaryChildFragment2.sibling = _fallbackChildFragment2;
19311 _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19312 // fallback children.
19313
19314 workInProgress.memoizedState = SUSPENDED_MARKER;
19315 workInProgress.child = _primaryChildFragment2;
19316 return _fallbackChildFragment2;
19317 } else {
19318 // No longer suspended. Switch back to showing the primary children,
19319 // and remove the intermediate fragment fiber.
19320 var _nextPrimaryChildren = nextProps.children;
19321 var currentPrimaryChild = currentPrimaryChildFragment.child;
19322 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
19323 // children. Wait until the complete phase, after we've confirmed the
19324 // fallback is no longer needed.
19325 // TODO: Would it be better to store the fallback fragment on
19326 // the stateNode?
19327 // Continue rendering the children, like we normally do.
19328
19329 workInProgress.memoizedState = null;
19330 return workInProgress.child = primaryChild;
19331 }
19332 } else {
19333 // The current tree has not already timed out. That means the primary
19334 // children are not wrapped in a fragment fiber.
19335 var _currentPrimaryChild = current$$1.child;
19336
19337 if (nextDidTimeout) {
19338 // Timed out. Wrap the children in a fragment fiber to keep them
19339 // separate from the fallback children.
19340 var _nextFallbackChildren3 = nextProps.fallback;
19341
19342 var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
19343 // going to render this fragment.
19344 null, mode, NoWork, null);
19345
19346 _primaryChildFragment3.return = workInProgress;
19347 _primaryChildFragment3.child = _currentPrimaryChild;
19348
19349 if (_currentPrimaryChild !== null) {
19350 _currentPrimaryChild.return = _primaryChildFragment3;
19351 } // Even though we're creating a new fiber, there are no new children,
19352 // because we're reusing an already mounted tree. So we don't need to
19353 // schedule a placement.
19354 // primaryChildFragment.effectTag |= Placement;
19355
19356
19357 if ((workInProgress.mode & BatchedMode) === NoMode) {
19358 // Outside of batched mode, we commit the effects from the
19359 // partially completed, timed-out tree, too.
19360 var _progressedState2 = workInProgress.memoizedState;
19361
19362 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
19363
19364 _primaryChildFragment3.child = _progressedPrimaryChild2;
19365 var _progressedChild3 = _progressedPrimaryChild2;
19366
19367 while (_progressedChild3 !== null) {
19368 _progressedChild3.return = _primaryChildFragment3;
19369 _progressedChild3 = _progressedChild3.sibling;
19370 }
19371 } // Because primaryChildFragment is a new fiber that we're inserting as the
19372 // parent of a new tree, we need to set its treeBaseDuration.
19373
19374
19375 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
19376 // treeBaseDuration is the sum of all the child tree base durations.
19377 var _treeBaseDuration2 = 0;
19378 var _hiddenChild2 = _primaryChildFragment3.child;
19379
19380 while (_hiddenChild2 !== null) {
19381 _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
19382 _hiddenChild2 = _hiddenChild2.sibling;
19383 }
19384
19385 _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
19386 } // Create a fragment from the fallback children, too.
19387
19388
19389 var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
19390
19391 _fallbackChildFragment3.return = workInProgress;
19392 _primaryChildFragment3.sibling = _fallbackChildFragment3;
19393 _fallbackChildFragment3.effectTag |= Placement;
19394 _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
19395 // fallback children.
19396
19397 workInProgress.memoizedState = SUSPENDED_MARKER;
19398 workInProgress.child = _primaryChildFragment3;
19399 return _fallbackChildFragment3;
19400 } else {
19401 // Still haven't timed out. Continue rendering the children, like we
19402 // normally do.
19403 workInProgress.memoizedState = null;
19404 var _nextPrimaryChildren2 = nextProps.children;
19405 return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
19406 }
19407 }
19408 }
19409}
19410
19411function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
19412 // We're now not suspended nor dehydrated.
19413 workInProgress.memoizedState = null; // Retry with the full children.
19414
19415 var nextProps = workInProgress.pendingProps;
19416 var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and
19417 // that the old child gets a Deletion effect.
19418 // We could also call forceUnmountCurrentAndReconcile.
19419
19420 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19421 return workInProgress.child;
19422}
19423
19424function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderExpirationTime) {
19425 // During the first pass, we'll bail out and not drill into the children.
19426 // Instead, we'll leave the content in place and try to hydrate it later.
19427 if ((workInProgress.mode & BatchedMode) === NoMode) {
19428 {
19429 warning$1(false, 'Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOM.createSyncRoot(container, { hydrate: true })' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
19430 }
19431
19432 workInProgress.expirationTime = Sync;
19433 } else if (isSuspenseInstanceFallback(suspenseInstance)) {
19434 // This is a client-only boundary. Since we won't get any content from the server
19435 // for this, we need to schedule that at a higher priority based on when it would
19436 // have timed out. In theory we could render it in this pass but it would have the
19437 // wrong priority associated with it and will prevent hydration of parent path.
19438 // Instead, we'll leave work left on it to render it in a separate commit.
19439 // TODO This time should be the time at which the server rendered response that is
19440 // a parent to this boundary was displayed. However, since we currently don't have
19441 // a protocol to transfer that time, we'll just estimate it by using the current
19442 // time. This will mean that Suspense timeouts are slightly shifted to later than
19443 // they should be.
19444 var serverDisplayTime = requestCurrentTimeForUpdate(); // Schedule a normal pri update to render this content.
19445
19446 var newExpirationTime = computeAsyncExpiration(serverDisplayTime);
19447
19448 if (enableSchedulerTracing) {
19449 markSpawnedWork(newExpirationTime);
19450 }
19451
19452 workInProgress.expirationTime = newExpirationTime;
19453 } else {
19454 // We'll continue hydrating the rest at offscreen priority since we'll already
19455 // be showing the right content coming from the server, it is no rush.
19456 workInProgress.expirationTime = Never;
19457
19458 if (enableSchedulerTracing) {
19459 markSpawnedWork(Never);
19460 }
19461 }
19462
19463 return null;
19464}
19465
19466function updateDehydratedSuspenseComponent(current$$1, workInProgress, suspenseInstance, suspenseState, renderExpirationTime) {
19467 // We should never be hydrating at this point because it is the first pass,
19468 // but after we've already committed once.
19469 warnIfHydrating();
19470
19471 if ((workInProgress.mode & BatchedMode) === NoMode) {
19472 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19473 }
19474
19475 if (isSuspenseInstanceFallback(suspenseInstance)) {
19476 // This boundary is in a permanent fallback state. In this case, we'll never
19477 // get an update and we'll never be able to hydrate the final content. Let's just try the
19478 // client side render instead.
19479 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19480 } // We use childExpirationTime to indicate that a child might depend on context, so if
19481 // any context has changed, we need to treat is as if the input might have changed.
19482
19483
19484 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
19485
19486 if (didReceiveUpdate || hasContextChanged$$1) {
19487 // This boundary has changed since the first render. This means that we are now unable to
19488 // hydrate it. We might still be able to hydrate it using an earlier expiration time, if
19489 // we are rendering at lower expiration than sync.
19490 if (renderExpirationTime < Sync) {
19491 if (suspenseState.retryTime <= renderExpirationTime) {
19492 // This render is even higher pri than we've seen before, let's try again
19493 // at even higher pri.
19494 var attemptHydrationAtExpirationTime = renderExpirationTime + 1;
19495 suspenseState.retryTime = attemptHydrationAtExpirationTime;
19496 scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render.
19497 } else {// We have already tried to ping at a higher priority than we're rendering with
19498 // so if we got here, we must have failed to hydrate at those levels. We must
19499 // now give up. Instead, we're going to delete the whole subtree and instead inject
19500 // a new real Suspense boundary to take its place, which may render content
19501 // or fallback. This might suspend for a while and if it does we might still have
19502 // an opportunity to hydrate before this pass commits.
19503 }
19504 } // If we have scheduled higher pri work above, this will probably just abort the render
19505 // since we now have higher priority work, but in case it doesn't, we need to prepare to
19506 // render something, if we time out. Even if that requires us to delete everything and
19507 // skip hydration.
19508 // Delay having to do this as long as the suspense timeout allows us.
19509
19510
19511 renderDidSuspendDelayIfPossible();
19512 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
19513 } else if (isSuspenseInstancePending(suspenseInstance)) {
19514 // This component is still pending more data from the server, so we can't hydrate its
19515 // content. We treat it as if this component suspended itself. It might seem as if
19516 // we could just try to render it client-side instead. However, this will perform a
19517 // lot of unnecessary work and is unlikely to complete since it often will suspend
19518 // on missing data anyway. Additionally, the server might be able to render more
19519 // than we can on the client yet. In that case we'd end up with more fallback states
19520 // on the client than if we just leave it alone. If the server times out or errors
19521 // these should update this boundary to the permanent Fallback state instead.
19522 // Mark it as having captured (i.e. suspended).
19523 workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
19524
19525 workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result.
19526
19527 registerSuspenseInstanceRetry(suspenseInstance, retryDehydratedSuspenseBoundary.bind(null, current$$1));
19528 return null;
19529 } else {
19530 // This is the first attempt.
19531 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance);
19532 var nextProps = workInProgress.pendingProps;
19533 var nextChildren = nextProps.children;
19534 var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19535 var node = child;
19536
19537 while (node) {
19538 // Mark each child as hydrating. This is a fast path to know whether this
19539 // tree is part of a hydrating tree. This is used to determine if a child
19540 // node has fully mounted yet, and for scheduling event replaying.
19541 // Conceptually this is similar to Placement in that a new subtree is
19542 // inserted into the React tree here. It just happens to not need DOM
19543 // mutations because it already exists.
19544 node.effectTag |= Hydrating;
19545 node = node.sibling;
19546 }
19547
19548 workInProgress.child = child;
19549 return workInProgress.child;
19550 }
19551}
19552
19553function scheduleWorkOnFiber(fiber, renderExpirationTime) {
19554 if (fiber.expirationTime < renderExpirationTime) {
19555 fiber.expirationTime = renderExpirationTime;
19556 }
19557
19558 var alternate = fiber.alternate;
19559
19560 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
19561 alternate.expirationTime = renderExpirationTime;
19562 }
19563
19564 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
19565}
19566
19567function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
19568 // Mark any Suspense boundaries with fallbacks as having work to do.
19569 // If they were previously forced into fallbacks, they may now be able
19570 // to unblock.
19571 var node = firstChild;
19572
19573 while (node !== null) {
19574 if (node.tag === SuspenseComponent) {
19575 var state = node.memoizedState;
19576
19577 if (state !== null) {
19578 scheduleWorkOnFiber(node, renderExpirationTime);
19579 }
19580 } else if (node.tag === SuspenseListComponent) {
19581 // If the tail is hidden there might not be an Suspense boundaries
19582 // to schedule work on. In this case we have to schedule it on the
19583 // list itself.
19584 // We don't have to traverse to the children of the list since
19585 // the list will propagate the change when it rerenders.
19586 scheduleWorkOnFiber(node, renderExpirationTime);
19587 } else if (node.child !== null) {
19588 node.child.return = node;
19589 node = node.child;
19590 continue;
19591 }
19592
19593 if (node === workInProgress) {
19594 return;
19595 }
19596
19597 while (node.sibling === null) {
19598 if (node.return === null || node.return === workInProgress) {
19599 return;
19600 }
19601
19602 node = node.return;
19603 }
19604
19605 node.sibling.return = node.return;
19606 node = node.sibling;
19607 }
19608}
19609
19610function findLastContentRow(firstChild) {
19611 // This is going to find the last row among these children that is already
19612 // showing content on the screen, as opposed to being in fallback state or
19613 // new. If a row has multiple Suspense boundaries, any of them being in the
19614 // fallback state, counts as the whole row being in a fallback state.
19615 // Note that the "rows" will be workInProgress, but any nested children
19616 // will still be current since we haven't rendered them yet. The mounted
19617 // order may not be the same as the new order. We use the new order.
19618 var row = firstChild;
19619 var lastContentRow = null;
19620
19621 while (row !== null) {
19622 var currentRow = row.alternate; // New rows can't be content rows.
19623
19624 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19625 lastContentRow = row;
19626 }
19627
19628 row = row.sibling;
19629 }
19630
19631 return lastContentRow;
19632}
19633
19634function validateRevealOrder(revealOrder) {
19635 {
19636 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
19637 didWarnAboutRevealOrder[revealOrder] = true;
19638
19639 if (typeof revealOrder === 'string') {
19640 switch (revealOrder.toLowerCase()) {
19641 case 'together':
19642 case 'forwards':
19643 case 'backwards':
19644 {
19645 warning$1(false, '"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
19646 break;
19647 }
19648
19649 case 'forward':
19650 case 'backward':
19651 {
19652 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());
19653 break;
19654 }
19655
19656 default:
19657 warning$1(false, '"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19658 break;
19659 }
19660 } else {
19661 warning$1(false, '%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
19662 }
19663 }
19664 }
19665}
19666
19667function validateTailOptions(tailMode, revealOrder) {
19668 {
19669 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
19670 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
19671 didWarnAboutTailOptions[tailMode] = true;
19672 warning$1(false, '"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
19673 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
19674 didWarnAboutTailOptions[tailMode] = true;
19675 warning$1(false, '<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
19676 }
19677 }
19678 }
19679}
19680
19681function validateSuspenseListNestedChild(childSlot, index) {
19682 {
19683 var isArray = Array.isArray(childSlot);
19684 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
19685
19686 if (isArray || isIterable) {
19687 var type = isArray ? 'array' : 'iterable';
19688 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);
19689 return false;
19690 }
19691 }
19692
19693 return true;
19694}
19695
19696function validateSuspenseListChildren(children, revealOrder) {
19697 {
19698 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
19699 if (Array.isArray(children)) {
19700 for (var i = 0; i < children.length; i++) {
19701 if (!validateSuspenseListNestedChild(children[i], i)) {
19702 return;
19703 }
19704 }
19705 } else {
19706 var iteratorFn = getIteratorFn(children);
19707
19708 if (typeof iteratorFn === 'function') {
19709 var childrenIterator = iteratorFn.call(children);
19710
19711 if (childrenIterator) {
19712 var step = childrenIterator.next();
19713 var _i = 0;
19714
19715 for (; !step.done; step = childrenIterator.next()) {
19716 if (!validateSuspenseListNestedChild(step.value, _i)) {
19717 return;
19718 }
19719
19720 _i++;
19721 }
19722 }
19723 } else {
19724 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);
19725 }
19726 }
19727 }
19728 }
19729}
19730
19731function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
19732 var renderState = workInProgress.memoizedState;
19733
19734 if (renderState === null) {
19735 workInProgress.memoizedState = {
19736 isBackwards: isBackwards,
19737 rendering: null,
19738 last: lastContentRow,
19739 tail: tail,
19740 tailExpiration: 0,
19741 tailMode: tailMode,
19742 lastEffect: lastEffectBeforeRendering
19743 };
19744 } else {
19745 // We can reuse the existing object from previous renders.
19746 renderState.isBackwards = isBackwards;
19747 renderState.rendering = null;
19748 renderState.last = lastContentRow;
19749 renderState.tail = tail;
19750 renderState.tailExpiration = 0;
19751 renderState.tailMode = tailMode;
19752 renderState.lastEffect = lastEffectBeforeRendering;
19753 }
19754} // This can end up rendering this component multiple passes.
19755// The first pass splits the children fibers into two sets. A head and tail.
19756// We first render the head. If anything is in fallback state, we do another
19757// pass through beginWork to rerender all children (including the tail) with
19758// the force suspend context. If the first render didn't have anything in
19759// in fallback state. Then we render each row in the tail one-by-one.
19760// That happens in the completeWork phase without going back to beginWork.
19761
19762
19763function updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime) {
19764 var nextProps = workInProgress.pendingProps;
19765 var revealOrder = nextProps.revealOrder;
19766 var tailMode = nextProps.tail;
19767 var newChildren = nextProps.children;
19768 validateRevealOrder(revealOrder);
19769 validateTailOptions(tailMode, revealOrder);
19770 validateSuspenseListChildren(newChildren, revealOrder);
19771 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19772 var suspenseContext = suspenseStackCursor.current;
19773 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
19774
19775 if (shouldForceFallback) {
19776 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
19777 workInProgress.effectTag |= DidCapture;
19778 } else {
19779 var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect;
19780
19781 if (didSuspendBefore) {
19782 // If we previously forced a fallback, we need to schedule work
19783 // on any nested boundaries to let them know to try to render
19784 // again. This is the same as context updating.
19785 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
19786 }
19787
19788 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
19789 }
19790
19791 pushSuspenseContext(workInProgress, suspenseContext);
19792
19793 if ((workInProgress.mode & BatchedMode) === NoMode) {
19794 // Outside of batched mode, SuspenseList doesn't work so we just
19795 // use make it a noop by treating it as the default revealOrder.
19796 workInProgress.memoizedState = null;
19797 } else {
19798 switch (revealOrder) {
19799 case 'forwards':
19800 {
19801 var lastContentRow = findLastContentRow(workInProgress.child);
19802 var tail;
19803
19804 if (lastContentRow === null) {
19805 // The whole list is part of the tail.
19806 // TODO: We could fast path by just rendering the tail now.
19807 tail = workInProgress.child;
19808 workInProgress.child = null;
19809 } else {
19810 // Disconnect the tail rows after the content row.
19811 // We're going to render them separately later.
19812 tail = lastContentRow.sibling;
19813 lastContentRow.sibling = null;
19814 }
19815
19816 initSuspenseListRenderState(workInProgress, false, // isBackwards
19817 tail, lastContentRow, tailMode, workInProgress.lastEffect);
19818 break;
19819 }
19820
19821 case 'backwards':
19822 {
19823 // We're going to find the first row that has existing content.
19824 // At the same time we're going to reverse the list of everything
19825 // we pass in the meantime. That's going to be our tail in reverse
19826 // order.
19827 var _tail = null;
19828 var row = workInProgress.child;
19829 workInProgress.child = null;
19830
19831 while (row !== null) {
19832 var currentRow = row.alternate; // New rows can't be content rows.
19833
19834 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
19835 // This is the beginning of the main content.
19836 workInProgress.child = row;
19837 break;
19838 }
19839
19840 var nextRow = row.sibling;
19841 row.sibling = _tail;
19842 _tail = row;
19843 row = nextRow;
19844 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
19845
19846
19847 initSuspenseListRenderState(workInProgress, true, // isBackwards
19848 _tail, null, // last
19849 tailMode, workInProgress.lastEffect);
19850 break;
19851 }
19852
19853 case 'together':
19854 {
19855 initSuspenseListRenderState(workInProgress, false, // isBackwards
19856 null, // tail
19857 null, // last
19858 undefined, workInProgress.lastEffect);
19859 break;
19860 }
19861
19862 default:
19863 {
19864 // The default reveal order is the same as not having
19865 // a boundary.
19866 workInProgress.memoizedState = null;
19867 }
19868 }
19869 }
19870
19871 return workInProgress.child;
19872}
19873
19874function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
19875 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
19876 var nextChildren = workInProgress.pendingProps;
19877
19878 if (current$$1 === null) {
19879 // Portals are special because we don't append the children during mount
19880 // but at commit. Therefore we need to track insertions which the normal
19881 // flow doesn't do during mount. This doesn't happen at the root because
19882 // the root always starts with a "current" with a null child.
19883 // TODO: Consider unifying this with how the root works.
19884 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
19885 } else {
19886 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19887 }
19888
19889 return workInProgress.child;
19890}
19891
19892function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
19893 var providerType = workInProgress.type;
19894 var context = providerType._context;
19895 var newProps = workInProgress.pendingProps;
19896 var oldProps = workInProgress.memoizedProps;
19897 var newValue = newProps.value;
19898
19899 {
19900 var providerPropTypes = workInProgress.type.propTypes;
19901
19902 if (providerPropTypes) {
19903 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
19904 }
19905 }
19906
19907 pushProvider(workInProgress, newValue);
19908
19909 if (oldProps !== null) {
19910 var oldValue = oldProps.value;
19911 var changedBits = calculateChangedBits(context, newValue, oldValue);
19912
19913 if (changedBits === 0) {
19914 // No change. Bailout early if children are the same.
19915 if (oldProps.children === newProps.children && !hasContextChanged()) {
19916 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
19917 }
19918 } else {
19919 // The context value changed. Search for matching consumers and schedule
19920 // them to update.
19921 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
19922 }
19923 }
19924
19925 var newChildren = newProps.children;
19926 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19927 return workInProgress.child;
19928}
19929
19930var hasWarnedAboutUsingContextAsConsumer = false;
19931
19932function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
19933 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
19934 // DEV mode, we create a separate object for Context.Consumer that acts
19935 // like a proxy to Context. This proxy object adds unnecessary code in PROD
19936 // so we use the old behaviour (Context.Consumer references Context) to
19937 // reduce size and overhead. The separate object references context via
19938 // a property called "_context", which also gives us the ability to check
19939 // in DEV mode if this property exists or not and warn if it does not.
19940
19941 {
19942 if (context._context === undefined) {
19943 // This may be because it's a Context (rather than a Consumer).
19944 // Or it may be because it's older React where they're the same thing.
19945 // We only want to warn if we're sure it's a new React.
19946 if (context !== context.Consumer) {
19947 if (!hasWarnedAboutUsingContextAsConsumer) {
19948 hasWarnedAboutUsingContextAsConsumer = true;
19949 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?');
19950 }
19951 }
19952 } else {
19953 context = context._context;
19954 }
19955 }
19956
19957 var newProps = workInProgress.pendingProps;
19958 var render = newProps.children;
19959
19960 {
19961 !(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;
19962 }
19963
19964 prepareToReadContext(workInProgress, renderExpirationTime);
19965 var newValue = readContext(context, newProps.unstable_observedBits);
19966 var newChildren;
19967
19968 {
19969 ReactCurrentOwner$3.current = workInProgress;
19970 setCurrentPhase('render');
19971 newChildren = render(newValue);
19972 setCurrentPhase(null);
19973 } // React DevTools reads this flag.
19974
19975
19976 workInProgress.effectTag |= PerformedWork;
19977 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
19978 return workInProgress.child;
19979}
19980
19981function updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime) {
19982 var fundamentalImpl = workInProgress.type.impl;
19983
19984 if (fundamentalImpl.reconcileChildren === false) {
19985 return null;
19986 }
19987
19988 var nextProps = workInProgress.pendingProps;
19989 var nextChildren = nextProps.children;
19990 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19991 return workInProgress.child;
19992}
19993
19994function updateScopeComponent(current$$1, workInProgress, renderExpirationTime) {
19995 var nextProps = workInProgress.pendingProps;
19996 var nextChildren = nextProps.children;
19997 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
19998 return workInProgress.child;
19999}
20000
20001function markWorkInProgressReceivedUpdate() {
20002 didReceiveUpdate = true;
20003}
20004
20005function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
20006 cancelWorkTimer(workInProgress);
20007
20008 if (current$$1 !== null) {
20009 // Reuse previous dependencies
20010 workInProgress.dependencies = current$$1.dependencies;
20011 }
20012
20013 if (enableProfilerTimer) {
20014 // Don't update "base" render times for bailouts.
20015 stopProfilerTimerIfRunning(workInProgress);
20016 }
20017
20018 var updateExpirationTime = workInProgress.expirationTime;
20019
20020 if (updateExpirationTime !== NoWork) {
20021 markUnprocessedUpdateTime(updateExpirationTime);
20022 } // Check if the children have any pending work.
20023
20024
20025 var childExpirationTime = workInProgress.childExpirationTime;
20026
20027 if (childExpirationTime < renderExpirationTime) {
20028 // The children don't have any work either. We can skip them.
20029 // TODO: Once we add back resuming, we should check if the children are
20030 // a work-in-progress set. If so, we need to transfer their effects.
20031 return null;
20032 } else {
20033 // This fiber doesn't have work, but its subtree does. Clone the child
20034 // fibers and continue.
20035 cloneChildFibers(current$$1, workInProgress);
20036 return workInProgress.child;
20037 }
20038}
20039
20040function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) {
20041 {
20042 var returnFiber = oldWorkInProgress.return;
20043
20044 if (returnFiber === null) {
20045 throw new Error('Cannot swap the root fiber.');
20046 } // Disconnect from the old current.
20047 // It will get deleted.
20048
20049
20050 current$$1.alternate = null;
20051 oldWorkInProgress.alternate = null; // Connect to the new tree.
20052
20053 newWorkInProgress.index = oldWorkInProgress.index;
20054 newWorkInProgress.sibling = oldWorkInProgress.sibling;
20055 newWorkInProgress.return = oldWorkInProgress.return;
20056 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
20057
20058 if (oldWorkInProgress === returnFiber.child) {
20059 returnFiber.child = newWorkInProgress;
20060 } else {
20061 var prevSibling = returnFiber.child;
20062
20063 if (prevSibling === null) {
20064 throw new Error('Expected parent to have a child.');
20065 }
20066
20067 while (prevSibling.sibling !== oldWorkInProgress) {
20068 prevSibling = prevSibling.sibling;
20069
20070 if (prevSibling === null) {
20071 throw new Error('Expected to find the previous sibling.');
20072 }
20073 }
20074
20075 prevSibling.sibling = newWorkInProgress;
20076 } // Delete the old fiber and place the new one.
20077 // Since the old fiber is disconnected, we have to schedule it manually.
20078
20079
20080 var last = returnFiber.lastEffect;
20081
20082 if (last !== null) {
20083 last.nextEffect = current$$1;
20084 returnFiber.lastEffect = current$$1;
20085 } else {
20086 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
20087 }
20088
20089 current$$1.nextEffect = null;
20090 current$$1.effectTag = Deletion;
20091 newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
20092
20093 return newWorkInProgress;
20094 }
20095}
20096
20097function beginWork$1(current$$1, workInProgress, renderExpirationTime) {
20098 var updateExpirationTime = workInProgress.expirationTime;
20099
20100 {
20101 if (workInProgress._debugNeedsRemount && current$$1 !== null) {
20102 // This will restart the begin phase with a new fiber.
20103 return remountFiber(current$$1, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
20104 }
20105 }
20106
20107 if (current$$1 !== null) {
20108 var oldProps = current$$1.memoizedProps;
20109 var newProps = workInProgress.pendingProps;
20110
20111 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
20112 workInProgress.type !== current$$1.type)) {
20113 // If props or context changed, mark the fiber as having performed work.
20114 // This may be unset if the props are determined to be equal later (memo).
20115 didReceiveUpdate = true;
20116 } else if (updateExpirationTime < renderExpirationTime) {
20117 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
20118 // the begin phase. There's still some bookkeeping we that needs to be done
20119 // in this optimized path, mostly pushing stuff onto the stack.
20120
20121 switch (workInProgress.tag) {
20122 case HostRoot:
20123 pushHostRootContext(workInProgress);
20124 resetHydrationState();
20125 break;
20126
20127 case HostComponent:
20128 pushHostContext(workInProgress);
20129
20130 if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
20131 if (enableSchedulerTracing) {
20132 markSpawnedWork(Never);
20133 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
20134
20135
20136 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
20137 return null;
20138 }
20139
20140 break;
20141
20142 case ClassComponent:
20143 {
20144 var Component = workInProgress.type;
20145
20146 if (isContextProvider(Component)) {
20147 pushContextProvider(workInProgress);
20148 }
20149
20150 break;
20151 }
20152
20153 case HostPortal:
20154 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
20155 break;
20156
20157 case ContextProvider:
20158 {
20159 var newValue = workInProgress.memoizedProps.value;
20160 pushProvider(workInProgress, newValue);
20161 break;
20162 }
20163
20164 case Profiler:
20165 if (enableProfilerTimer) {
20166 workInProgress.effectTag |= Update;
20167 }
20168
20169 break;
20170
20171 case SuspenseComponent:
20172 {
20173 var state = workInProgress.memoizedState;
20174
20175 if (state !== null) {
20176 if (enableSuspenseServerRenderer) {
20177 if (state.dehydrated !== null) {
20178 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
20179 // been unsuspended it has committed as a resolved Suspense component.
20180 // If it needs to be retried, it should have work scheduled on it.
20181
20182 workInProgress.effectTag |= DidCapture;
20183 break;
20184 }
20185 } // If this boundary is currently timed out, we need to decide
20186 // whether to retry the primary children, or to skip over it and
20187 // go straight to the fallback. Check the priority of the primary
20188 // child fragment.
20189
20190
20191 var primaryChildFragment = workInProgress.child;
20192 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
20193
20194 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
20195 // The primary children have pending work. Use the normal path
20196 // to attempt to render the primary children again.
20197 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20198 } else {
20199 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
20200 // priority. Bailout.
20201
20202 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20203
20204 if (child !== null) {
20205 // The fallback children have pending work. Skip over the
20206 // primary children and work on the fallback.
20207 return child.sibling;
20208 } else {
20209 return null;
20210 }
20211 }
20212 } else {
20213 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
20214 }
20215
20216 break;
20217 }
20218
20219 case SuspenseListComponent:
20220 {
20221 var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect;
20222 var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
20223
20224 if (didSuspendBefore) {
20225 if (hasChildWork) {
20226 // If something was in fallback state last time, and we have all the
20227 // same children then we're still in progressive loading state.
20228 // Something might get unblocked by state updates or retries in the
20229 // tree which will affect the tail. So we need to use the normal
20230 // path to compute the correct tail.
20231 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20232 } // If none of the children had any work, that means that none of
20233 // them got retried so they'll still be blocked in the same way
20234 // as before. We can fast bail out.
20235
20236
20237 workInProgress.effectTag |= DidCapture;
20238 } // If nothing suspended before and we're rendering the same children,
20239 // then the tail doesn't matter. Anything new that suspends will work
20240 // in the "together" mode, so we can continue from the state we had.
20241
20242
20243 var renderState = workInProgress.memoizedState;
20244
20245 if (renderState !== null) {
20246 // Reset to the "together" mode in case we've started a different
20247 // update in the past but didn't complete it.
20248 renderState.rendering = null;
20249 renderState.tail = null;
20250 }
20251
20252 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
20253
20254 if (hasChildWork) {
20255 break;
20256 } else {
20257 // If none of the children had any work, that means that none of
20258 // them got retried so they'll still be blocked in the same way
20259 // as before. We can fast bail out.
20260 return null;
20261 }
20262 }
20263 }
20264
20265 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
20266 } else {
20267 // An update was scheduled on this fiber, but there are no new props
20268 // nor legacy context. Set this to false. If an update queue or context
20269 // consumer produces a changed value, it will set this to true. Otherwise,
20270 // the component will assume the children have not changed and bail out.
20271 didReceiveUpdate = false;
20272 }
20273 } else {
20274 didReceiveUpdate = false;
20275 } // Before entering the begin phase, clear the expiration time.
20276
20277
20278 workInProgress.expirationTime = NoWork;
20279
20280 switch (workInProgress.tag) {
20281 case IndeterminateComponent:
20282 {
20283 return mountIndeterminateComponent(current$$1, workInProgress, workInProgress.type, renderExpirationTime);
20284 }
20285
20286 case LazyComponent:
20287 {
20288 var elementType = workInProgress.elementType;
20289 return mountLazyComponent(current$$1, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
20290 }
20291
20292 case FunctionComponent:
20293 {
20294 var _Component = workInProgress.type;
20295 var unresolvedProps = workInProgress.pendingProps;
20296 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
20297 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
20298 }
20299
20300 case ClassComponent:
20301 {
20302 var _Component2 = workInProgress.type;
20303 var _unresolvedProps = workInProgress.pendingProps;
20304
20305 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
20306
20307 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
20308 }
20309
20310 case HostRoot:
20311 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
20312
20313 case HostComponent:
20314 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
20315
20316 case HostText:
20317 return updateHostText(current$$1, workInProgress);
20318
20319 case SuspenseComponent:
20320 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
20321
20322 case HostPortal:
20323 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
20324
20325 case ForwardRef:
20326 {
20327 var type = workInProgress.type;
20328 var _unresolvedProps2 = workInProgress.pendingProps;
20329
20330 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
20331
20332 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
20333 }
20334
20335 case Fragment:
20336 return updateFragment(current$$1, workInProgress, renderExpirationTime);
20337
20338 case Mode:
20339 return updateMode(current$$1, workInProgress, renderExpirationTime);
20340
20341 case Profiler:
20342 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
20343
20344 case ContextProvider:
20345 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
20346
20347 case ContextConsumer:
20348 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
20349
20350 case MemoComponent:
20351 {
20352 var _type2 = workInProgress.type;
20353 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
20354
20355 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
20356
20357 {
20358 if (workInProgress.type !== workInProgress.elementType) {
20359 var outerPropTypes = _type2.propTypes;
20360
20361 if (outerPropTypes) {
20362 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
20363 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
20364 }
20365 }
20366 }
20367
20368 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
20369 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
20370 }
20371
20372 case SimpleMemoComponent:
20373 {
20374 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
20375 }
20376
20377 case IncompleteClassComponent:
20378 {
20379 var _Component3 = workInProgress.type;
20380 var _unresolvedProps4 = workInProgress.pendingProps;
20381
20382 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
20383
20384 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
20385 }
20386
20387 case SuspenseListComponent:
20388 {
20389 return updateSuspenseListComponent(current$$1, workInProgress, renderExpirationTime);
20390 }
20391
20392 case FundamentalComponent:
20393 {
20394 if (enableFundamentalAPI) {
20395 return updateFundamentalComponent$1(current$$1, workInProgress, renderExpirationTime);
20396 }
20397
20398 break;
20399 }
20400
20401 case ScopeComponent:
20402 {
20403 if (enableScopeAPI) {
20404 return updateScopeComponent(current$$1, workInProgress, renderExpirationTime);
20405 }
20406
20407 break;
20408 }
20409 }
20410
20411 {
20412 {
20413 throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
20414 }
20415 }
20416}
20417
20418function createFundamentalStateInstance(currentFiber, props, impl, state) {
20419 return {
20420 currentFiber: currentFiber,
20421 impl: impl,
20422 instance: null,
20423 prevProps: null,
20424 props: props,
20425 state: state
20426 };
20427}
20428
20429function isFiberSuspenseAndTimedOut(fiber) {
20430 return fiber.tag === SuspenseComponent && fiber.memoizedState !== null;
20431}
20432
20433function getSuspenseFallbackChild(fiber) {
20434 return fiber.child.sibling.child;
20435}
20436
20437function collectScopedNodes(node, fn, scopedNodes) {
20438 if (enableScopeAPI) {
20439 if (node.tag === HostComponent) {
20440 var _type = node.type,
20441 memoizedProps = node.memoizedProps;
20442
20443 if (fn(_type, memoizedProps) === true) {
20444 scopedNodes.push(getPublicInstance(node.stateNode));
20445 }
20446 }
20447
20448 var child = node.child;
20449
20450 if (isFiberSuspenseAndTimedOut(node)) {
20451 child = getSuspenseFallbackChild(node);
20452 }
20453
20454 if (child !== null) {
20455 collectScopedNodesFromChildren(child, fn, scopedNodes);
20456 }
20457 }
20458}
20459
20460function collectFirstScopedNode(node, fn) {
20461 if (enableScopeAPI) {
20462 if (node.tag === HostComponent) {
20463 var _type2 = node.type,
20464 memoizedProps = node.memoizedProps;
20465
20466 if (fn(_type2, memoizedProps) === true) {
20467 return getPublicInstance(node.stateNode);
20468 }
20469 }
20470
20471 var child = node.child;
20472
20473 if (isFiberSuspenseAndTimedOut(node)) {
20474 child = getSuspenseFallbackChild(node);
20475 }
20476
20477 if (child !== null) {
20478 return collectFirstScopedNodeFromChildren(child, fn);
20479 }
20480 }
20481
20482 return null;
20483}
20484
20485function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) {
20486 var child = startingChild;
20487
20488 while (child !== null) {
20489 collectScopedNodes(child, fn, scopedNodes);
20490 child = child.sibling;
20491 }
20492}
20493
20494function collectFirstScopedNodeFromChildren(startingChild, fn) {
20495 var child = startingChild;
20496
20497 while (child !== null) {
20498 var scopedNode = collectFirstScopedNode(child, fn);
20499
20500 if (scopedNode !== null) {
20501 return scopedNode;
20502 }
20503
20504 child = child.sibling;
20505 }
20506
20507 return null;
20508}
20509
20510function collectNearestScopeMethods(node, scope, childrenScopes) {
20511 if (isValidScopeNode(node, scope)) {
20512 childrenScopes.push(node.stateNode.methods);
20513 } else {
20514 var child = node.child;
20515
20516 if (isFiberSuspenseAndTimedOut(node)) {
20517 child = getSuspenseFallbackChild(node);
20518 }
20519
20520 if (child !== null) {
20521 collectNearestChildScopeMethods(child, scope, childrenScopes);
20522 }
20523 }
20524}
20525
20526function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) {
20527 var child = startingChild;
20528
20529 while (child !== null) {
20530 collectNearestScopeMethods(child, scope, childrenScopes);
20531 child = child.sibling;
20532 }
20533}
20534
20535function isValidScopeNode(node, scope) {
20536 return node.tag === ScopeComponent && node.type === scope && node.stateNode !== null;
20537}
20538
20539function createScopeMethods(scope, instance) {
20540 return {
20541 getChildren: function () {
20542 var currentFiber = instance.fiber;
20543 var child = currentFiber.child;
20544 var childrenScopes = [];
20545
20546 if (child !== null) {
20547 collectNearestChildScopeMethods(child, scope, childrenScopes);
20548 }
20549
20550 return childrenScopes.length === 0 ? null : childrenScopes;
20551 },
20552 getChildrenFromRoot: function () {
20553 var currentFiber = instance.fiber;
20554 var node = currentFiber;
20555
20556 while (node !== null) {
20557 var parent = node.return;
20558
20559 if (parent === null) {
20560 break;
20561 }
20562
20563 node = parent;
20564
20565 if (node.tag === ScopeComponent && node.type === scope) {
20566 break;
20567 }
20568 }
20569
20570 var childrenScopes = [];
20571 collectNearestChildScopeMethods(node.child, scope, childrenScopes);
20572 return childrenScopes.length === 0 ? null : childrenScopes;
20573 },
20574 getParent: function () {
20575 var node = instance.fiber.return;
20576
20577 while (node !== null) {
20578 if (node.tag === ScopeComponent && node.type === scope) {
20579 return node.stateNode.methods;
20580 }
20581
20582 node = node.return;
20583 }
20584
20585 return null;
20586 },
20587 getProps: function () {
20588 var currentFiber = instance.fiber;
20589 return currentFiber.memoizedProps;
20590 },
20591 queryAllNodes: function (fn) {
20592 var currentFiber = instance.fiber;
20593 var child = currentFiber.child;
20594 var scopedNodes = [];
20595
20596 if (child !== null) {
20597 collectScopedNodesFromChildren(child, fn, scopedNodes);
20598 }
20599
20600 return scopedNodes.length === 0 ? null : scopedNodes;
20601 },
20602 queryFirstNode: function (fn) {
20603 var currentFiber = instance.fiber;
20604 var child = currentFiber.child;
20605
20606 if (child !== null) {
20607 return collectFirstScopedNodeFromChildren(child, fn);
20608 }
20609
20610 return null;
20611 },
20612 containsNode: function (node) {
20613 var fiber = getInstanceFromNode$2(node);
20614
20615 while (fiber !== null) {
20616 if (fiber.tag === ScopeComponent && fiber.type === scope && fiber.stateNode === instance) {
20617 return true;
20618 }
20619
20620 fiber = fiber.return;
20621 }
20622
20623 return false;
20624 }
20625 };
20626}
20627
20628function markUpdate(workInProgress) {
20629 // Tag the fiber with an update effect. This turns a Placement into
20630 // a PlacementAndUpdate.
20631 workInProgress.effectTag |= Update;
20632}
20633
20634function markRef$1(workInProgress) {
20635 workInProgress.effectTag |= Ref;
20636}
20637
20638var appendAllChildren;
20639var updateHostContainer;
20640var updateHostComponent$1;
20641var updateHostText$1;
20642
20643if (supportsMutation) {
20644 // Mutation mode
20645 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20646 // We only have the top Fiber that was created but we need recurse down its
20647 // children to find all the terminal nodes.
20648 var node = workInProgress.child;
20649
20650 while (node !== null) {
20651 if (node.tag === HostComponent || node.tag === HostText) {
20652 appendInitialChild(parent, node.stateNode);
20653 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20654 appendInitialChild(parent, node.stateNode.instance);
20655 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20656 // down its children. Instead, we'll get insertions from each child in
20657 // the portal directly.
20658 } else if (node.child !== null) {
20659 node.child.return = node;
20660 node = node.child;
20661 continue;
20662 }
20663
20664 if (node === workInProgress) {
20665 return;
20666 }
20667
20668 while (node.sibling === null) {
20669 if (node.return === null || node.return === workInProgress) {
20670 return;
20671 }
20672
20673 node = node.return;
20674 }
20675
20676 node.sibling.return = node.return;
20677 node = node.sibling;
20678 }
20679 };
20680
20681 updateHostContainer = function (workInProgress) {// Noop
20682 };
20683
20684 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20685 // If we have an alternate, that means this is an update and we need to
20686 // schedule a side-effect to do the updates.
20687 var oldProps = current.memoizedProps;
20688
20689 if (oldProps === newProps) {
20690 // In mutation mode, this is sufficient for a bailout because
20691 // we won't touch this node even if children changed.
20692 return;
20693 } // If we get updated because one of our children updated, we don't
20694 // have newProps so we'll have to reuse them.
20695 // TODO: Split the update API as separate for the props vs. children.
20696 // Even better would be if children weren't special cased at all tho.
20697
20698
20699 var instance = workInProgress.stateNode;
20700 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
20701 // component is hitting the resume path. Figure out why. Possibly
20702 // related to `hidden`.
20703
20704 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
20705
20706 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
20707 // is a new ref we mark this as an update. All the work is done in commitWork.
20708
20709 if (updatePayload) {
20710 markUpdate(workInProgress);
20711 }
20712 };
20713
20714 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20715 // If the text differs, mark it as an update. All the work in done in commitWork.
20716 if (oldText !== newText) {
20717 markUpdate(workInProgress);
20718 }
20719 };
20720} else if (supportsPersistence) {
20721 // Persistent host tree mode
20722 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
20723 // We only have the top Fiber that was created but we need recurse down its
20724 // children to find all the terminal nodes.
20725 var node = workInProgress.child;
20726
20727 while (node !== null) {
20728 // eslint-disable-next-line no-labels
20729 branches: if (node.tag === HostComponent) {
20730 var instance = node.stateNode;
20731
20732 if (needsVisibilityToggle && isHidden) {
20733 // This child is inside a timed out tree. Hide it.
20734 var props = node.memoizedProps;
20735 var type = node.type;
20736 instance = cloneHiddenInstance(instance, type, props, node);
20737 }
20738
20739 appendInitialChild(parent, instance);
20740 } else if (node.tag === HostText) {
20741 var _instance = node.stateNode;
20742
20743 if (needsVisibilityToggle && isHidden) {
20744 // This child is inside a timed out tree. Hide it.
20745 var text = node.memoizedProps;
20746 _instance = cloneHiddenTextInstance(_instance, text, node);
20747 }
20748
20749 appendInitialChild(parent, _instance);
20750 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20751 var _instance2 = node.stateNode.instance;
20752
20753 if (needsVisibilityToggle && isHidden) {
20754 // This child is inside a timed out tree. Hide it.
20755 var _props = node.memoizedProps;
20756 var _type = node.type;
20757 _instance2 = cloneHiddenInstance(_instance2, _type, _props, node);
20758 }
20759
20760 appendInitialChild(parent, _instance2);
20761 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20762 // down its children. Instead, we'll get insertions from each child in
20763 // the portal directly.
20764 } else if (node.tag === SuspenseComponent) {
20765 if ((node.effectTag & Update) !== NoEffect) {
20766 // Need to toggle the visibility of the primary children.
20767 var newIsHidden = node.memoizedState !== null;
20768
20769 if (newIsHidden) {
20770 var primaryChildParent = node.child;
20771
20772 if (primaryChildParent !== null) {
20773 if (primaryChildParent.child !== null) {
20774 primaryChildParent.child.return = primaryChildParent;
20775 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
20776 }
20777
20778 var fallbackChildParent = primaryChildParent.sibling;
20779
20780 if (fallbackChildParent !== null) {
20781 fallbackChildParent.return = node;
20782 node = fallbackChildParent;
20783 continue;
20784 }
20785 }
20786 }
20787 }
20788
20789 if (node.child !== null) {
20790 // Continue traversing like normal
20791 node.child.return = node;
20792 node = node.child;
20793 continue;
20794 }
20795 } else if (node.child !== null) {
20796 node.child.return = node;
20797 node = node.child;
20798 continue;
20799 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20800
20801
20802 node = node;
20803
20804 if (node === workInProgress) {
20805 return;
20806 }
20807
20808 while (node.sibling === null) {
20809 if (node.return === null || node.return === workInProgress) {
20810 return;
20811 }
20812
20813 node = node.return;
20814 }
20815
20816 node.sibling.return = node.return;
20817 node = node.sibling;
20818 }
20819 }; // An unfortunate fork of appendAllChildren because we have two different parent types.
20820
20821
20822 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
20823 // We only have the top Fiber that was created but we need recurse down its
20824 // children to find all the terminal nodes.
20825 var node = workInProgress.child;
20826
20827 while (node !== null) {
20828 // eslint-disable-next-line no-labels
20829 branches: if (node.tag === HostComponent) {
20830 var instance = node.stateNode;
20831
20832 if (needsVisibilityToggle && isHidden) {
20833 // This child is inside a timed out tree. Hide it.
20834 var props = node.memoizedProps;
20835 var type = node.type;
20836 instance = cloneHiddenInstance(instance, type, props, node);
20837 }
20838
20839 appendChildToContainerChildSet(containerChildSet, instance);
20840 } else if (node.tag === HostText) {
20841 var _instance3 = node.stateNode;
20842
20843 if (needsVisibilityToggle && isHidden) {
20844 // This child is inside a timed out tree. Hide it.
20845 var text = node.memoizedProps;
20846 _instance3 = cloneHiddenTextInstance(_instance3, text, node);
20847 }
20848
20849 appendChildToContainerChildSet(containerChildSet, _instance3);
20850 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
20851 var _instance4 = node.stateNode.instance;
20852
20853 if (needsVisibilityToggle && isHidden) {
20854 // This child is inside a timed out tree. Hide it.
20855 var _props2 = node.memoizedProps;
20856 var _type2 = node.type;
20857 _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node);
20858 }
20859
20860 appendChildToContainerChildSet(containerChildSet, _instance4);
20861 } else if (node.tag === HostPortal) {// If we have a portal child, then we don't want to traverse
20862 // down its children. Instead, we'll get insertions from each child in
20863 // the portal directly.
20864 } else if (node.tag === SuspenseComponent) {
20865 if ((node.effectTag & Update) !== NoEffect) {
20866 // Need to toggle the visibility of the primary children.
20867 var newIsHidden = node.memoizedState !== null;
20868
20869 if (newIsHidden) {
20870 var primaryChildParent = node.child;
20871
20872 if (primaryChildParent !== null) {
20873 if (primaryChildParent.child !== null) {
20874 primaryChildParent.child.return = primaryChildParent;
20875 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
20876 }
20877
20878 var fallbackChildParent = primaryChildParent.sibling;
20879
20880 if (fallbackChildParent !== null) {
20881 fallbackChildParent.return = node;
20882 node = fallbackChildParent;
20883 continue;
20884 }
20885 }
20886 }
20887 }
20888
20889 if (node.child !== null) {
20890 // Continue traversing like normal
20891 node.child.return = node;
20892 node = node.child;
20893 continue;
20894 }
20895 } else if (node.child !== null) {
20896 node.child.return = node;
20897 node = node.child;
20898 continue;
20899 } // $FlowFixMe This is correct but Flow is confused by the labeled break.
20900
20901
20902 node = node;
20903
20904 if (node === workInProgress) {
20905 return;
20906 }
20907
20908 while (node.sibling === null) {
20909 if (node.return === null || node.return === workInProgress) {
20910 return;
20911 }
20912
20913 node = node.return;
20914 }
20915
20916 node.sibling.return = node.return;
20917 node = node.sibling;
20918 }
20919 };
20920
20921 updateHostContainer = function (workInProgress) {
20922 var portalOrRoot = workInProgress.stateNode;
20923 var childrenUnchanged = workInProgress.firstEffect === null;
20924
20925 if (childrenUnchanged) {// No changes, just reuse the existing instance.
20926 } else {
20927 var container = portalOrRoot.containerInfo;
20928 var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set.
20929
20930 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
20931 portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container.
20932
20933 markUpdate(workInProgress);
20934 finalizeContainerChildren(container, newChildSet);
20935 }
20936 };
20937
20938 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
20939 var currentInstance = current.stateNode;
20940 var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates.
20941 // This guarantees that we can reuse all of them.
20942
20943 var childrenUnchanged = workInProgress.firstEffect === null;
20944
20945 if (childrenUnchanged && oldProps === newProps) {
20946 // No changes, just reuse the existing instance.
20947 // Note that this might release a previous clone.
20948 workInProgress.stateNode = currentInstance;
20949 return;
20950 }
20951
20952 var recyclableInstance = workInProgress.stateNode;
20953 var currentHostContext = getHostContext();
20954 var updatePayload = null;
20955
20956 if (oldProps !== newProps) {
20957 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
20958 }
20959
20960 if (childrenUnchanged && updatePayload === null) {
20961 // No changes, just reuse the existing instance.
20962 // Note that this might release a previous clone.
20963 workInProgress.stateNode = currentInstance;
20964 return;
20965 }
20966
20967 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
20968
20969 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
20970 markUpdate(workInProgress);
20971 }
20972
20973 workInProgress.stateNode = newInstance;
20974
20975 if (childrenUnchanged) {
20976 // If there are no other effects in this tree, we need to flag this node as having one.
20977 // Even though we're not going to use it for anything.
20978 // Otherwise parents won't know that there are new children to propagate upwards.
20979 markUpdate(workInProgress);
20980 } else {
20981 // If children might have changed, we have to add them all to the set.
20982 appendAllChildren(newInstance, workInProgress, false, false);
20983 }
20984 };
20985
20986 updateHostText$1 = function (current, workInProgress, oldText, newText) {
20987 if (oldText !== newText) {
20988 // If the text content differs, we'll create a new text instance for it.
20989 var rootContainerInstance = getRootHostContainer();
20990 var currentHostContext = getHostContext();
20991 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.
20992 // This lets the parents know that at least one of their children has changed.
20993
20994 markUpdate(workInProgress);
20995 }
20996 };
20997} else {
20998 // No host operations
20999 updateHostContainer = function (workInProgress) {// Noop
21000 };
21001
21002 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {// Noop
21003 };
21004
21005 updateHostText$1 = function (current, workInProgress, oldText, newText) {// Noop
21006 };
21007}
21008
21009function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
21010 switch (renderState.tailMode) {
21011 case 'hidden':
21012 {
21013 // Any insertions at the end of the tail list after this point
21014 // should be invisible. If there are already mounted boundaries
21015 // anything before them are not considered for collapsing.
21016 // Therefore we need to go through the whole tail to find if
21017 // there are any.
21018 var tailNode = renderState.tail;
21019 var lastTailNode = null;
21020
21021 while (tailNode !== null) {
21022 if (tailNode.alternate !== null) {
21023 lastTailNode = tailNode;
21024 }
21025
21026 tailNode = tailNode.sibling;
21027 } // Next we're simply going to delete all insertions after the
21028 // last rendered item.
21029
21030
21031 if (lastTailNode === null) {
21032 // All remaining items in the tail are insertions.
21033 renderState.tail = null;
21034 } else {
21035 // Detach the insertion after the last node that was already
21036 // inserted.
21037 lastTailNode.sibling = null;
21038 }
21039
21040 break;
21041 }
21042
21043 case 'collapsed':
21044 {
21045 // Any insertions at the end of the tail list after this point
21046 // should be invisible. If there are already mounted boundaries
21047 // anything before them are not considered for collapsing.
21048 // Therefore we need to go through the whole tail to find if
21049 // there are any.
21050 var _tailNode = renderState.tail;
21051 var _lastTailNode = null;
21052
21053 while (_tailNode !== null) {
21054 if (_tailNode.alternate !== null) {
21055 _lastTailNode = _tailNode;
21056 }
21057
21058 _tailNode = _tailNode.sibling;
21059 } // Next we're simply going to delete all insertions after the
21060 // last rendered item.
21061
21062
21063 if (_lastTailNode === null) {
21064 // All remaining items in the tail are insertions.
21065 if (!hasRenderedATailFallback && renderState.tail !== null) {
21066 // We suspended during the head. We want to show at least one
21067 // row at the tail. So we'll keep on and cut off the rest.
21068 renderState.tail.sibling = null;
21069 } else {
21070 renderState.tail = null;
21071 }
21072 } else {
21073 // Detach the insertion after the last node that was already
21074 // inserted.
21075 _lastTailNode.sibling = null;
21076 }
21077
21078 break;
21079 }
21080 }
21081}
21082
21083function completeWork(current, workInProgress, renderExpirationTime) {
21084 var newProps = workInProgress.pendingProps;
21085
21086 switch (workInProgress.tag) {
21087 case IndeterminateComponent:
21088 break;
21089
21090 case LazyComponent:
21091 break;
21092
21093 case SimpleMemoComponent:
21094 case FunctionComponent:
21095 break;
21096
21097 case ClassComponent:
21098 {
21099 var Component = workInProgress.type;
21100
21101 if (isContextProvider(Component)) {
21102 popContext(workInProgress);
21103 }
21104
21105 break;
21106 }
21107
21108 case HostRoot:
21109 {
21110 popHostContainer(workInProgress);
21111 popTopLevelContextObject(workInProgress);
21112 var fiberRoot = workInProgress.stateNode;
21113
21114 if (fiberRoot.pendingContext) {
21115 fiberRoot.context = fiberRoot.pendingContext;
21116 fiberRoot.pendingContext = null;
21117 }
21118
21119 if (current === null || current.child === null) {
21120 // If we hydrated, pop so that we can delete any remaining children
21121 // that weren't hydrated.
21122 var wasHydrated = popHydrationState(workInProgress);
21123
21124 if (wasHydrated) {
21125 // If we hydrated, then we'll need to schedule an update for
21126 // the commit side-effects on the root.
21127 markUpdate(workInProgress);
21128 }
21129 }
21130
21131 updateHostContainer(workInProgress);
21132 break;
21133 }
21134
21135 case HostComponent:
21136 {
21137 popHostContext(workInProgress);
21138 var rootContainerInstance = getRootHostContainer();
21139 var type = workInProgress.type;
21140
21141 if (current !== null && workInProgress.stateNode != null) {
21142 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
21143
21144 if (enableFlareAPI) {
21145 var prevListeners = current.memoizedProps.listeners;
21146 var nextListeners = newProps.listeners;
21147
21148 if (prevListeners !== nextListeners) {
21149 markUpdate(workInProgress);
21150 }
21151 }
21152
21153 if (current.ref !== workInProgress.ref) {
21154 markRef$1(workInProgress);
21155 }
21156 } else {
21157 if (!newProps) {
21158 if (!(workInProgress.stateNode !== null)) {
21159 {
21160 throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
21161 }
21162 } // This can happen when we abort work.
21163
21164
21165 break;
21166 }
21167
21168 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
21169 // "stack" as the parent. Then append children as we go in beginWork
21170 // or completeWork depending on we want to add then top->down or
21171 // bottom->up. Top->down is faster in IE11.
21172
21173 var _wasHydrated = popHydrationState(workInProgress);
21174
21175 if (_wasHydrated) {
21176 // TODO: Move this and createInstance step into the beginPhase
21177 // to consolidate.
21178 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
21179 // If changes to the hydrated node needs to be applied at the
21180 // commit-phase we mark this as such.
21181 markUpdate(workInProgress);
21182 }
21183
21184 if (enableFlareAPI) {
21185 var listeners = newProps.listeners;
21186
21187 if (listeners != null) {
21188 updateEventListeners(listeners, workInProgress, rootContainerInstance);
21189 }
21190 }
21191 } else {
21192 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
21193 appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
21194
21195 workInProgress.stateNode = instance;
21196
21197 if (enableFlareAPI) {
21198 var _listeners = newProps.listeners;
21199
21200 if (_listeners != null) {
21201 updateEventListeners(_listeners, workInProgress, rootContainerInstance);
21202 }
21203 } // Certain renderers require commit-time effects for initial mount.
21204 // (eg DOM renderer supports auto-focus for certain elements).
21205 // Make sure such renderers get scheduled for later work.
21206
21207
21208 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
21209 markUpdate(workInProgress);
21210 }
21211 }
21212
21213 if (workInProgress.ref !== null) {
21214 // If there is a ref on a host node we need to schedule a callback
21215 markRef$1(workInProgress);
21216 }
21217 }
21218
21219 break;
21220 }
21221
21222 case HostText:
21223 {
21224 var newText = newProps;
21225
21226 if (current && workInProgress.stateNode != null) {
21227 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
21228 // to schedule a side-effect to do the updates.
21229
21230 updateHostText$1(current, workInProgress, oldText, newText);
21231 } else {
21232 if (typeof newText !== 'string') {
21233 if (!(workInProgress.stateNode !== null)) {
21234 {
21235 throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
21236 }
21237 } // This can happen when we abort work.
21238
21239 }
21240
21241 var _rootContainerInstance = getRootHostContainer();
21242
21243 var _currentHostContext = getHostContext();
21244
21245 var _wasHydrated2 = popHydrationState(workInProgress);
21246
21247 if (_wasHydrated2) {
21248 if (prepareToHydrateHostTextInstance(workInProgress)) {
21249 markUpdate(workInProgress);
21250 }
21251 } else {
21252 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
21253 }
21254 }
21255
21256 break;
21257 }
21258
21259 case ForwardRef:
21260 break;
21261
21262 case SuspenseComponent:
21263 {
21264 popSuspenseContext(workInProgress);
21265 var nextState = workInProgress.memoizedState;
21266
21267 if (enableSuspenseServerRenderer) {
21268 if (nextState !== null && nextState.dehydrated !== null) {
21269 if (current === null) {
21270 var _wasHydrated3 = popHydrationState(workInProgress);
21271
21272 if (!_wasHydrated3) {
21273 {
21274 throw Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.");
21275 }
21276 }
21277
21278 prepareToHydrateHostSuspenseInstance(workInProgress);
21279
21280 if (enableSchedulerTracing) {
21281 markSpawnedWork(Never);
21282 }
21283
21284 return null;
21285 } else {
21286 // We should never have been in a hydration state if we didn't have a current.
21287 // However, in some of those paths, we might have reentered a hydration state
21288 // and then we might be inside a hydration state. In that case, we'll need to
21289 // exit out of it.
21290 resetHydrationState();
21291
21292 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
21293 // This boundary did not suspend so it's now hydrated and unsuspended.
21294 workInProgress.memoizedState = null;
21295 } // If nothing suspended, we need to schedule an effect to mark this boundary
21296 // as having hydrated so events know that they're free be invoked.
21297 // It's also a signal to replay events and the suspense callback.
21298 // If something suspended, schedule an effect to attach retry listeners.
21299 // So we might as well always mark this.
21300
21301
21302 workInProgress.effectTag |= Update;
21303 return null;
21304 }
21305 }
21306 }
21307
21308 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
21309 // Something suspended. Re-render with the fallback children.
21310 workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
21311
21312 return workInProgress;
21313 }
21314
21315 var nextDidTimeout = nextState !== null;
21316 var prevDidTimeout = false;
21317
21318 if (current === null) {
21319 if (workInProgress.memoizedProps.fallback !== undefined) {
21320 popHydrationState(workInProgress);
21321 }
21322 } else {
21323 var prevState = current.memoizedState;
21324 prevDidTimeout = prevState !== null;
21325
21326 if (!nextDidTimeout && prevState !== null) {
21327 // We just switched from the fallback to the normal children.
21328 // Delete the fallback.
21329 // TODO: Would it be better to store the fallback fragment on
21330 // the stateNode during the begin phase?
21331 var currentFallbackChild = current.child.sibling;
21332
21333 if (currentFallbackChild !== null) {
21334 // Deletions go at the beginning of the return fiber's effect list
21335 var first = workInProgress.firstEffect;
21336
21337 if (first !== null) {
21338 workInProgress.firstEffect = currentFallbackChild;
21339 currentFallbackChild.nextEffect = first;
21340 } else {
21341 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
21342 currentFallbackChild.nextEffect = null;
21343 }
21344
21345 currentFallbackChild.effectTag = Deletion;
21346 }
21347 }
21348 }
21349
21350 if (nextDidTimeout && !prevDidTimeout) {
21351 // If this subtreee is running in batched mode we can suspend,
21352 // otherwise we won't suspend.
21353 // TODO: This will still suspend a synchronous tree if anything
21354 // in the concurrent tree already suspended during this render.
21355 // This is a known bug.
21356 if ((workInProgress.mode & BatchedMode) !== NoMode) {
21357 // TODO: Move this back to throwException because this is too late
21358 // if this is a large tree which is common for initial loads. We
21359 // don't know if we should restart a render or not until we get
21360 // this marker, and this is too late.
21361 // If this render already had a ping or lower pri updates,
21362 // and this is the first time we know we're going to suspend we
21363 // should be able to immediately restart from within throwException.
21364 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
21365
21366 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
21367 // If this was in an invisible tree or a new render, then showing
21368 // this boundary is ok.
21369 renderDidSuspend();
21370 } else {
21371 // Otherwise, we're going to have to hide content so we should
21372 // suspend for longer if possible.
21373 renderDidSuspendDelayIfPossible();
21374 }
21375 }
21376 }
21377
21378 if (supportsPersistence) {
21379 // TODO: Only schedule updates if not prevDidTimeout.
21380 if (nextDidTimeout) {
21381 // If this boundary just timed out, schedule an effect to attach a
21382 // retry listener to the proimse. This flag is also used to hide the
21383 // primary children.
21384 workInProgress.effectTag |= Update;
21385 }
21386 }
21387
21388 if (supportsMutation) {
21389 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
21390 if (nextDidTimeout || prevDidTimeout) {
21391 // If this boundary just timed out, schedule an effect to attach a
21392 // retry listener to the proimse. This flag is also used to hide the
21393 // primary children. In mutation mode, we also need the flag to
21394 // *unhide* children that were previously hidden, so check if the
21395 // is currently timed out, too.
21396 workInProgress.effectTag |= Update;
21397 }
21398 }
21399
21400 if (enableSuspenseCallback && workInProgress.updateQueue !== null && workInProgress.memoizedProps.suspenseCallback != null) {
21401 // Always notify the callback
21402 workInProgress.effectTag |= Update;
21403 }
21404
21405 break;
21406 }
21407
21408 case Fragment:
21409 break;
21410
21411 case Mode:
21412 break;
21413
21414 case Profiler:
21415 break;
21416
21417 case HostPortal:
21418 popHostContainer(workInProgress);
21419 updateHostContainer(workInProgress);
21420 break;
21421
21422 case ContextProvider:
21423 // Pop provider fiber
21424 popProvider(workInProgress);
21425 break;
21426
21427 case ContextConsumer:
21428 break;
21429
21430 case MemoComponent:
21431 break;
21432
21433 case IncompleteClassComponent:
21434 {
21435 // Same as class component case. I put it down here so that the tags are
21436 // sequential to ensure this switch is compiled to a jump table.
21437 var _Component = workInProgress.type;
21438
21439 if (isContextProvider(_Component)) {
21440 popContext(workInProgress);
21441 }
21442
21443 break;
21444 }
21445
21446 case SuspenseListComponent:
21447 {
21448 popSuspenseContext(workInProgress);
21449 var renderState = workInProgress.memoizedState;
21450
21451 if (renderState === null) {
21452 // We're running in the default, "independent" mode. We don't do anything
21453 // in this mode.
21454 break;
21455 }
21456
21457 var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
21458 var renderedTail = renderState.rendering;
21459
21460 if (renderedTail === null) {
21461 // We just rendered the head.
21462 if (!didSuspendAlready) {
21463 // This is the first pass. We need to figure out if anything is still
21464 // suspended in the rendered set.
21465 // If new content unsuspended, but there's still some content that
21466 // didn't. Then we need to do a second pass that forces everything
21467 // to keep showing their fallbacks.
21468 // We might be suspended if something in this render pass suspended, or
21469 // something in the previous committed pass suspended. Otherwise,
21470 // there's no chance so we can skip the expensive call to
21471 // findFirstSuspended.
21472 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
21473
21474 if (!cannotBeSuspended) {
21475 var row = workInProgress.child;
21476
21477 while (row !== null) {
21478 var suspended = findFirstSuspended(row);
21479
21480 if (suspended !== null) {
21481 didSuspendAlready = true;
21482 workInProgress.effectTag |= DidCapture;
21483 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
21484 // part of the second pass. In that case nothing will subscribe to
21485 // its thennables. Instead, we'll transfer its thennables to the
21486 // SuspenseList so that it can retry if they resolve.
21487 // There might be multiple of these in the list but since we're
21488 // going to wait for all of them anyway, it doesn't really matter
21489 // which ones gets to ping. In theory we could get clever and keep
21490 // track of how many dependencies remain but it gets tricky because
21491 // in the meantime, we can add/remove/change items and dependencies.
21492 // We might bail out of the loop before finding any but that
21493 // doesn't matter since that means that the other boundaries that
21494 // we did find already has their listeners attached.
21495
21496 var newThennables = suspended.updateQueue;
21497
21498 if (newThennables !== null) {
21499 workInProgress.updateQueue = newThennables;
21500 workInProgress.effectTag |= Update;
21501 } // Rerender the whole list, but this time, we'll force fallbacks
21502 // to stay in place.
21503 // Reset the effect list before doing the second pass since that's now invalid.
21504
21505
21506 if (renderState.lastEffect === null) {
21507 workInProgress.firstEffect = null;
21508 }
21509
21510 workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.
21511
21512 resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
21513 // rerender the children.
21514
21515 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
21516 return workInProgress.child;
21517 }
21518
21519 row = row.sibling;
21520 }
21521 }
21522 } else {
21523 cutOffTailIfNeeded(renderState, false);
21524 } // Next we're going to render the tail.
21525
21526 } else {
21527 // Append the rendered row to the child list.
21528 if (!didSuspendAlready) {
21529 var _suspended = findFirstSuspended(renderedTail);
21530
21531 if (_suspended !== null) {
21532 workInProgress.effectTag |= DidCapture;
21533 didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
21534 // get lost if this row ends up dropped during a second pass.
21535
21536 var _newThennables = _suspended.updateQueue;
21537
21538 if (_newThennables !== null) {
21539 workInProgress.updateQueue = _newThennables;
21540 workInProgress.effectTag |= Update;
21541 }
21542
21543 cutOffTailIfNeeded(renderState, true); // This might have been modified.
21544
21545 if (renderState.tail === null && renderState.tailMode === 'hidden') {
21546 // We need to delete the row we just rendered.
21547 // Reset the effect list to what it w as before we rendered this
21548 // child. The nested children have already appended themselves.
21549 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
21550
21551 if (lastEffect !== null) {
21552 lastEffect.nextEffect = null;
21553 } // We're done.
21554
21555
21556 return null;
21557 }
21558 } else if (now() > renderState.tailExpiration && renderExpirationTime > Never) {
21559 // We have now passed our CPU deadline and we'll just give up further
21560 // attempts to render the main content and only render fallbacks.
21561 // The assumption is that this is usually faster.
21562 workInProgress.effectTag |= DidCapture;
21563 didSuspendAlready = true;
21564 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
21565 // to get it started back up to attempt the next item. If we can show
21566 // them, then they really have the same priority as this render.
21567 // So we'll pick it back up the very next render pass once we've had
21568 // an opportunity to yield for paint.
21569
21570 var nextPriority = renderExpirationTime - 1;
21571 workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
21572
21573 if (enableSchedulerTracing) {
21574 markSpawnedWork(nextPriority);
21575 }
21576 }
21577 }
21578
21579 if (renderState.isBackwards) {
21580 // The effect list of the backwards tail will have been added
21581 // to the end. This breaks the guarantee that life-cycles fire in
21582 // sibling order but that isn't a strong guarantee promised by React.
21583 // Especially since these might also just pop in during future commits.
21584 // Append to the beginning of the list.
21585 renderedTail.sibling = workInProgress.child;
21586 workInProgress.child = renderedTail;
21587 } else {
21588 var previousSibling = renderState.last;
21589
21590 if (previousSibling !== null) {
21591 previousSibling.sibling = renderedTail;
21592 } else {
21593 workInProgress.child = renderedTail;
21594 }
21595
21596 renderState.last = renderedTail;
21597 }
21598 }
21599
21600 if (renderState.tail !== null) {
21601 // We still have tail rows to render.
21602 if (renderState.tailExpiration === 0) {
21603 // Heuristic for how long we're willing to spend rendering rows
21604 // until we just give up and show what we have so far.
21605 var TAIL_EXPIRATION_TIMEOUT_MS = 500;
21606 renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
21607 } // Pop a row.
21608
21609
21610 var next = renderState.tail;
21611 renderState.rendering = next;
21612 renderState.tail = next.sibling;
21613 renderState.lastEffect = workInProgress.lastEffect;
21614 next.sibling = null; // Restore the context.
21615 // TODO: We can probably just avoid popping it instead and only
21616 // setting it the first time we go from not suspended to suspended.
21617
21618 var suspenseContext = suspenseStackCursor.current;
21619
21620 if (didSuspendAlready) {
21621 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21622 } else {
21623 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21624 }
21625
21626 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
21627
21628 return next;
21629 }
21630
21631 break;
21632 }
21633
21634 case FundamentalComponent:
21635 {
21636 if (enableFundamentalAPI) {
21637 var fundamentalImpl = workInProgress.type.impl;
21638 var fundamentalInstance = workInProgress.stateNode;
21639
21640 if (fundamentalInstance === null) {
21641 var getInitialState = fundamentalImpl.getInitialState;
21642 var fundamentalState;
21643
21644 if (getInitialState !== undefined) {
21645 fundamentalState = getInitialState(newProps);
21646 }
21647
21648 fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(workInProgress, newProps, fundamentalImpl, fundamentalState || {});
21649
21650 var _instance5 = getFundamentalComponentInstance(fundamentalInstance);
21651
21652 fundamentalInstance.instance = _instance5;
21653
21654 if (fundamentalImpl.reconcileChildren === false) {
21655 return null;
21656 }
21657
21658 appendAllChildren(_instance5, workInProgress, false, false);
21659 mountFundamentalComponent(fundamentalInstance);
21660 } else {
21661 // We fire update in commit phase
21662 var prevProps = fundamentalInstance.props;
21663 fundamentalInstance.prevProps = prevProps;
21664 fundamentalInstance.props = newProps;
21665 fundamentalInstance.currentFiber = workInProgress;
21666
21667 if (supportsPersistence) {
21668 var _instance6 = cloneFundamentalInstance(fundamentalInstance);
21669
21670 fundamentalInstance.instance = _instance6;
21671 appendAllChildren(_instance6, workInProgress, false, false);
21672 }
21673
21674 var shouldUpdate = shouldUpdateFundamentalComponent(fundamentalInstance);
21675
21676 if (shouldUpdate) {
21677 markUpdate(workInProgress);
21678 }
21679 }
21680 }
21681
21682 break;
21683 }
21684
21685 case ScopeComponent:
21686 {
21687 if (enableScopeAPI) {
21688 if (current === null) {
21689 var _type3 = workInProgress.type;
21690 var scopeInstance = {
21691 fiber: workInProgress,
21692 methods: null
21693 };
21694 workInProgress.stateNode = scopeInstance;
21695 scopeInstance.methods = createScopeMethods(_type3, scopeInstance);
21696
21697 if (enableFlareAPI) {
21698 var _listeners2 = newProps.listeners;
21699
21700 if (_listeners2 != null) {
21701 var _rootContainerInstance2 = getRootHostContainer();
21702
21703 updateEventListeners(_listeners2, workInProgress, _rootContainerInstance2);
21704 }
21705 }
21706
21707 if (workInProgress.ref !== null) {
21708 markRef$1(workInProgress);
21709 markUpdate(workInProgress);
21710 }
21711 } else {
21712 if (enableFlareAPI) {
21713 var _prevListeners = current.memoizedProps.listeners;
21714 var _nextListeners = newProps.listeners;
21715
21716 if (_prevListeners !== _nextListeners || workInProgress.ref !== null) {
21717 markUpdate(workInProgress);
21718 }
21719 } else {
21720 if (workInProgress.ref !== null) {
21721 markUpdate(workInProgress);
21722 }
21723 }
21724
21725 if (current.ref !== workInProgress.ref) {
21726 markRef$1(workInProgress);
21727 }
21728 }
21729 }
21730
21731 break;
21732 }
21733
21734 default:
21735 {
21736 {
21737 throw Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue.");
21738 }
21739 }
21740
21741 }
21742
21743 return null;
21744}
21745
21746function unwindWork(workInProgress, renderExpirationTime) {
21747 switch (workInProgress.tag) {
21748 case ClassComponent:
21749 {
21750 var Component = workInProgress.type;
21751
21752 if (isContextProvider(Component)) {
21753 popContext(workInProgress);
21754 }
21755
21756 var effectTag = workInProgress.effectTag;
21757
21758 if (effectTag & ShouldCapture) {
21759 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
21760 return workInProgress;
21761 }
21762
21763 return null;
21764 }
21765
21766 case HostRoot:
21767 {
21768 popHostContainer(workInProgress);
21769 popTopLevelContextObject(workInProgress);
21770 var _effectTag = workInProgress.effectTag;
21771
21772 if (!((_effectTag & DidCapture) === NoEffect)) {
21773 {
21774 throw Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue.");
21775 }
21776 }
21777
21778 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
21779 return workInProgress;
21780 }
21781
21782 case HostComponent:
21783 {
21784 // TODO: popHydrationState
21785 popHostContext(workInProgress);
21786 return null;
21787 }
21788
21789 case SuspenseComponent:
21790 {
21791 popSuspenseContext(workInProgress);
21792
21793 if (enableSuspenseServerRenderer) {
21794 var suspenseState = workInProgress.memoizedState;
21795
21796 if (suspenseState !== null && suspenseState.dehydrated !== null) {
21797 if (!(workInProgress.alternate !== null)) {
21798 {
21799 throw Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue.");
21800 }
21801 }
21802
21803 resetHydrationState();
21804 }
21805 }
21806
21807 var _effectTag2 = workInProgress.effectTag;
21808
21809 if (_effectTag2 & ShouldCapture) {
21810 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
21811
21812 return workInProgress;
21813 }
21814
21815 return null;
21816 }
21817
21818 case SuspenseListComponent:
21819 {
21820 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
21821 // caught by a nested boundary. If not, it should bubble through.
21822
21823 return null;
21824 }
21825
21826 case HostPortal:
21827 popHostContainer(workInProgress);
21828 return null;
21829
21830 case ContextProvider:
21831 popProvider(workInProgress);
21832 return null;
21833
21834 default:
21835 return null;
21836 }
21837}
21838
21839function unwindInterruptedWork(interruptedWork) {
21840 switch (interruptedWork.tag) {
21841 case ClassComponent:
21842 {
21843 var childContextTypes = interruptedWork.type.childContextTypes;
21844
21845 if (childContextTypes !== null && childContextTypes !== undefined) {
21846 popContext(interruptedWork);
21847 }
21848
21849 break;
21850 }
21851
21852 case HostRoot:
21853 {
21854 popHostContainer(interruptedWork);
21855 popTopLevelContextObject(interruptedWork);
21856 break;
21857 }
21858
21859 case HostComponent:
21860 {
21861 popHostContext(interruptedWork);
21862 break;
21863 }
21864
21865 case HostPortal:
21866 popHostContainer(interruptedWork);
21867 break;
21868
21869 case SuspenseComponent:
21870 popSuspenseContext(interruptedWork);
21871 break;
21872
21873 case SuspenseListComponent:
21874 popSuspenseContext(interruptedWork);
21875 break;
21876
21877 case ContextProvider:
21878 popProvider(interruptedWork);
21879 break;
21880
21881 default:
21882 break;
21883 }
21884}
21885
21886function createCapturedValue(value, source) {
21887 // If the value is an error, call this function immediately after it is thrown
21888 // so the stack is accurate.
21889 return {
21890 value: value,
21891 source: source,
21892 stack: getStackByFiberInDevAndProd(source)
21893 };
21894}
21895
21896// This module is forked in different environments.
21897// By default, return `true` to log errors to the console.
21898// Forks can return `false` if this isn't desirable.
21899function showErrorDialog(capturedError) {
21900 return true;
21901}
21902
21903function logCapturedError(capturedError) {
21904 var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging.
21905 // This enables renderers like ReactNative to better manage redbox behavior.
21906
21907 if (logError === false) {
21908 return;
21909 }
21910
21911 var error = capturedError.error;
21912
21913 {
21914 var componentName = capturedError.componentName,
21915 componentStack = capturedError.componentStack,
21916 errorBoundaryName = capturedError.errorBoundaryName,
21917 errorBoundaryFound = capturedError.errorBoundaryFound,
21918 willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
21919 // `preventDefault()` in window `error` handler.
21920 // We record this information as an expando on the error.
21921
21922 if (error != null && error._suppressLogging) {
21923 if (errorBoundaryFound && willRetry) {
21924 // The error is recoverable and was silenced.
21925 // Ignore it and don't print the stack addendum.
21926 // This is handy for testing error boundaries without noise.
21927 return;
21928 } // The error is fatal. Since the silencing might have
21929 // been accidental, we'll surface it anyway.
21930 // However, the browser would have silenced the original error
21931 // so we'll print it first, and then print the stack addendum.
21932
21933
21934 console.error(error); // For a more detailed description of this block, see:
21935 // https://github.com/facebook/react/pull/13384
21936 }
21937
21938 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
21939 var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
21940
21941 if (errorBoundaryFound && errorBoundaryName) {
21942 if (willRetry) {
21943 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
21944 } else {
21945 errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
21946 }
21947 } else {
21948 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.';
21949 }
21950
21951 var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
21952 // We don't include the original error message and JS stack because the browser
21953 // has already printed it. Even if the application swallows the error, it is still
21954 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
21955
21956 console.error(combinedMessage);
21957 }
21958}
21959
21960var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
21961
21962{
21963 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
21964}
21965
21966var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
21967function logError(boundary, errorInfo) {
21968 var source = errorInfo.source;
21969 var stack = errorInfo.stack;
21970
21971 if (stack === null && source !== null) {
21972 stack = getStackByFiberInDevAndProd(source);
21973 }
21974
21975 var capturedError = {
21976 componentName: source !== null ? getComponentName(source.type) : null,
21977 componentStack: stack !== null ? stack : '',
21978 error: errorInfo.value,
21979 errorBoundary: null,
21980 errorBoundaryName: null,
21981 errorBoundaryFound: false,
21982 willRetry: false
21983 };
21984
21985 if (boundary !== null && boundary.tag === ClassComponent) {
21986 capturedError.errorBoundary = boundary.stateNode;
21987 capturedError.errorBoundaryName = getComponentName(boundary.type);
21988 capturedError.errorBoundaryFound = true;
21989 capturedError.willRetry = true;
21990 }
21991
21992 try {
21993 logCapturedError(capturedError);
21994 } catch (e) {
21995 // This method must not throw, or React internal state will get messed up.
21996 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
21997 // we want to report this error outside of the normal stack as a last resort.
21998 // https://github.com/facebook/react/issues/13188
21999 setTimeout(function () {
22000 throw e;
22001 });
22002 }
22003}
22004
22005var callComponentWillUnmountWithTimer = function (current$$1, instance) {
22006 startPhaseTimer(current$$1, 'componentWillUnmount');
22007 instance.props = current$$1.memoizedProps;
22008 instance.state = current$$1.memoizedState;
22009 instance.componentWillUnmount();
22010 stopPhaseTimer();
22011}; // Capture errors so they don't interrupt unmounting.
22012
22013
22014function safelyCallComponentWillUnmount(current$$1, instance) {
22015 {
22016 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
22017
22018 if (hasCaughtError()) {
22019 var unmountError = clearCaughtError();
22020 captureCommitPhaseError(current$$1, unmountError);
22021 }
22022 }
22023}
22024
22025function safelyDetachRef(current$$1) {
22026 var ref = current$$1.ref;
22027
22028 if (ref !== null) {
22029 if (typeof ref === 'function') {
22030 {
22031 invokeGuardedCallback(null, ref, null, null);
22032
22033 if (hasCaughtError()) {
22034 var refError = clearCaughtError();
22035 captureCommitPhaseError(current$$1, refError);
22036 }
22037 }
22038 } else {
22039 ref.current = null;
22040 }
22041 }
22042}
22043
22044function safelyCallDestroy(current$$1, destroy) {
22045 {
22046 invokeGuardedCallback(null, destroy, null);
22047
22048 if (hasCaughtError()) {
22049 var error = clearCaughtError();
22050 captureCommitPhaseError(current$$1, error);
22051 }
22052 }
22053}
22054
22055function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
22056 switch (finishedWork.tag) {
22057 case FunctionComponent:
22058 case ForwardRef:
22059 case SimpleMemoComponent:
22060 {
22061 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
22062 return;
22063 }
22064
22065 case ClassComponent:
22066 {
22067 if (finishedWork.effectTag & Snapshot) {
22068 if (current$$1 !== null) {
22069 var prevProps = current$$1.memoizedProps;
22070 var prevState = current$$1.memoizedState;
22071 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
22072 var instance = finishedWork.stateNode; // We could update instance props and state here,
22073 // but instead we rely on them being set during last render.
22074 // TODO: revisit this when we implement resuming.
22075
22076 {
22077 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22078 !(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;
22079 !(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;
22080 }
22081 }
22082
22083 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
22084
22085 {
22086 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
22087
22088 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
22089 didWarnSet.add(finishedWork.type);
22090 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
22091 }
22092 }
22093
22094 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
22095 stopPhaseTimer();
22096 }
22097 }
22098
22099 return;
22100 }
22101
22102 case HostRoot:
22103 case HostComponent:
22104 case HostText:
22105 case HostPortal:
22106 case IncompleteClassComponent:
22107 // Nothing to do for these component types
22108 return;
22109
22110 default:
22111 {
22112 {
22113 {
22114 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.");
22115 }
22116 }
22117 }
22118 }
22119}
22120
22121function commitHookEffectList(unmountTag, mountTag, finishedWork) {
22122 var updateQueue = finishedWork.updateQueue;
22123 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
22124
22125 if (lastEffect !== null) {
22126 var firstEffect = lastEffect.next;
22127 var effect = firstEffect;
22128
22129 do {
22130 if ((effect.tag & unmountTag) !== NoEffect$1) {
22131 // Unmount
22132 var destroy = effect.destroy;
22133 effect.destroy = undefined;
22134
22135 if (destroy !== undefined) {
22136 destroy();
22137 }
22138 }
22139
22140 if ((effect.tag & mountTag) !== NoEffect$1) {
22141 // Mount
22142 var create = effect.create;
22143 effect.destroy = create();
22144
22145 {
22146 var _destroy = effect.destroy;
22147
22148 if (_destroy !== undefined && typeof _destroy !== 'function') {
22149 var addendum = void 0;
22150
22151 if (_destroy === null) {
22152 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
22153 } else if (typeof _destroy.then === 'function') {
22154 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';
22155 } else {
22156 addendum = ' You returned: ' + _destroy;
22157 }
22158
22159 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
22160 }
22161 }
22162 }
22163
22164 effect = effect.next;
22165 } while (effect !== firstEffect);
22166 }
22167}
22168
22169function commitPassiveHookEffects(finishedWork) {
22170 if ((finishedWork.effectTag & Passive) !== NoEffect) {
22171 switch (finishedWork.tag) {
22172 case FunctionComponent:
22173 case ForwardRef:
22174 case SimpleMemoComponent:
22175 {
22176 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
22177 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
22178 break;
22179 }
22180
22181 default:
22182 break;
22183 }
22184 }
22185}
22186
22187function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
22188 switch (finishedWork.tag) {
22189 case FunctionComponent:
22190 case ForwardRef:
22191 case SimpleMemoComponent:
22192 {
22193 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
22194 break;
22195 }
22196
22197 case ClassComponent:
22198 {
22199 var instance = finishedWork.stateNode;
22200
22201 if (finishedWork.effectTag & Update) {
22202 if (current$$1 === null) {
22203 startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
22204 // but instead we rely on them being set during last render.
22205 // TODO: revisit this when we implement resuming.
22206
22207 {
22208 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22209 !(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;
22210 !(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;
22211 }
22212 }
22213
22214 instance.componentDidMount();
22215 stopPhaseTimer();
22216 } else {
22217 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
22218 var prevState = current$$1.memoizedState;
22219 startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
22220 // but instead we rely on them being set during last render.
22221 // TODO: revisit this when we implement resuming.
22222
22223 {
22224 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22225 !(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;
22226 !(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;
22227 }
22228 }
22229
22230 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
22231 stopPhaseTimer();
22232 }
22233 }
22234
22235 var updateQueue = finishedWork.updateQueue;
22236
22237 if (updateQueue !== null) {
22238 {
22239 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
22240 !(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;
22241 !(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;
22242 }
22243 } // We could update instance props and state here,
22244 // but instead we rely on them being set during last render.
22245 // TODO: revisit this when we implement resuming.
22246
22247
22248 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
22249 }
22250
22251 return;
22252 }
22253
22254 case HostRoot:
22255 {
22256 var _updateQueue = finishedWork.updateQueue;
22257
22258 if (_updateQueue !== null) {
22259 var _instance = null;
22260
22261 if (finishedWork.child !== null) {
22262 switch (finishedWork.child.tag) {
22263 case HostComponent:
22264 _instance = getPublicInstance(finishedWork.child.stateNode);
22265 break;
22266
22267 case ClassComponent:
22268 _instance = finishedWork.child.stateNode;
22269 break;
22270 }
22271 }
22272
22273 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
22274 }
22275
22276 return;
22277 }
22278
22279 case HostComponent:
22280 {
22281 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
22282 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
22283 // These effects should only be committed when components are first mounted,
22284 // aka when there is no current/alternate.
22285
22286 if (current$$1 === null && finishedWork.effectTag & Update) {
22287 var type = finishedWork.type;
22288 var props = finishedWork.memoizedProps;
22289 commitMount(_instance2, type, props, finishedWork);
22290 }
22291
22292 return;
22293 }
22294
22295 case HostText:
22296 {
22297 // We have no life-cycles associated with text.
22298 return;
22299 }
22300
22301 case HostPortal:
22302 {
22303 // We have no life-cycles associated with portals.
22304 return;
22305 }
22306
22307 case Profiler:
22308 {
22309 if (enableProfilerTimer) {
22310 var onRender = finishedWork.memoizedProps.onRender;
22311
22312 if (typeof onRender === 'function') {
22313 if (enableSchedulerTracing) {
22314 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
22315 } else {
22316 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
22317 }
22318 }
22319 }
22320
22321 return;
22322 }
22323
22324 case SuspenseComponent:
22325 {
22326 commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
22327 return;
22328 }
22329
22330 case SuspenseListComponent:
22331 case IncompleteClassComponent:
22332 case FundamentalComponent:
22333 case ScopeComponent:
22334 return;
22335
22336 default:
22337 {
22338 {
22339 {
22340 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.");
22341 }
22342 }
22343 }
22344 }
22345}
22346
22347function hideOrUnhideAllChildren(finishedWork, isHidden) {
22348 if (supportsMutation) {
22349 // We only have the top Fiber that was inserted but we need to recurse down its
22350 // children to find all the terminal nodes.
22351 var node = finishedWork;
22352
22353 while (true) {
22354 if (node.tag === HostComponent) {
22355 var instance = node.stateNode;
22356
22357 if (isHidden) {
22358 hideInstance(instance);
22359 } else {
22360 unhideInstance(node.stateNode, node.memoizedProps);
22361 }
22362 } else if (node.tag === HostText) {
22363 var _instance3 = node.stateNode;
22364
22365 if (isHidden) {
22366 hideTextInstance(_instance3);
22367 } else {
22368 unhideTextInstance(_instance3, node.memoizedProps);
22369 }
22370 } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
22371 // Found a nested Suspense component that timed out. Skip over the
22372 // primary child fragment, which should remain hidden.
22373 var fallbackChildFragment = node.child.sibling;
22374 fallbackChildFragment.return = node;
22375 node = fallbackChildFragment;
22376 continue;
22377 } else if (node.child !== null) {
22378 node.child.return = node;
22379 node = node.child;
22380 continue;
22381 }
22382
22383 if (node === finishedWork) {
22384 return;
22385 }
22386
22387 while (node.sibling === null) {
22388 if (node.return === null || node.return === finishedWork) {
22389 return;
22390 }
22391
22392 node = node.return;
22393 }
22394
22395 node.sibling.return = node.return;
22396 node = node.sibling;
22397 }
22398 }
22399}
22400
22401function commitAttachRef(finishedWork) {
22402 var ref = finishedWork.ref;
22403
22404 if (ref !== null) {
22405 var instance = finishedWork.stateNode;
22406 var instanceToUse;
22407
22408 switch (finishedWork.tag) {
22409 case HostComponent:
22410 instanceToUse = getPublicInstance(instance);
22411 break;
22412
22413 default:
22414 instanceToUse = instance;
22415 } // Moved outside to ensure DCE works with this flag
22416
22417
22418 if (enableScopeAPI && finishedWork.tag === ScopeComponent) {
22419 instanceToUse = instance.methods;
22420 }
22421
22422 if (typeof ref === 'function') {
22423 ref(instanceToUse);
22424 } else {
22425 {
22426 if (!ref.hasOwnProperty('current')) {
22427 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
22428 }
22429 }
22430
22431 ref.current = instanceToUse;
22432 }
22433 }
22434}
22435
22436function commitDetachRef(current$$1) {
22437 var currentRef = current$$1.ref;
22438
22439 if (currentRef !== null) {
22440 if (typeof currentRef === 'function') {
22441 currentRef(null);
22442 } else {
22443 currentRef.current = null;
22444 }
22445 }
22446} // User-originating errors (lifecycles and refs) should not interrupt
22447// deletion, so don't let them throw. Host-originating errors should
22448// interrupt deletion, so it's okay
22449
22450
22451function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) {
22452 onCommitUnmount(current$$1);
22453
22454 switch (current$$1.tag) {
22455 case FunctionComponent:
22456 case ForwardRef:
22457 case MemoComponent:
22458 case SimpleMemoComponent:
22459 {
22460 var updateQueue = current$$1.updateQueue;
22461
22462 if (updateQueue !== null) {
22463 var lastEffect = updateQueue.lastEffect;
22464
22465 if (lastEffect !== null) {
22466 var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive
22467 // effect hook is called during the synchronous commit phase. This is
22468 // a concession to implementation complexity. Calling it in the
22469 // passive effect phase (like they usually are, when dependencies
22470 // change during an update) would require either traversing the
22471 // children of the deleted fiber again, or including unmount effects
22472 // as part of the fiber effect list.
22473 //
22474 // Because this is during the sync commit phase, we need to change
22475 // the priority.
22476 //
22477 // TODO: Reconsider this implementation trade off.
22478
22479 var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
22480 runWithPriority$2(priorityLevel, function () {
22481 var effect = firstEffect;
22482
22483 do {
22484 var destroy = effect.destroy;
22485
22486 if (destroy !== undefined) {
22487 safelyCallDestroy(current$$1, destroy);
22488 }
22489
22490 effect = effect.next;
22491 } while (effect !== firstEffect);
22492 });
22493 }
22494 }
22495
22496 break;
22497 }
22498
22499 case ClassComponent:
22500 {
22501 safelyDetachRef(current$$1);
22502 var instance = current$$1.stateNode;
22503
22504 if (typeof instance.componentWillUnmount === 'function') {
22505 safelyCallComponentWillUnmount(current$$1, instance);
22506 }
22507
22508 return;
22509 }
22510
22511 case HostComponent:
22512 {
22513 if (enableFlareAPI) {
22514 var dependencies = current$$1.dependencies;
22515
22516 if (dependencies !== null) {
22517 var respondersMap = dependencies.responders;
22518
22519 if (respondersMap !== null) {
22520 var responderInstances = Array.from(respondersMap.values());
22521
22522 for (var i = 0, length = responderInstances.length; i < length; i++) {
22523 var responderInstance = responderInstances[i];
22524 unmountResponderInstance(responderInstance);
22525 }
22526
22527 dependencies.responders = null;
22528 }
22529 }
22530 }
22531
22532 safelyDetachRef(current$$1);
22533 return;
22534 }
22535
22536 case HostPortal:
22537 {
22538 // TODO: this is recursive.
22539 // We are also not using this parent because
22540 // the portal will get pushed immediately.
22541 if (supportsMutation) {
22542 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
22543 } else if (supportsPersistence) {
22544 emptyPortalContainer(current$$1);
22545 }
22546
22547 return;
22548 }
22549
22550 case FundamentalComponent:
22551 {
22552 if (enableFundamentalAPI) {
22553 var fundamentalInstance = current$$1.stateNode;
22554
22555 if (fundamentalInstance !== null) {
22556 unmountFundamentalComponent(fundamentalInstance);
22557 current$$1.stateNode = null;
22558 }
22559 }
22560
22561 return;
22562 }
22563
22564 case DehydratedFragment:
22565 {
22566 if (enableSuspenseCallback) {
22567 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22568
22569 if (hydrationCallbacks !== null) {
22570 var onDeleted = hydrationCallbacks.onDeleted;
22571
22572 if (onDeleted) {
22573 onDeleted(current$$1.stateNode);
22574 }
22575 }
22576 }
22577
22578 return;
22579 }
22580
22581 case ScopeComponent:
22582 {
22583 if (enableScopeAPI) {
22584 safelyDetachRef(current$$1);
22585 }
22586 }
22587 }
22588}
22589
22590function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
22591 // While we're inside a removed host node we don't want to call
22592 // removeChild on the inner nodes because they're removed by the top
22593 // call anyway. We also want to call componentWillUnmount on all
22594 // composites before this host node is removed from the tree. Therefore
22595 // we do an inner loop while we're still inside the host node.
22596 var node = root;
22597
22598 while (true) {
22599 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
22600 // Skip portals because commitUnmount() currently visits them recursively.
22601
22602 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
22603 // If we don't use mutation we drill down into portals here instead.
22604 !supportsMutation || node.tag !== HostPortal)) {
22605 node.child.return = node;
22606 node = node.child;
22607 continue;
22608 }
22609
22610 if (node === root) {
22611 return;
22612 }
22613
22614 while (node.sibling === null) {
22615 if (node.return === null || node.return === root) {
22616 return;
22617 }
22618
22619 node = node.return;
22620 }
22621
22622 node.sibling.return = node.return;
22623 node = node.sibling;
22624 }
22625}
22626
22627function detachFiber(current$$1) {
22628 var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
22629 // should clear the child pointer of the parent alternate to let this
22630 // get GC:ed but we don't know which for sure which parent is the current
22631 // one so we'll settle for GC:ing the subtree of this child. This child
22632 // itself will be GC:ed when the parent updates the next time.
22633
22634 current$$1.return = null;
22635 current$$1.child = null;
22636 current$$1.memoizedState = null;
22637 current$$1.updateQueue = null;
22638 current$$1.dependencies = null;
22639 current$$1.alternate = null;
22640 current$$1.firstEffect = null;
22641 current$$1.lastEffect = null;
22642 current$$1.pendingProps = null;
22643 current$$1.memoizedProps = null;
22644
22645 if (alternate !== null) {
22646 detachFiber(alternate);
22647 }
22648}
22649
22650function emptyPortalContainer(current$$1) {
22651 if (!supportsPersistence) {
22652 return;
22653 }
22654
22655 var portal = current$$1.stateNode;
22656 var containerInfo = portal.containerInfo;
22657 var emptyChildSet = createContainerChildSet(containerInfo);
22658 replaceContainerChildren(containerInfo, emptyChildSet);
22659}
22660
22661function commitContainer(finishedWork) {
22662 if (!supportsPersistence) {
22663 return;
22664 }
22665
22666 switch (finishedWork.tag) {
22667 case ClassComponent:
22668 case HostComponent:
22669 case HostText:
22670 case FundamentalComponent:
22671 {
22672 return;
22673 }
22674
22675 case HostRoot:
22676 case HostPortal:
22677 {
22678 var portalOrRoot = finishedWork.stateNode;
22679 var containerInfo = portalOrRoot.containerInfo,
22680 pendingChildren = portalOrRoot.pendingChildren;
22681 replaceContainerChildren(containerInfo, pendingChildren);
22682 return;
22683 }
22684
22685 default:
22686 {
22687 {
22688 {
22689 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.");
22690 }
22691 }
22692 }
22693 }
22694}
22695
22696function getHostParentFiber(fiber) {
22697 var parent = fiber.return;
22698
22699 while (parent !== null) {
22700 if (isHostParent(parent)) {
22701 return parent;
22702 }
22703
22704 parent = parent.return;
22705 }
22706
22707 {
22708 {
22709 throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
22710 }
22711 }
22712}
22713
22714function isHostParent(fiber) {
22715 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
22716}
22717
22718function getHostSibling(fiber) {
22719 // We're going to search forward into the tree until we find a sibling host
22720 // node. Unfortunately, if multiple insertions are done in a row we have to
22721 // search past them. This leads to exponential search for the next sibling.
22722 // TODO: Find a more efficient way to do this.
22723 var node = fiber;
22724
22725 siblings: while (true) {
22726 // If we didn't find anything, let's try the next sibling.
22727 while (node.sibling === null) {
22728 if (node.return === null || isHostParent(node.return)) {
22729 // If we pop out of the root or hit the parent the fiber we are the
22730 // last sibling.
22731 return null;
22732 }
22733
22734 node = node.return;
22735 }
22736
22737 node.sibling.return = node.return;
22738 node = node.sibling;
22739
22740 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
22741 // If it is not host node and, we might have a host node inside it.
22742 // Try to search down until we find one.
22743 if (node.effectTag & Placement) {
22744 // If we don't have a child, try the siblings instead.
22745 continue siblings;
22746 } // If we don't have a child, try the siblings instead.
22747 // We also skip portals because they are not part of this host tree.
22748
22749
22750 if (node.child === null || node.tag === HostPortal) {
22751 continue siblings;
22752 } else {
22753 node.child.return = node;
22754 node = node.child;
22755 }
22756 } // Check if this host node is stable or about to be placed.
22757
22758
22759 if (!(node.effectTag & Placement)) {
22760 // Found it!
22761 return node.stateNode;
22762 }
22763 }
22764}
22765
22766function commitPlacement(finishedWork) {
22767 if (!supportsMutation) {
22768 return;
22769 } // Recursively insert all host nodes into the parent.
22770
22771
22772 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
22773
22774 var parent;
22775 var isContainer;
22776 var parentStateNode = parentFiber.stateNode;
22777
22778 switch (parentFiber.tag) {
22779 case HostComponent:
22780 parent = parentStateNode;
22781 isContainer = false;
22782 break;
22783
22784 case HostRoot:
22785 parent = parentStateNode.containerInfo;
22786 isContainer = true;
22787 break;
22788
22789 case HostPortal:
22790 parent = parentStateNode.containerInfo;
22791 isContainer = true;
22792 break;
22793
22794 case FundamentalComponent:
22795 if (enableFundamentalAPI) {
22796 parent = parentStateNode.instance;
22797 isContainer = false;
22798 }
22799
22800 // eslint-disable-next-line-no-fallthrough
22801
22802 default:
22803 {
22804 {
22805 throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
22806 }
22807 }
22808
22809 }
22810
22811 if (parentFiber.effectTag & ContentReset) {
22812 // Reset the text content of the parent before doing any insertions
22813 resetTextContent(parent); // Clear ContentReset from the effect tag
22814
22815 parentFiber.effectTag &= ~ContentReset;
22816 }
22817
22818 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
22819 // children to find all the terminal nodes.
22820
22821 var node = finishedWork;
22822
22823 while (true) {
22824 var isHost = node.tag === HostComponent || node.tag === HostText;
22825
22826 if (isHost || enableFundamentalAPI && node.tag === FundamentalComponent) {
22827 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
22828
22829 if (before) {
22830 if (isContainer) {
22831 insertInContainerBefore(parent, stateNode, before);
22832 } else {
22833 insertBefore(parent, stateNode, before);
22834 }
22835 } else {
22836 if (isContainer) {
22837 appendChildToContainer(parent, stateNode);
22838 } else {
22839 appendChild(parent, stateNode);
22840 }
22841 }
22842 } else if (node.tag === HostPortal) {// If the insertion itself is a portal, then we don't want to traverse
22843 // down its children. Instead, we'll get insertions from each child in
22844 // the portal directly.
22845 } else if (node.child !== null) {
22846 node.child.return = node;
22847 node = node.child;
22848 continue;
22849 }
22850
22851 if (node === finishedWork) {
22852 return;
22853 }
22854
22855 while (node.sibling === null) {
22856 if (node.return === null || node.return === finishedWork) {
22857 return;
22858 }
22859
22860 node = node.return;
22861 }
22862
22863 node.sibling.return = node.return;
22864 node = node.sibling;
22865 }
22866}
22867
22868function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) {
22869 // We only have the top Fiber that was deleted but we need to recurse down its
22870 // children to find all the terminal nodes.
22871 var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not
22872 // currentParentIsValid.
22873
22874 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
22875
22876 var currentParent;
22877 var currentParentIsContainer;
22878
22879 while (true) {
22880 if (!currentParentIsValid) {
22881 var parent = node.return;
22882
22883 findParent: while (true) {
22884 if (!(parent !== null)) {
22885 {
22886 throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
22887 }
22888 }
22889
22890 var parentStateNode = parent.stateNode;
22891
22892 switch (parent.tag) {
22893 case HostComponent:
22894 currentParent = parentStateNode;
22895 currentParentIsContainer = false;
22896 break findParent;
22897
22898 case HostRoot:
22899 currentParent = parentStateNode.containerInfo;
22900 currentParentIsContainer = true;
22901 break findParent;
22902
22903 case HostPortal:
22904 currentParent = parentStateNode.containerInfo;
22905 currentParentIsContainer = true;
22906 break findParent;
22907
22908 case FundamentalComponent:
22909 if (enableFundamentalAPI) {
22910 currentParent = parentStateNode.instance;
22911 currentParentIsContainer = false;
22912 }
22913
22914 }
22915
22916 parent = parent.return;
22917 }
22918
22919 currentParentIsValid = true;
22920 }
22921
22922 if (node.tag === HostComponent || node.tag === HostText) {
22923 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22924 // node from the tree.
22925
22926 if (currentParentIsContainer) {
22927 removeChildFromContainer(currentParent, node.stateNode);
22928 } else {
22929 removeChild(currentParent, node.stateNode);
22930 } // Don't visit children because we already visited them.
22931
22932 } else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
22933 var fundamentalNode = node.stateNode.instance;
22934 commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
22935 // node from the tree.
22936
22937 if (currentParentIsContainer) {
22938 removeChildFromContainer(currentParent, fundamentalNode);
22939 } else {
22940 removeChild(currentParent, fundamentalNode);
22941 }
22942 } else if (enableSuspenseServerRenderer && node.tag === DehydratedFragment) {
22943 if (enableSuspenseCallback) {
22944 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
22945
22946 if (hydrationCallbacks !== null) {
22947 var onDeleted = hydrationCallbacks.onDeleted;
22948
22949 if (onDeleted) {
22950 onDeleted(node.stateNode);
22951 }
22952 }
22953 } // Delete the dehydrated suspense boundary and all of its content.
22954
22955
22956 if (currentParentIsContainer) {
22957 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
22958 } else {
22959 clearSuspenseBoundary(currentParent, node.stateNode);
22960 }
22961 } else if (node.tag === HostPortal) {
22962 if (node.child !== null) {
22963 // When we go into a portal, it becomes the parent to remove from.
22964 // We will reassign it back when we pop the portal on the way up.
22965 currentParent = node.stateNode.containerInfo;
22966 currentParentIsContainer = true; // Visit children because portals might contain host components.
22967
22968 node.child.return = node;
22969 node = node.child;
22970 continue;
22971 }
22972 } else {
22973 commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
22974
22975 if (node.child !== null) {
22976 node.child.return = node;
22977 node = node.child;
22978 continue;
22979 }
22980 }
22981
22982 if (node === current$$1) {
22983 return;
22984 }
22985
22986 while (node.sibling === null) {
22987 if (node.return === null || node.return === current$$1) {
22988 return;
22989 }
22990
22991 node = node.return;
22992
22993 if (node.tag === HostPortal) {
22994 // When we go out of the portal, we need to restore the parent.
22995 // Since we don't keep a stack of them, we will search for it.
22996 currentParentIsValid = false;
22997 }
22998 }
22999
23000 node.sibling.return = node.return;
23001 node = node.sibling;
23002 }
23003}
23004
23005function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) {
23006 if (supportsMutation) {
23007 // Recursively delete all host nodes from the parent.
23008 // Detach refs and call componentWillUnmount() on the whole subtree.
23009 unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel);
23010 } else {
23011 // Detach refs and call componentWillUnmount() on the whole subtree.
23012 commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel);
23013 }
23014
23015 detachFiber(current$$1);
23016}
23017
23018function commitWork(current$$1, finishedWork) {
23019 if (!supportsMutation) {
23020 switch (finishedWork.tag) {
23021 case FunctionComponent:
23022 case ForwardRef:
23023 case MemoComponent:
23024 case SimpleMemoComponent:
23025 {
23026 // Note: We currently never use MountMutation, but useLayout uses
23027 // UnmountMutation.
23028 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
23029 return;
23030 }
23031
23032 case Profiler:
23033 {
23034 return;
23035 }
23036
23037 case SuspenseComponent:
23038 {
23039 commitSuspenseComponent(finishedWork);
23040 attachSuspenseRetryListeners(finishedWork);
23041 return;
23042 }
23043
23044 case SuspenseListComponent:
23045 {
23046 attachSuspenseRetryListeners(finishedWork);
23047 return;
23048 }
23049
23050 case HostRoot:
23051 {
23052 if (supportsHydration) {
23053 var root = finishedWork.stateNode;
23054
23055 if (root.hydrate) {
23056 // We've just hydrated. No need to hydrate again.
23057 root.hydrate = false;
23058 commitHydratedContainer(root.containerInfo);
23059 }
23060 }
23061
23062 break;
23063 }
23064 }
23065
23066 commitContainer(finishedWork);
23067 return;
23068 }
23069
23070 switch (finishedWork.tag) {
23071 case FunctionComponent:
23072 case ForwardRef:
23073 case MemoComponent:
23074 case SimpleMemoComponent:
23075 {
23076 // Note: We currently never use MountMutation, but useLayout uses
23077 // UnmountMutation.
23078 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
23079 return;
23080 }
23081
23082 case ClassComponent:
23083 {
23084 return;
23085 }
23086
23087 case HostComponent:
23088 {
23089 var instance = finishedWork.stateNode;
23090
23091 if (instance != null) {
23092 // Commit the work prepared earlier.
23093 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23094 // as the newProps. The updatePayload will contain the real change in
23095 // this case.
23096
23097 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
23098 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
23099
23100 var updatePayload = finishedWork.updateQueue;
23101 finishedWork.updateQueue = null;
23102
23103 if (updatePayload !== null) {
23104 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
23105 }
23106
23107 if (enableFlareAPI) {
23108 var prevListeners = oldProps.listeners;
23109 var nextListeners = newProps.listeners;
23110
23111 if (prevListeners !== nextListeners) {
23112 updateEventListeners(nextListeners, finishedWork, null);
23113 }
23114 }
23115 }
23116
23117 return;
23118 }
23119
23120 case HostText:
23121 {
23122 if (!(finishedWork.stateNode !== null)) {
23123 {
23124 throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
23125 }
23126 }
23127
23128 var textInstance = finishedWork.stateNode;
23129 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
23130 // as the newProps. The updatePayload will contain the real change in
23131 // this case.
23132
23133 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
23134 commitTextUpdate(textInstance, oldText, newText);
23135 return;
23136 }
23137
23138 case HostRoot:
23139 {
23140 if (supportsHydration) {
23141 var _root = finishedWork.stateNode;
23142
23143 if (_root.hydrate) {
23144 // We've just hydrated. No need to hydrate again.
23145 _root.hydrate = false;
23146 commitHydratedContainer(_root.containerInfo);
23147 }
23148 }
23149
23150 return;
23151 }
23152
23153 case Profiler:
23154 {
23155 return;
23156 }
23157
23158 case SuspenseComponent:
23159 {
23160 commitSuspenseComponent(finishedWork);
23161 attachSuspenseRetryListeners(finishedWork);
23162 return;
23163 }
23164
23165 case SuspenseListComponent:
23166 {
23167 attachSuspenseRetryListeners(finishedWork);
23168 return;
23169 }
23170
23171 case IncompleteClassComponent:
23172 {
23173 return;
23174 }
23175
23176 case FundamentalComponent:
23177 {
23178 if (enableFundamentalAPI) {
23179 var fundamentalInstance = finishedWork.stateNode;
23180 updateFundamentalComponent(fundamentalInstance);
23181 }
23182
23183 return;
23184 }
23185
23186 case ScopeComponent:
23187 {
23188 if (enableScopeAPI) {
23189 var scopeInstance = finishedWork.stateNode;
23190 scopeInstance.fiber = finishedWork;
23191
23192 if (enableFlareAPI) {
23193 var _newProps = finishedWork.memoizedProps;
23194
23195 var _oldProps = current$$1 !== null ? current$$1.memoizedProps : _newProps;
23196
23197 var _prevListeners = _oldProps.listeners;
23198 var _nextListeners = _newProps.listeners;
23199
23200 if (_prevListeners !== _nextListeners) {
23201 updateEventListeners(_nextListeners, finishedWork, null);
23202 }
23203 }
23204 }
23205
23206 return;
23207 }
23208
23209 default:
23210 {
23211 {
23212 {
23213 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.");
23214 }
23215 }
23216 }
23217 }
23218}
23219
23220function commitSuspenseComponent(finishedWork) {
23221 var newState = finishedWork.memoizedState;
23222 var newDidTimeout;
23223 var primaryChildParent = finishedWork;
23224
23225 if (newState === null) {
23226 newDidTimeout = false;
23227 } else {
23228 newDidTimeout = true;
23229 primaryChildParent = finishedWork.child;
23230 markCommitTimeOfFallback();
23231 }
23232
23233 if (supportsMutation && primaryChildParent !== null) {
23234 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
23235 }
23236
23237 if (enableSuspenseCallback && newState !== null) {
23238 var suspenseCallback = finishedWork.memoizedProps.suspenseCallback;
23239
23240 if (typeof suspenseCallback === 'function') {
23241 var thenables = finishedWork.updateQueue;
23242
23243 if (thenables !== null) {
23244 suspenseCallback(new Set(thenables));
23245 }
23246 } else {
23247 if (suspenseCallback !== undefined) {
23248 warning$1(false, 'Unexpected type for suspenseCallback.');
23249 }
23250 }
23251 }
23252}
23253
23254function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
23255 if (!supportsHydration) {
23256 return;
23257 }
23258
23259 var newState = finishedWork.memoizedState;
23260
23261 if (newState === null) {
23262 var current$$1 = finishedWork.alternate;
23263
23264 if (current$$1 !== null) {
23265 var prevState = current$$1.memoizedState;
23266
23267 if (prevState !== null) {
23268 var suspenseInstance = prevState.dehydrated;
23269
23270 if (suspenseInstance !== null) {
23271 commitHydratedSuspenseInstance(suspenseInstance);
23272
23273 if (enableSuspenseCallback) {
23274 var hydrationCallbacks = finishedRoot.hydrationCallbacks;
23275
23276 if (hydrationCallbacks !== null) {
23277 var onHydrated = hydrationCallbacks.onHydrated;
23278
23279 if (onHydrated) {
23280 onHydrated(suspenseInstance);
23281 }
23282 }
23283 }
23284 }
23285 }
23286 }
23287 }
23288}
23289
23290function attachSuspenseRetryListeners(finishedWork) {
23291 // If this boundary just timed out, then it will have a set of thenables.
23292 // For each thenable, attach a listener so that when it resolves, React
23293 // attempts to re-render the boundary in the primary (pre-timeout) state.
23294 var thenables = finishedWork.updateQueue;
23295
23296 if (thenables !== null) {
23297 finishedWork.updateQueue = null;
23298 var retryCache = finishedWork.stateNode;
23299
23300 if (retryCache === null) {
23301 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
23302 }
23303
23304 thenables.forEach(function (thenable) {
23305 // Memoize using the boundary fiber to prevent redundant listeners.
23306 var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
23307
23308 if (!retryCache.has(thenable)) {
23309 if (enableSchedulerTracing) {
23310 if (thenable.__reactDoNotTraceInteractions !== true) {
23311 retry = unstable_wrap(retry);
23312 }
23313 }
23314
23315 retryCache.add(thenable);
23316 thenable.then(retry, retry);
23317 }
23318 });
23319 }
23320}
23321
23322function commitResetTextContent(current$$1) {
23323 if (!supportsMutation) {
23324 return;
23325 }
23326
23327 resetTextContent(current$$1.stateNode);
23328}
23329
23330var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
23331
23332function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
23333 var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
23334
23335 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
23336 // being called "element".
23337
23338 update.payload = {
23339 element: null
23340 };
23341 var error = errorInfo.value;
23342
23343 update.callback = function () {
23344 onUncaughtError(error);
23345 logError(fiber, errorInfo);
23346 };
23347
23348 return update;
23349}
23350
23351function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
23352 var update = createUpdate(expirationTime, null);
23353 update.tag = CaptureUpdate;
23354 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
23355
23356 if (typeof getDerivedStateFromError === 'function') {
23357 var error = errorInfo.value;
23358
23359 update.payload = function () {
23360 logError(fiber, errorInfo);
23361 return getDerivedStateFromError(error);
23362 };
23363 }
23364
23365 var inst = fiber.stateNode;
23366
23367 if (inst !== null && typeof inst.componentDidCatch === 'function') {
23368 update.callback = function callback() {
23369 {
23370 markFailedErrorBoundaryForHotReloading(fiber);
23371 }
23372
23373 if (typeof getDerivedStateFromError !== 'function') {
23374 // To preserve the preexisting retry behavior of error boundaries,
23375 // we keep track of which ones already failed during this batch.
23376 // This gets reset before we yield back to the browser.
23377 // TODO: Warn in strict mode if getDerivedStateFromError is
23378 // not defined.
23379 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
23380
23381 logError(fiber, errorInfo);
23382 }
23383
23384 var error = errorInfo.value;
23385 var stack = errorInfo.stack;
23386 this.componentDidCatch(error, {
23387 componentStack: stack !== null ? stack : ''
23388 });
23389
23390 {
23391 if (typeof getDerivedStateFromError !== 'function') {
23392 // If componentDidCatch is the only error boundary method defined,
23393 // then it needs to call setState to recover from errors.
23394 // If no state update is scheduled then the boundary will swallow the error.
23395 !(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;
23396 }
23397 }
23398 };
23399 } else {
23400 update.callback = function () {
23401 markFailedErrorBoundaryForHotReloading(fiber);
23402 };
23403 }
23404
23405 return update;
23406}
23407
23408function attachPingListener(root, renderExpirationTime, thenable) {
23409 // Attach a listener to the promise to "ping" the root and retry. But
23410 // only if one does not already exist for the current render expiration
23411 // time (which acts like a "thread ID" here).
23412 var pingCache = root.pingCache;
23413 var threadIDs;
23414
23415 if (pingCache === null) {
23416 pingCache = root.pingCache = new PossiblyWeakMap$1();
23417 threadIDs = new Set();
23418 pingCache.set(thenable, threadIDs);
23419 } else {
23420 threadIDs = pingCache.get(thenable);
23421
23422 if (threadIDs === undefined) {
23423 threadIDs = new Set();
23424 pingCache.set(thenable, threadIDs);
23425 }
23426 }
23427
23428 if (!threadIDs.has(renderExpirationTime)) {
23429 // Memoize using the thread ID to prevent redundant listeners.
23430 threadIDs.add(renderExpirationTime);
23431 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
23432 thenable.then(ping, ping);
23433 }
23434}
23435
23436function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
23437 // The source fiber did not complete.
23438 sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
23439
23440 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
23441
23442 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
23443 // This is a thenable.
23444 var thenable = value;
23445 checkForWrongSuspensePriorityInDEV(sourceFiber);
23446 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
23447
23448 var _workInProgress = returnFiber;
23449
23450 do {
23451 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
23452 // Found the nearest boundary.
23453 // Stash the promise on the boundary fiber. If the boundary times out, we'll
23454 // attach another listener to flip the boundary back to its normal state.
23455 var thenables = _workInProgress.updateQueue;
23456
23457 if (thenables === null) {
23458 var updateQueue = new Set();
23459 updateQueue.add(thenable);
23460 _workInProgress.updateQueue = updateQueue;
23461 } else {
23462 thenables.add(thenable);
23463 } // If the boundary is outside of batched mode, we should *not*
23464 // suspend the commit. Pretend as if the suspended component rendered
23465 // null and keep rendering. In the commit phase, we'll schedule a
23466 // subsequent synchronous update to re-render the Suspense.
23467 //
23468 // Note: It doesn't matter whether the component that suspended was
23469 // inside a batched mode tree. If the Suspense is outside of it, we
23470 // should *not* suspend the commit.
23471
23472
23473 if ((_workInProgress.mode & BatchedMode) === NoMode) {
23474 _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
23475 // But we shouldn't call any lifecycle methods or callbacks. Remove
23476 // all lifecycle effect tags.
23477
23478 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
23479
23480 if (sourceFiber.tag === ClassComponent) {
23481 var currentSourceFiber = sourceFiber.alternate;
23482
23483 if (currentSourceFiber === null) {
23484 // This is a new mount. Change the tag so it's not mistaken for a
23485 // completed class component. For example, we should not call
23486 // componentWillUnmount if it is deleted.
23487 sourceFiber.tag = IncompleteClassComponent;
23488 } else {
23489 // When we try rendering again, we should not reuse the current fiber,
23490 // since it's known to be in an inconsistent state. Use a force update to
23491 // prevent a bail out.
23492 var update = createUpdate(Sync, null);
23493 update.tag = ForceUpdate;
23494 enqueueUpdate(sourceFiber, update);
23495 }
23496 } // The source fiber did not complete. Mark it with Sync priority to
23497 // indicate that it still has pending work.
23498
23499
23500 sourceFiber.expirationTime = Sync; // Exit without suspending.
23501
23502 return;
23503 } // Confirmed that the boundary is in a concurrent mode tree. Continue
23504 // with the normal suspend path.
23505 //
23506 // After this we'll use a set of heuristics to determine whether this
23507 // render pass will run to completion or restart or "suspend" the commit.
23508 // The actual logic for this is spread out in different places.
23509 //
23510 // This first principle is that if we're going to suspend when we complete
23511 // a root, then we should also restart if we get an update or ping that
23512 // might unsuspend it, and vice versa. The only reason to suspend is
23513 // because you think you might want to restart before committing. However,
23514 // it doesn't make sense to restart only while in the period we're suspended.
23515 //
23516 // Restarting too aggressively is also not good because it starves out any
23517 // intermediate loading state. So we use heuristics to determine when.
23518 // Suspense Heuristics
23519 //
23520 // If nothing threw a Promise or all the same fallbacks are already showing,
23521 // then don't suspend/restart.
23522 //
23523 // If this is an initial render of a new tree of Suspense boundaries and
23524 // those trigger a fallback, then don't suspend/restart. We want to ensure
23525 // that we can show the initial loading state as quickly as possible.
23526 //
23527 // If we hit a "Delayed" case, such as when we'd switch from content back into
23528 // a fallback, then we should always suspend/restart. SuspenseConfig applies to
23529 // this case. If none is defined, JND is used instead.
23530 //
23531 // If we're already showing a fallback and it gets "retried", allowing us to show
23532 // another level, but there's still an inner boundary that would show a fallback,
23533 // then we suspend/restart for 500ms since the last time we showed a fallback
23534 // anywhere in the tree. This effectively throttles progressive loading into a
23535 // consistent train of commits. This also gives us an opportunity to restart to
23536 // get to the completed state slightly earlier.
23537 //
23538 // If there's ambiguity due to batching it's resolved in preference of:
23539 // 1) "delayed", 2) "initial render", 3) "retry".
23540 //
23541 // We want to ensure that a "busy" state doesn't get force committed. We want to
23542 // ensure that new initial loading states can commit as soon as possible.
23543
23544
23545 attachPingListener(root, renderExpirationTime, thenable);
23546 _workInProgress.effectTag |= ShouldCapture;
23547 _workInProgress.expirationTime = renderExpirationTime;
23548 return;
23549 } // This boundary already captured during this render. Continue to the next
23550 // boundary.
23551
23552
23553 _workInProgress = _workInProgress.return;
23554 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
23555 // TODO: Use invariant so the message is stripped in prod?
23556
23557
23558 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));
23559 } // We didn't find a boundary that could handle this type of exception. Start
23560 // over and traverse parent path again, this time treating the exception
23561 // as an error.
23562
23563
23564 renderDidError();
23565 value = createCapturedValue(value, sourceFiber);
23566 var workInProgress = returnFiber;
23567
23568 do {
23569 switch (workInProgress.tag) {
23570 case HostRoot:
23571 {
23572 var _errorInfo = value;
23573 workInProgress.effectTag |= ShouldCapture;
23574 workInProgress.expirationTime = renderExpirationTime;
23575
23576 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
23577
23578 enqueueCapturedUpdate(workInProgress, _update);
23579 return;
23580 }
23581
23582 case ClassComponent:
23583 // Capture and retry
23584 var errorInfo = value;
23585 var ctor = workInProgress.type;
23586 var instance = workInProgress.stateNode;
23587
23588 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
23589 workInProgress.effectTag |= ShouldCapture;
23590 workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
23591
23592 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
23593
23594 enqueueCapturedUpdate(workInProgress, _update2);
23595 return;
23596 }
23597
23598 break;
23599
23600 default:
23601 break;
23602 }
23603
23604 workInProgress = workInProgress.return;
23605 } while (workInProgress !== null);
23606}
23607
23608var ceil = Math.ceil;
23609var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
23610var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
23611var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
23612var NoContext =
23613/* */
236140;
23615var BatchedContext =
23616/* */
236171;
23618var EventContext =
23619/* */
236202;
23621var DiscreteEventContext =
23622/* */
236234;
23624var LegacyUnbatchedContext =
23625/* */
236268;
23627var RenderContext =
23628/* */
2362916;
23630var CommitContext =
23631/* */
2363232;
23633var RootIncomplete = 0;
23634var RootFatalErrored = 1;
23635var RootErrored = 2;
23636var RootSuspended = 3;
23637var RootSuspendedWithDelay = 4;
23638var RootCompleted = 5;
23639// Describes where we are in the React execution stack
23640var executionContext = NoContext; // The root we're working on
23641
23642var workInProgressRoot = null; // The fiber we're working on
23643
23644var workInProgress = null; // The expiration time we're rendering
23645
23646var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc.
23647
23648var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
23649
23650var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
23651// This is conceptually a time stamp but expressed in terms of an ExpirationTime
23652// because we deal mostly with expiration times in the hot path, so this avoids
23653// the conversion happening in the hot path.
23654
23655var workInProgressRootLatestProcessedExpirationTime = Sync;
23656var workInProgressRootLatestSuspenseTimeout = Sync;
23657var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
23658// includes unprocessed updates, not work in bailed out children.
23659
23660var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
23661// This flag determines if it might be worthwhile to restart if an opportunity
23662// happens latere.
23663
23664var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
23665// model where we don't commit new loading states in too quick succession.
23666
23667var globalMostRecentFallbackTime = 0;
23668var FALLBACK_THROTTLE_MS = 500;
23669var nextEffect = null;
23670var hasUncaughtError = false;
23671var firstUncaughtError = null;
23672var legacyErrorBoundariesThatAlreadyFailed = null;
23673var rootDoesHavePassiveEffects = false;
23674var rootWithPendingPassiveEffects = null;
23675var pendingPassiveEffectsRenderPriority = NoPriority;
23676var pendingPassiveEffectsExpirationTime = NoWork;
23677var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
23678
23679var NESTED_UPDATE_LIMIT = 50;
23680var nestedUpdateCount = 0;
23681var rootWithNestedUpdates = null;
23682var NESTED_PASSIVE_UPDATE_LIMIT = 50;
23683var nestedPassiveUpdateCount = 0;
23684var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
23685// during the commit phase. This enables them to be traced across components
23686// that spawn new work during render. E.g. hidden boundaries, suspended SSR
23687// hydration or SuspenseList.
23688
23689var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
23690// time). However, if two updates are scheduled within the same event, we
23691// should treat their start times as simultaneous, even if the actual clock
23692// time has advanced between the first and second call.
23693// In other words, because expiration times determine how updates are batched,
23694// we want all updates of like priority that occur within the same event to
23695// receive the same expiration time. Otherwise we get tearing.
23696
23697var currentEventTime = NoWork;
23698function requestCurrentTimeForUpdate() {
23699 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
23700 // We're inside React, so it's fine to read the actual time.
23701 return msToExpirationTime(now());
23702 } // We're not inside React, so we may be in the middle of a browser event.
23703
23704
23705 if (currentEventTime !== NoWork) {
23706 // Use the same start time for all updates until we enter React again.
23707 return currentEventTime;
23708 } // This is the first update since React yielded. Compute a new start time.
23709
23710
23711 currentEventTime = msToExpirationTime(now());
23712 return currentEventTime;
23713}
23714function getCurrentTime() {
23715 return msToExpirationTime(now());
23716}
23717function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
23718 var mode = fiber.mode;
23719
23720 if ((mode & BatchedMode) === NoMode) {
23721 return Sync;
23722 }
23723
23724 var priorityLevel = getCurrentPriorityLevel();
23725
23726 if ((mode & ConcurrentMode) === NoMode) {
23727 return priorityLevel === ImmediatePriority ? Sync : Batched;
23728 }
23729
23730 if ((executionContext & RenderContext) !== NoContext) {
23731 // Use whatever time we're already rendering
23732 // TODO: Should there be a way to opt out, like with `runWithPriority`?
23733 return renderExpirationTime;
23734 }
23735
23736 var expirationTime;
23737
23738 if (suspenseConfig !== null) {
23739 // Compute an expiration time based on the Suspense timeout.
23740 expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
23741 } else {
23742 // Compute an expiration time based on the Scheduler priority.
23743 switch (priorityLevel) {
23744 case ImmediatePriority:
23745 expirationTime = Sync;
23746 break;
23747
23748 case UserBlockingPriority$2:
23749 // TODO: Rename this to computeUserBlockingExpiration
23750 expirationTime = computeInteractiveExpiration(currentTime);
23751 break;
23752
23753 case NormalPriority:
23754 case LowPriority:
23755 // TODO: Handle LowPriority
23756 // TODO: Rename this to... something better.
23757 expirationTime = computeAsyncExpiration(currentTime);
23758 break;
23759
23760 case IdlePriority:
23761 expirationTime = Idle;
23762 break;
23763
23764 default:
23765 {
23766 {
23767 throw Error("Expected a valid priority level");
23768 }
23769 }
23770
23771 }
23772 } // If we're in the middle of rendering a tree, do not update at the same
23773 // expiration time that is already rendering.
23774 // TODO: We shouldn't have to do this if the update is on a different root.
23775 // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
23776 // the root when we check for this condition.
23777
23778
23779 if (workInProgressRoot !== null && expirationTime === renderExpirationTime) {
23780 // This is a trick to move this update into a separate batch
23781 expirationTime -= 1;
23782 }
23783
23784 return expirationTime;
23785}
23786function scheduleUpdateOnFiber(fiber, expirationTime) {
23787 checkForNestedUpdates();
23788 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
23789 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
23790
23791 if (root === null) {
23792 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
23793 return;
23794 }
23795
23796 checkForInterruption(fiber, expirationTime);
23797 recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
23798 // priority as an argument to that function and this one.
23799
23800 var priorityLevel = getCurrentPriorityLevel();
23801
23802 if (expirationTime === Sync) {
23803 if ( // Check if we're inside unbatchedUpdates
23804 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
23805 (executionContext & (RenderContext | CommitContext)) === NoContext) {
23806 // Register pending interactions on the root to avoid losing traced interaction data.
23807 schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
23808 // root inside of batchedUpdates should be synchronous, but layout updates
23809 // should be deferred until the end of the batch.
23810
23811 performSyncWorkOnRoot(root);
23812 } else {
23813 ensureRootIsScheduled(root);
23814 schedulePendingInteractions(root, expirationTime);
23815
23816 if (executionContext === NoContext) {
23817 // Flush the synchronous work now, unless we're already working or inside
23818 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
23819 // scheduleCallbackForFiber to preserve the ability to schedule a callback
23820 // without immediately flushing it. We only do this for user-initiated
23821 // updates, to preserve historical behavior of sync mode.
23822 flushSyncCallbackQueue();
23823 }
23824 }
23825 } else {
23826 ensureRootIsScheduled(root);
23827 schedulePendingInteractions(root, expirationTime);
23828 }
23829
23830 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
23831 // discrete, even inside a discrete event.
23832 priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority)) {
23833 // This is the result of a discrete event. Track the lowest priority
23834 // discrete update per root so we can flush them early, if needed.
23835 if (rootsWithPendingDiscreteUpdates === null) {
23836 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
23837 } else {
23838 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
23839
23840 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
23841 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
23842 }
23843 }
23844 }
23845}
23846var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
23847// work without treating it as a typical update that originates from an event;
23848// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
23849// on a fiber.
23850
23851function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
23852 // Update the source fiber's expiration time
23853 if (fiber.expirationTime < expirationTime) {
23854 fiber.expirationTime = expirationTime;
23855 }
23856
23857 var alternate = fiber.alternate;
23858
23859 if (alternate !== null && alternate.expirationTime < expirationTime) {
23860 alternate.expirationTime = expirationTime;
23861 } // Walk the parent path to the root and update the child expiration time.
23862
23863
23864 var node = fiber.return;
23865 var root = null;
23866
23867 if (node === null && fiber.tag === HostRoot) {
23868 root = fiber.stateNode;
23869 } else {
23870 while (node !== null) {
23871 alternate = node.alternate;
23872
23873 if (node.childExpirationTime < expirationTime) {
23874 node.childExpirationTime = expirationTime;
23875
23876 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23877 alternate.childExpirationTime = expirationTime;
23878 }
23879 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
23880 alternate.childExpirationTime = expirationTime;
23881 }
23882
23883 if (node.return === null && node.tag === HostRoot) {
23884 root = node.stateNode;
23885 break;
23886 }
23887
23888 node = node.return;
23889 }
23890 }
23891
23892 if (root !== null) {
23893 if (workInProgressRoot === root) {
23894 // Received an update to a tree that's in the middle of rendering. Mark
23895 // that's unprocessed work on this root.
23896 markUnprocessedUpdateTime(expirationTime);
23897
23898 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
23899 // The root already suspended with a delay, which means this render
23900 // definitely won't finish. Since we have a new update, let's mark it as
23901 // suspended now, right before marking the incoming update. This has the
23902 // effect of interrupting the current render and switching to the update.
23903 // TODO: This happens to work when receiving an update during the render
23904 // phase, because of the trick inside computeExpirationForFiber to
23905 // subtract 1 from `renderExpirationTime` to move it into a
23906 // separate bucket. But we should probably model it with an exception,
23907 // using the same mechanism we use to force hydration of a subtree.
23908 // TODO: This does not account for low pri updates that were already
23909 // scheduled before the root started rendering. Need to track the next
23910 // pending expiration time (perhaps by backtracking the return path) and
23911 // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
23912 markRootSuspendedAtTime(root, renderExpirationTime);
23913 }
23914 } // Mark that the root has a pending update.
23915
23916
23917 markRootUpdatedAtTime(root, expirationTime);
23918 }
23919
23920 return root;
23921}
23922
23923function getNextRootExpirationTimeToWorkOn(root) {
23924 // Determines the next expiration time that the root should render, taking
23925 // into account levels that may be suspended, or levels that may have
23926 // received a ping.
23927 var lastExpiredTime = root.lastExpiredTime;
23928
23929 if (lastExpiredTime !== NoWork) {
23930 return lastExpiredTime;
23931 } // "Pending" refers to any update that hasn't committed yet, including if it
23932 // suspended. The "suspended" range is therefore a subset.
23933
23934
23935 var firstPendingTime = root.firstPendingTime;
23936
23937 if (!isRootSuspendedAtTime(root, firstPendingTime)) {
23938 // The highest priority pending time is not suspended. Let's work on that.
23939 return firstPendingTime;
23940 } // If the first pending time is suspended, check if there's a lower priority
23941 // pending level that we know about. Or check if we received a ping. Work
23942 // on whichever is higher priority.
23943
23944
23945 var lastPingedTime = root.lastPingedTime;
23946 var nextKnownPendingLevel = root.nextKnownPendingLevel;
23947 return lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
23948} // Use this function to schedule a task for a root. There's only one task per
23949// root; if a task was already scheduled, we'll check to make sure the
23950// expiration time of the existing task is the same as the expiration time of
23951// the next level that the root has work on. This function is called on every
23952// update, and right before exiting a task.
23953
23954
23955function ensureRootIsScheduled(root) {
23956 var lastExpiredTime = root.lastExpiredTime;
23957
23958 if (lastExpiredTime !== NoWork) {
23959 // Special case: Expired work should flush synchronously.
23960 root.callbackExpirationTime = Sync;
23961 root.callbackPriority = ImmediatePriority;
23962 root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
23963 return;
23964 }
23965
23966 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
23967 var existingCallbackNode = root.callbackNode;
23968
23969 if (expirationTime === NoWork) {
23970 // There's nothing to work on.
23971 if (existingCallbackNode !== null) {
23972 root.callbackNode = null;
23973 root.callbackExpirationTime = NoWork;
23974 root.callbackPriority = NoPriority;
23975 }
23976
23977 return;
23978 } // TODO: If this is an update, we already read the current time. Pass the
23979 // time as an argument.
23980
23981
23982 var currentTime = requestCurrentTimeForUpdate();
23983 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
23984 // expiration time. Otherwise, we'll cancel it and schedule a new one.
23985
23986 if (existingCallbackNode !== null) {
23987 var existingCallbackPriority = root.callbackPriority;
23988 var existingCallbackExpirationTime = root.callbackExpirationTime;
23989
23990 if ( // Callback must have the exact same expiration time.
23991 existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
23992 existingCallbackPriority >= priorityLevel) {
23993 // Existing callback is sufficient.
23994 return;
23995 } // Need to schedule a new task.
23996 // TODO: Instead of scheduling a new task, we should be able to change the
23997 // priority of the existing one.
23998
23999
24000 cancelCallback(existingCallbackNode);
24001 }
24002
24003 root.callbackExpirationTime = expirationTime;
24004 root.callbackPriority = priorityLevel;
24005 var callbackNode;
24006
24007 if (expirationTime === Sync) {
24008 // Sync React callbacks are scheduled on a special internal queue
24009 callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
24010 } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) {
24011 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root));
24012 } else {
24013 callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
24014 // ordering because tasks are processed in timeout order.
24015 {
24016 timeout: expirationTimeToMs(expirationTime) - now()
24017 });
24018 }
24019
24020 root.callbackNode = callbackNode;
24021} // This is the entry point for every concurrent task, i.e. anything that
24022// goes through Scheduler.
24023
24024
24025function performConcurrentWorkOnRoot(root, didTimeout) {
24026 // Since we know we're in a React event, we can clear the current
24027 // event time. The next update will compute a new event time.
24028 currentEventTime = NoWork;
24029
24030 if (didTimeout) {
24031 // The render task took too long to complete. Mark the current time as
24032 // expired to synchronously render all expired work in a single batch.
24033 var currentTime = requestCurrentTimeForUpdate();
24034 markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
24035
24036 ensureRootIsScheduled(root);
24037 return null;
24038 } // Determine the next expiration time to work on, using the fields stored
24039 // on the root.
24040
24041
24042 var expirationTime = getNextRootExpirationTimeToWorkOn(root);
24043
24044 if (expirationTime !== NoWork) {
24045 var originalCallbackNode = root.callbackNode;
24046
24047 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24048 {
24049 throw Error("Should not already be working.");
24050 }
24051 }
24052
24053 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24054 // and prepare a fresh one. Otherwise we'll continue where we left off.
24055
24056 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24057 prepareFreshStack(root, expirationTime);
24058 startWorkOnPendingInteractions(root, expirationTime);
24059 } // If we have a work-in-progress fiber, it means there's still work to do
24060 // in this root.
24061
24062
24063 if (workInProgress !== null) {
24064 var prevExecutionContext = executionContext;
24065 executionContext |= RenderContext;
24066 var prevDispatcher = pushDispatcher(root);
24067 var prevInteractions = pushInteractions(root);
24068 startWorkLoopTimer(workInProgress);
24069
24070 do {
24071 try {
24072 workLoopConcurrent();
24073 break;
24074 } catch (thrownValue) {
24075 handleError(root, thrownValue);
24076 }
24077 } while (true);
24078
24079 resetContextDependencies();
24080 executionContext = prevExecutionContext;
24081 popDispatcher(prevDispatcher);
24082
24083 if (enableSchedulerTracing) {
24084 popInteractions(prevInteractions);
24085 }
24086
24087 if (workInProgressRootExitStatus === RootFatalErrored) {
24088 var fatalError = workInProgressRootFatalError;
24089 stopInterruptedWorkLoopTimer();
24090 prepareFreshStack(root, expirationTime);
24091 markRootSuspendedAtTime(root, expirationTime);
24092 ensureRootIsScheduled(root);
24093 throw fatalError;
24094 }
24095
24096 if (workInProgress !== null) {
24097 // There's still work left over. Exit without committing.
24098 stopInterruptedWorkLoopTimer();
24099 } else {
24100 // We now have a consistent tree. The next step is either to commit it,
24101 // or, if something suspended, wait to commit it after a timeout.
24102 stopFinishedWorkLoopTimer();
24103 var finishedWork = root.finishedWork = root.current.alternate;
24104 root.finishedExpirationTime = expirationTime;
24105 finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
24106 }
24107
24108 ensureRootIsScheduled(root);
24109
24110 if (root.callbackNode === originalCallbackNode) {
24111 // The task node scheduled for this root is the same one that's
24112 // currently executed. Need to return a continuation.
24113 return performConcurrentWorkOnRoot.bind(null, root);
24114 }
24115 }
24116 }
24117
24118 return null;
24119}
24120
24121function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
24122 // Set this to null to indicate there's no in-progress render.
24123 workInProgressRoot = null;
24124
24125 switch (exitStatus) {
24126 case RootIncomplete:
24127 case RootFatalErrored:
24128 {
24129 {
24130 {
24131 throw Error("Root did not complete. This is a bug in React.");
24132 }
24133 }
24134 }
24135 // Flow knows about invariant, so it complains if I add a break
24136 // statement, but eslint doesn't know about invariant, so it complains
24137 // if I do. eslint-disable-next-line no-fallthrough
24138
24139 case RootErrored:
24140 {
24141 // If this was an async render, the error may have happened due to
24142 // a mutation in a concurrent event. Try rendering one more time,
24143 // synchronously, to see if the error goes away. If there are
24144 // lower priority updates, let's include those, too, in case they
24145 // fix the inconsistency. Render at Idle to include all updates.
24146 // If it was Idle or Never or some not-yet-invented time, render
24147 // at that time.
24148 markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous
24149 // and therefore not hit this path again.
24150
24151 break;
24152 }
24153
24154 case RootSuspended:
24155 {
24156 markRootSuspendedAtTime(root, expirationTime);
24157 var lastSuspendedTime = root.lastSuspendedTime;
24158
24159 if (expirationTime === lastSuspendedTime) {
24160 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24161 }
24162
24163 flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we
24164 // should immediately commit it or wait a bit.
24165 // If we have processed new updates during this render, we may now
24166 // have a new loading state ready. We want to ensure that we commit
24167 // that as soon as possible.
24168
24169 var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
24170
24171 if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
24172 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24173 // If we have not processed any new updates during this pass, then
24174 // this is either a retry of an existing fallback state or a
24175 // hidden tree. Hidden trees shouldn't be batched with other work
24176 // and after that's fixed it can only be a retry. We're going to
24177 // throttle committing retries so that we don't show too many
24178 // loading states too quickly.
24179 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
24180
24181 if (msUntilTimeout > 10) {
24182 if (workInProgressRootHasPendingPing) {
24183 var lastPingedTime = root.lastPingedTime;
24184
24185 if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
24186 // This render was pinged but we didn't get to restart
24187 // earlier so try restarting now instead.
24188 root.lastPingedTime = expirationTime;
24189 prepareFreshStack(root, expirationTime);
24190 break;
24191 }
24192 }
24193
24194 var nextTime = getNextRootExpirationTimeToWorkOn(root);
24195
24196 if (nextTime !== NoWork && nextTime !== expirationTime) {
24197 // There's additional work on this root.
24198 break;
24199 }
24200
24201 if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
24202 // We should prefer to render the fallback of at the last
24203 // suspended level. Ping the last suspended level to try
24204 // rendering it again.
24205 root.lastPingedTime = lastSuspendedTime;
24206 break;
24207 } // The render is suspended, it hasn't timed out, and there's no
24208 // lower priority work to do. Instead of committing the fallback
24209 // immediately, wait for more data to arrive.
24210
24211
24212 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
24213 break;
24214 }
24215 } // The work expired. Commit immediately.
24216
24217
24218 commitRoot(root);
24219 break;
24220 }
24221
24222 case RootSuspendedWithDelay:
24223 {
24224 markRootSuspendedAtTime(root, expirationTime);
24225 var _lastSuspendedTime = root.lastSuspendedTime;
24226
24227 if (expirationTime === _lastSuspendedTime) {
24228 root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
24229 }
24230
24231 flushSuspensePriorityWarningInDEV();
24232
24233 if ( // do not delay if we're inside an act() scope
24234 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current)) {
24235 // We're suspended in a state that should be avoided. We'll try to
24236 // avoid committing it for as long as the timeouts let us.
24237 if (workInProgressRootHasPendingPing) {
24238 var _lastPingedTime = root.lastPingedTime;
24239
24240 if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
24241 // This render was pinged but we didn't get to restart earlier
24242 // so try restarting now instead.
24243 root.lastPingedTime = expirationTime;
24244 prepareFreshStack(root, expirationTime);
24245 break;
24246 }
24247 }
24248
24249 var _nextTime = getNextRootExpirationTimeToWorkOn(root);
24250
24251 if (_nextTime !== NoWork && _nextTime !== expirationTime) {
24252 // There's additional work on this root.
24253 break;
24254 }
24255
24256 if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
24257 // We should prefer to render the fallback of at the last
24258 // suspended level. Ping the last suspended level to try
24259 // rendering it again.
24260 root.lastPingedTime = _lastSuspendedTime;
24261 break;
24262 }
24263
24264 var _msUntilTimeout;
24265
24266 if (workInProgressRootLatestSuspenseTimeout !== Sync) {
24267 // We have processed a suspense config whose expiration time we
24268 // can use as the timeout.
24269 _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
24270 } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
24271 // This should never normally happen because only new updates
24272 // cause delayed states, so we should have processed something.
24273 // However, this could also happen in an offscreen tree.
24274 _msUntilTimeout = 0;
24275 } else {
24276 // If we don't have a suspense config, we're going to use a
24277 // heuristic to determine how long we can suspend.
24278 var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
24279 var currentTimeMs = now();
24280 var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
24281 var timeElapsed = currentTimeMs - eventTimeMs;
24282
24283 if (timeElapsed < 0) {
24284 // We get this wrong some time since we estimate the time.
24285 timeElapsed = 0;
24286 }
24287
24288 _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
24289 // event time is exact instead of inferred from expiration time
24290 // we don't need this.
24291
24292 if (timeUntilExpirationMs < _msUntilTimeout) {
24293 _msUntilTimeout = timeUntilExpirationMs;
24294 }
24295 } // Don't bother with a very short suspense time.
24296
24297
24298 if (_msUntilTimeout > 10) {
24299 // The render is suspended, it hasn't timed out, and there's no
24300 // lower priority work to do. Instead of committing the fallback
24301 // immediately, wait for more data to arrive.
24302 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
24303 break;
24304 }
24305 } // The work expired. Commit immediately.
24306
24307
24308 commitRoot(root);
24309 break;
24310 }
24311
24312 case RootCompleted:
24313 {
24314 // The work completed. Ready to commit.
24315 if ( // do not delay if we're inside an act() scope
24316 !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
24317 // If we have exceeded the minimum loading delay, which probably
24318 // means we have shown a spinner already, we might have to suspend
24319 // a bit longer to ensure that the spinner is shown for
24320 // enough time.
24321 var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
24322
24323 if (_msUntilTimeout2 > 10) {
24324 markRootSuspendedAtTime(root, expirationTime);
24325 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
24326 break;
24327 }
24328 }
24329
24330 commitRoot(root);
24331 break;
24332 }
24333
24334 default:
24335 {
24336 {
24337 {
24338 throw Error("Unknown root exit status.");
24339 }
24340 }
24341 }
24342 }
24343} // This is the entry point for synchronous tasks that don't go
24344// through Scheduler
24345
24346
24347function performSyncWorkOnRoot(root) {
24348 // Check if there's expired work on this root. Otherwise, render at Sync.
24349 var lastExpiredTime = root.lastExpiredTime;
24350 var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
24351
24352 if (root.finishedExpirationTime === expirationTime) {
24353 // There's already a pending commit at this expiration time.
24354 // TODO: This is poorly factored. This case only exists for the
24355 // batch.commit() API.
24356 commitRoot(root);
24357 } else {
24358 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
24359 {
24360 throw Error("Should not already be working.");
24361 }
24362 }
24363
24364 flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
24365 // and prepare a fresh one. Otherwise we'll continue where we left off.
24366
24367 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) {
24368 prepareFreshStack(root, expirationTime);
24369 startWorkOnPendingInteractions(root, expirationTime);
24370 } // If we have a work-in-progress fiber, it means there's still work to do
24371 // in this root.
24372
24373
24374 if (workInProgress !== null) {
24375 var prevExecutionContext = executionContext;
24376 executionContext |= RenderContext;
24377 var prevDispatcher = pushDispatcher(root);
24378 var prevInteractions = pushInteractions(root);
24379 startWorkLoopTimer(workInProgress);
24380
24381 do {
24382 try {
24383 workLoopSync();
24384 break;
24385 } catch (thrownValue) {
24386 handleError(root, thrownValue);
24387 }
24388 } while (true);
24389
24390 resetContextDependencies();
24391 executionContext = prevExecutionContext;
24392 popDispatcher(prevDispatcher);
24393
24394 if (enableSchedulerTracing) {
24395 popInteractions(prevInteractions);
24396 }
24397
24398 if (workInProgressRootExitStatus === RootFatalErrored) {
24399 var fatalError = workInProgressRootFatalError;
24400 stopInterruptedWorkLoopTimer();
24401 prepareFreshStack(root, expirationTime);
24402 markRootSuspendedAtTime(root, expirationTime);
24403 ensureRootIsScheduled(root);
24404 throw fatalError;
24405 }
24406
24407 if (workInProgress !== null) {
24408 // This is a sync render, so we should have finished the whole tree.
24409 {
24410 {
24411 throw Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
24412 }
24413 }
24414 } else {
24415 // We now have a consistent tree. Because this is a sync render, we
24416 // will commit it even if something suspended.
24417 stopFinishedWorkLoopTimer();
24418 root.finishedWork = root.current.alternate;
24419 root.finishedExpirationTime = expirationTime;
24420 finishSyncRender(root, workInProgressRootExitStatus, expirationTime);
24421 } // Before exiting, make sure there's a callback scheduled for the next
24422 // pending level.
24423
24424
24425 ensureRootIsScheduled(root);
24426 }
24427 }
24428
24429 return null;
24430}
24431
24432function finishSyncRender(root, exitStatus, expirationTime) {
24433 // Set this to null to indicate there's no in-progress render.
24434 workInProgressRoot = null;
24435
24436 {
24437 if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) {
24438 flushSuspensePriorityWarningInDEV();
24439 }
24440 }
24441
24442 commitRoot(root);
24443}
24444
24445function flushRoot(root, expirationTime) {
24446 markRootExpiredAtTime(root, expirationTime);
24447 ensureRootIsScheduled(root);
24448
24449 if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
24450 flushSyncCallbackQueue();
24451 }
24452}
24453function flushDiscreteUpdates() {
24454 // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
24455 // However, `act` uses `batchedUpdates`, so there's no way to distinguish
24456 // those two cases. Need to fix this before exposing flushDiscreteUpdates
24457 // as a public API.
24458 if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
24459 if (true && (executionContext & RenderContext) !== NoContext) {
24460 warning$1(false, 'unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
24461 } // We're already rendering, so we can't synchronously flush pending work.
24462 // This is probably a nested event dispatch triggered by a lifecycle/effect,
24463 // like `el.focus()`. Exit.
24464
24465
24466 return;
24467 }
24468
24469 flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
24470 // they fire before the next serial event.
24471
24472 flushPassiveEffects();
24473}
24474
24475function syncUpdates(fn, a, b, c) {
24476 return runWithPriority$2(ImmediatePriority, fn.bind(null, a, b, c));
24477}
24478
24479function flushPendingDiscreteUpdates() {
24480 if (rootsWithPendingDiscreteUpdates !== null) {
24481 // For each root with pending discrete updates, schedule a callback to
24482 // immediately flush them.
24483 var roots = rootsWithPendingDiscreteUpdates;
24484 rootsWithPendingDiscreteUpdates = null;
24485 roots.forEach(function (expirationTime, root) {
24486 markRootExpiredAtTime(root, expirationTime);
24487 ensureRootIsScheduled(root);
24488 }); // Now flush the immediate queue.
24489
24490 flushSyncCallbackQueue();
24491 }
24492}
24493
24494function batchedUpdates$1(fn, a) {
24495 var prevExecutionContext = executionContext;
24496 executionContext |= BatchedContext;
24497
24498 try {
24499 return fn(a);
24500 } finally {
24501 executionContext = prevExecutionContext;
24502
24503 if (executionContext === NoContext) {
24504 // Flush the immediate callbacks that were scheduled during this batch
24505 flushSyncCallbackQueue();
24506 }
24507 }
24508}
24509function batchedEventUpdates$1(fn, a) {
24510 var prevExecutionContext = executionContext;
24511 executionContext |= EventContext;
24512
24513 try {
24514 return fn(a);
24515 } finally {
24516 executionContext = prevExecutionContext;
24517
24518 if (executionContext === NoContext) {
24519 // Flush the immediate callbacks that were scheduled during this batch
24520 flushSyncCallbackQueue();
24521 }
24522 }
24523}
24524function discreteUpdates$1(fn, a, b, c) {
24525 var prevExecutionContext = executionContext;
24526 executionContext |= DiscreteEventContext;
24527
24528 try {
24529 // Should this
24530 return runWithPriority$2(UserBlockingPriority$2, fn.bind(null, a, b, c));
24531 } finally {
24532 executionContext = prevExecutionContext;
24533
24534 if (executionContext === NoContext) {
24535 // Flush the immediate callbacks that were scheduled during this batch
24536 flushSyncCallbackQueue();
24537 }
24538 }
24539}
24540function unbatchedUpdates(fn, a) {
24541 var prevExecutionContext = executionContext;
24542 executionContext &= ~BatchedContext;
24543 executionContext |= LegacyUnbatchedContext;
24544
24545 try {
24546 return fn(a);
24547 } finally {
24548 executionContext = prevExecutionContext;
24549
24550 if (executionContext === NoContext) {
24551 // Flush the immediate callbacks that were scheduled during this batch
24552 flushSyncCallbackQueue();
24553 }
24554 }
24555}
24556function flushSync(fn, a) {
24557 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
24558 {
24559 {
24560 throw Error("flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.");
24561 }
24562 }
24563 }
24564
24565 var prevExecutionContext = executionContext;
24566 executionContext |= BatchedContext;
24567
24568 try {
24569 return runWithPriority$2(ImmediatePriority, fn.bind(null, a));
24570 } finally {
24571 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
24572 // Note that this will happen even if batchedUpdates is higher up
24573 // the stack.
24574
24575 flushSyncCallbackQueue();
24576 }
24577}
24578function flushControlled(fn) {
24579 var prevExecutionContext = executionContext;
24580 executionContext |= BatchedContext;
24581
24582 try {
24583 runWithPriority$2(ImmediatePriority, fn);
24584 } finally {
24585 executionContext = prevExecutionContext;
24586
24587 if (executionContext === NoContext) {
24588 // Flush the immediate callbacks that were scheduled during this batch
24589 flushSyncCallbackQueue();
24590 }
24591 }
24592}
24593
24594function prepareFreshStack(root, expirationTime) {
24595 root.finishedWork = null;
24596 root.finishedExpirationTime = NoWork;
24597 var timeoutHandle = root.timeoutHandle;
24598
24599 if (timeoutHandle !== noTimeout) {
24600 // The root previous suspended and scheduled a timeout to commit a fallback
24601 // state. Now that we have additional work, cancel the timeout.
24602 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
24603
24604 cancelTimeout(timeoutHandle);
24605 }
24606
24607 if (workInProgress !== null) {
24608 var interruptedWork = workInProgress.return;
24609
24610 while (interruptedWork !== null) {
24611 unwindInterruptedWork(interruptedWork);
24612 interruptedWork = interruptedWork.return;
24613 }
24614 }
24615
24616 workInProgressRoot = root;
24617 workInProgress = createWorkInProgress(root.current, null, expirationTime);
24618 renderExpirationTime = expirationTime;
24619 workInProgressRootExitStatus = RootIncomplete;
24620 workInProgressRootFatalError = null;
24621 workInProgressRootLatestProcessedExpirationTime = Sync;
24622 workInProgressRootLatestSuspenseTimeout = Sync;
24623 workInProgressRootCanSuspendUsingConfig = null;
24624 workInProgressRootNextUnprocessedUpdateTime = NoWork;
24625 workInProgressRootHasPendingPing = false;
24626
24627 if (enableSchedulerTracing) {
24628 spawnedWorkDuringRender = null;
24629 }
24630
24631 {
24632 ReactStrictModeWarnings.discardPendingWarnings();
24633 componentsThatTriggeredHighPriSuspend = null;
24634 }
24635}
24636
24637function handleError(root, thrownValue) {
24638 do {
24639 try {
24640 // Reset module-level state that was set during the render phase.
24641 resetContextDependencies();
24642 resetHooks();
24643 resetCurrentFiber();
24644
24645 if (workInProgress === null || workInProgress.return === null) {
24646 // Expected to be working on a non-root fiber. This is a fatal error
24647 // because there's no ancestor that can handle it; the root is
24648 // supposed to capture all errors that weren't caught by an error
24649 // boundary.
24650 workInProgressRootExitStatus = RootFatalErrored;
24651 workInProgressRootFatalError = thrownValue;
24652 return null;
24653 }
24654
24655 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
24656 // Record the time spent rendering before an error was thrown. This
24657 // avoids inaccurate Profiler durations in the case of a
24658 // suspended render.
24659 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
24660 }
24661
24662 throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime);
24663 workInProgress = completeUnitOfWork(workInProgress);
24664 } catch (yetAnotherThrownValue) {
24665 // Something in the return path also threw.
24666 thrownValue = yetAnotherThrownValue;
24667 continue;
24668 } // Return to the normal work loop.
24669
24670
24671 return;
24672 } while (true);
24673}
24674
24675function pushDispatcher(root) {
24676 var prevDispatcher = ReactCurrentDispatcher.current;
24677 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
24678
24679 if (prevDispatcher === null) {
24680 // The React isomorphic package does not include a default dispatcher.
24681 // Instead the first renderer will lazily attach one, in order to give
24682 // nicer error messages.
24683 return ContextOnlyDispatcher;
24684 } else {
24685 return prevDispatcher;
24686 }
24687}
24688
24689function popDispatcher(prevDispatcher) {
24690 ReactCurrentDispatcher.current = prevDispatcher;
24691}
24692
24693function pushInteractions(root) {
24694 if (enableSchedulerTracing) {
24695 var prevInteractions = __interactionsRef.current;
24696 __interactionsRef.current = root.memoizedInteractions;
24697 return prevInteractions;
24698 }
24699
24700 return null;
24701}
24702
24703function popInteractions(prevInteractions) {
24704 if (enableSchedulerTracing) {
24705 __interactionsRef.current = prevInteractions;
24706 }
24707}
24708
24709function markCommitTimeOfFallback() {
24710 globalMostRecentFallbackTime = now();
24711}
24712function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
24713 if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
24714 workInProgressRootLatestProcessedExpirationTime = expirationTime;
24715 }
24716
24717 if (suspenseConfig !== null) {
24718 if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
24719 workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
24720
24721 workInProgressRootCanSuspendUsingConfig = suspenseConfig;
24722 }
24723 }
24724}
24725function markUnprocessedUpdateTime(expirationTime) {
24726 if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
24727 workInProgressRootNextUnprocessedUpdateTime = expirationTime;
24728 }
24729}
24730function renderDidSuspend() {
24731 if (workInProgressRootExitStatus === RootIncomplete) {
24732 workInProgressRootExitStatus = RootSuspended;
24733 }
24734}
24735function renderDidSuspendDelayIfPossible() {
24736 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
24737 workInProgressRootExitStatus = RootSuspendedWithDelay;
24738 } // Check if there's a lower priority update somewhere else in the tree.
24739
24740
24741 if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
24742 // Mark the current render as suspended, and then mark that there's a
24743 // pending update.
24744 // TODO: This should immediately interrupt the current render, instead
24745 // of waiting until the next time we yield.
24746 markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime);
24747 markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
24748 }
24749}
24750function renderDidError() {
24751 if (workInProgressRootExitStatus !== RootCompleted) {
24752 workInProgressRootExitStatus = RootErrored;
24753 }
24754} // Called during render to determine if anything has suspended.
24755// Returns false if we're not sure.
24756
24757function renderHasNotSuspendedYet() {
24758 // If something errored or completed, we can't really be sure,
24759 // so those are false.
24760 return workInProgressRootExitStatus === RootIncomplete;
24761}
24762
24763function inferTimeFromExpirationTime(expirationTime) {
24764 // We don't know exactly when the update was scheduled, but we can infer an
24765 // approximate start time from the expiration time.
24766 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24767 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
24768}
24769
24770function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
24771 // We don't know exactly when the update was scheduled, but we can infer an
24772 // approximate start time from the expiration time by subtracting the timeout
24773 // that was added to the event time.
24774 var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
24775 return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
24776} // The work loop is an extremely hot path. Tell Closure not to inline it.
24777
24778/** @noinline */
24779
24780
24781function workLoopSync() {
24782 // Already timed out, so perform work without checking if we need to yield.
24783 while (workInProgress !== null) {
24784 workInProgress = performUnitOfWork(workInProgress);
24785 }
24786}
24787/** @noinline */
24788
24789
24790function workLoopConcurrent() {
24791 // Perform work until Scheduler asks us to yield
24792 while (workInProgress !== null && !shouldYield()) {
24793 workInProgress = performUnitOfWork(workInProgress);
24794 }
24795}
24796
24797function performUnitOfWork(unitOfWork) {
24798 // The current, flushed, state of this fiber is the alternate. Ideally
24799 // nothing should rely on this, but relying on it here means that we don't
24800 // need an additional field on the work in progress.
24801 var current$$1 = unitOfWork.alternate;
24802 startWorkTimer(unitOfWork);
24803 setCurrentFiber(unitOfWork);
24804 var next;
24805
24806 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
24807 startProfilerTimer(unitOfWork);
24808 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24809 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
24810 } else {
24811 next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime);
24812 }
24813
24814 resetCurrentFiber();
24815 unitOfWork.memoizedProps = unitOfWork.pendingProps;
24816
24817 if (next === null) {
24818 // If this doesn't spawn new work, complete the current work.
24819 next = completeUnitOfWork(unitOfWork);
24820 }
24821
24822 ReactCurrentOwner$2.current = null;
24823 return next;
24824}
24825
24826function completeUnitOfWork(unitOfWork) {
24827 // Attempt to complete the current unit of work, then move to the next
24828 // sibling. If there are no more siblings, return to the parent fiber.
24829 workInProgress = unitOfWork;
24830
24831 do {
24832 // The current, flushed, state of this fiber is the alternate. Ideally
24833 // nothing should rely on this, but relying on it here means that we don't
24834 // need an additional field on the work in progress.
24835 var current$$1 = workInProgress.alternate;
24836 var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
24837
24838 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
24839 setCurrentFiber(workInProgress);
24840 var next = void 0;
24841
24842 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode) {
24843 next = completeWork(current$$1, workInProgress, renderExpirationTime);
24844 } else {
24845 startProfilerTimer(workInProgress);
24846 next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error.
24847
24848 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
24849 }
24850
24851 stopWorkTimer(workInProgress);
24852 resetCurrentFiber();
24853 resetChildExpirationTime(workInProgress);
24854
24855 if (next !== null) {
24856 // Completing this fiber spawned new work. Work on that next.
24857 return next;
24858 }
24859
24860 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
24861 (returnFiber.effectTag & Incomplete) === NoEffect) {
24862 // Append all the effects of the subtree and this fiber onto the effect
24863 // list of the parent. The completion order of the children affects the
24864 // side-effect order.
24865 if (returnFiber.firstEffect === null) {
24866 returnFiber.firstEffect = workInProgress.firstEffect;
24867 }
24868
24869 if (workInProgress.lastEffect !== null) {
24870 if (returnFiber.lastEffect !== null) {
24871 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
24872 }
24873
24874 returnFiber.lastEffect = workInProgress.lastEffect;
24875 } // If this fiber had side-effects, we append it AFTER the children's
24876 // side-effects. We can perform certain side-effects earlier if needed,
24877 // by doing multiple passes over the effect list. We don't want to
24878 // schedule our own side-effect on our own list because if end up
24879 // reusing children we'll schedule this effect onto itself since we're
24880 // at the end.
24881
24882
24883 var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
24884 // list. PerformedWork effect is read by React DevTools but shouldn't be
24885 // committed.
24886
24887 if (effectTag > PerformedWork) {
24888 if (returnFiber.lastEffect !== null) {
24889 returnFiber.lastEffect.nextEffect = workInProgress;
24890 } else {
24891 returnFiber.firstEffect = workInProgress;
24892 }
24893
24894 returnFiber.lastEffect = workInProgress;
24895 }
24896 }
24897 } else {
24898 // This fiber did not complete because something threw. Pop values off
24899 // the stack without entering the complete phase. If this is a boundary,
24900 // capture values if possible.
24901 var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time.
24902
24903
24904 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode) {
24905 // Record the render duration for the fiber that errored.
24906 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
24907
24908 var actualDuration = workInProgress.actualDuration;
24909 var child = workInProgress.child;
24910
24911 while (child !== null) {
24912 actualDuration += child.actualDuration;
24913 child = child.sibling;
24914 }
24915
24916 workInProgress.actualDuration = actualDuration;
24917 }
24918
24919 if (_next !== null) {
24920 // If completing this work spawned new work, do that next. We'll come
24921 // back here again.
24922 // Since we're restarting, remove anything that is not a host effect
24923 // from the effect tag.
24924 // TODO: The name stopFailedWorkTimer is misleading because Suspense
24925 // also captures and restarts.
24926 stopFailedWorkTimer(workInProgress);
24927 _next.effectTag &= HostEffectMask;
24928 return _next;
24929 }
24930
24931 stopWorkTimer(workInProgress);
24932
24933 if (returnFiber !== null) {
24934 // Mark the parent fiber as incomplete and clear its effect list.
24935 returnFiber.firstEffect = returnFiber.lastEffect = null;
24936 returnFiber.effectTag |= Incomplete;
24937 }
24938 }
24939
24940 var siblingFiber = workInProgress.sibling;
24941
24942 if (siblingFiber !== null) {
24943 // If there is more work to do in this returnFiber, do that next.
24944 return siblingFiber;
24945 } // Otherwise, return to the parent
24946
24947
24948 workInProgress = returnFiber;
24949 } while (workInProgress !== null); // We've reached the root.
24950
24951
24952 if (workInProgressRootExitStatus === RootIncomplete) {
24953 workInProgressRootExitStatus = RootCompleted;
24954 }
24955
24956 return null;
24957}
24958
24959function getRemainingExpirationTime(fiber) {
24960 var updateExpirationTime = fiber.expirationTime;
24961 var childExpirationTime = fiber.childExpirationTime;
24962 return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
24963}
24964
24965function resetChildExpirationTime(completedWork) {
24966 if (renderExpirationTime !== Never && completedWork.childExpirationTime === Never) {
24967 // The children of this component are hidden. Don't bubble their
24968 // expiration times.
24969 return;
24970 }
24971
24972 var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
24973
24974 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) {
24975 // In profiling mode, resetChildExpirationTime is also used to reset
24976 // profiler durations.
24977 var actualDuration = completedWork.actualDuration;
24978 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
24979 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
24980 // When work is done, it should bubble to the parent's actualDuration. If
24981 // the fiber has not been cloned though, (meaning no work was done), then
24982 // this value will reflect the amount of time spent working on a previous
24983 // render. In that case it should not bubble. We determine whether it was
24984 // cloned by comparing the child pointer.
24985
24986 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
24987 var child = completedWork.child;
24988
24989 while (child !== null) {
24990 var childUpdateExpirationTime = child.expirationTime;
24991 var childChildExpirationTime = child.childExpirationTime;
24992
24993 if (childUpdateExpirationTime > newChildExpirationTime) {
24994 newChildExpirationTime = childUpdateExpirationTime;
24995 }
24996
24997 if (childChildExpirationTime > newChildExpirationTime) {
24998 newChildExpirationTime = childChildExpirationTime;
24999 }
25000
25001 if (shouldBubbleActualDurations) {
25002 actualDuration += child.actualDuration;
25003 }
25004
25005 treeBaseDuration += child.treeBaseDuration;
25006 child = child.sibling;
25007 }
25008
25009 completedWork.actualDuration = actualDuration;
25010 completedWork.treeBaseDuration = treeBaseDuration;
25011 } else {
25012 var _child = completedWork.child;
25013
25014 while (_child !== null) {
25015 var _childUpdateExpirationTime = _child.expirationTime;
25016 var _childChildExpirationTime = _child.childExpirationTime;
25017
25018 if (_childUpdateExpirationTime > newChildExpirationTime) {
25019 newChildExpirationTime = _childUpdateExpirationTime;
25020 }
25021
25022 if (_childChildExpirationTime > newChildExpirationTime) {
25023 newChildExpirationTime = _childChildExpirationTime;
25024 }
25025
25026 _child = _child.sibling;
25027 }
25028 }
25029
25030 completedWork.childExpirationTime = newChildExpirationTime;
25031}
25032
25033function commitRoot(root) {
25034 var renderPriorityLevel = getCurrentPriorityLevel();
25035 runWithPriority$2(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
25036 return null;
25037}
25038
25039function commitRootImpl(root, renderPriorityLevel) {
25040 flushPassiveEffects();
25041 flushRenderPhaseStrictModeWarningsInDEV();
25042
25043 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25044 {
25045 throw Error("Should not already be working.");
25046 }
25047 }
25048
25049 var finishedWork = root.finishedWork;
25050 var expirationTime = root.finishedExpirationTime;
25051
25052 if (finishedWork === null) {
25053 return null;
25054 }
25055
25056 root.finishedWork = null;
25057 root.finishedExpirationTime = NoWork;
25058
25059 if (!(finishedWork !== root.current)) {
25060 {
25061 throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
25062 }
25063 } // commitRoot never returns a continuation; it always finishes synchronously.
25064 // So we can clear these now to allow a new callback to be scheduled.
25065
25066
25067 root.callbackNode = null;
25068 root.callbackExpirationTime = NoWork;
25069 root.callbackPriority = NoPriority;
25070 root.nextKnownPendingLevel = NoWork;
25071 startCommitTimer(); // Update the first and last pending times on this root. The new first
25072 // pending time is whatever is left on the root fiber.
25073
25074 var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
25075 markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
25076
25077 if (root === workInProgressRoot) {
25078 // We can reset these now that they are finished.
25079 workInProgressRoot = null;
25080 workInProgress = null;
25081 renderExpirationTime = NoWork;
25082 } else {} // This indicates that the last root we worked on is not the same one that
25083 // we're committing now. This most commonly happens when a suspended root
25084 // times out.
25085 // Get the list of effects.
25086
25087
25088 var firstEffect;
25089
25090 if (finishedWork.effectTag > PerformedWork) {
25091 // A fiber's effect list consists only of its children, not itself. So if
25092 // the root has an effect, we need to add it to the end of the list. The
25093 // resulting list is the set that would belong to the root's parent, if it
25094 // had one; that is, all the effects in the tree including the root.
25095 if (finishedWork.lastEffect !== null) {
25096 finishedWork.lastEffect.nextEffect = finishedWork;
25097 firstEffect = finishedWork.firstEffect;
25098 } else {
25099 firstEffect = finishedWork;
25100 }
25101 } else {
25102 // There is no effect on the root.
25103 firstEffect = finishedWork.firstEffect;
25104 }
25105
25106 if (firstEffect !== null) {
25107 var prevExecutionContext = executionContext;
25108 executionContext |= CommitContext;
25109 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
25110
25111 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
25112 // of the effect list for each phase: all mutation effects come before all
25113 // layout effects, and so on.
25114 // The first phase a "before mutation" phase. We use this phase to read the
25115 // state of the host tree right before we mutate it. This is where
25116 // getSnapshotBeforeUpdate is called.
25117
25118 startCommitSnapshotEffectsTimer();
25119 prepareForCommit(root.containerInfo);
25120 nextEffect = firstEffect;
25121
25122 do {
25123 {
25124 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
25125
25126 if (hasCaughtError()) {
25127 if (!(nextEffect !== null)) {
25128 {
25129 throw Error("Should be working on an effect.");
25130 }
25131 }
25132
25133 var error = clearCaughtError();
25134 captureCommitPhaseError(nextEffect, error);
25135 nextEffect = nextEffect.nextEffect;
25136 }
25137 }
25138 } while (nextEffect !== null);
25139
25140 stopCommitSnapshotEffectsTimer();
25141
25142 if (enableProfilerTimer) {
25143 // Mark the current commit time to be shared by all Profilers in this
25144 // batch. This enables them to be grouped later.
25145 recordCommitTime();
25146 } // The next phase is the mutation phase, where we mutate the host tree.
25147
25148
25149 startCommitHostEffectsTimer();
25150 nextEffect = firstEffect;
25151
25152 do {
25153 {
25154 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
25155
25156 if (hasCaughtError()) {
25157 if (!(nextEffect !== null)) {
25158 {
25159 throw Error("Should be working on an effect.");
25160 }
25161 }
25162
25163 var _error = clearCaughtError();
25164
25165 captureCommitPhaseError(nextEffect, _error);
25166 nextEffect = nextEffect.nextEffect;
25167 }
25168 }
25169 } while (nextEffect !== null);
25170
25171 stopCommitHostEffectsTimer();
25172 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
25173 // the mutation phase, so that the previous tree is still current during
25174 // componentWillUnmount, but before the layout phase, so that the finished
25175 // work is current during componentDidMount/Update.
25176
25177 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
25178 // the host tree after it's been mutated. The idiomatic use case for this is
25179 // layout, but class component lifecycles also fire here for legacy reasons.
25180
25181 startCommitLifeCyclesTimer();
25182 nextEffect = firstEffect;
25183
25184 do {
25185 {
25186 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
25187
25188 if (hasCaughtError()) {
25189 if (!(nextEffect !== null)) {
25190 {
25191 throw Error("Should be working on an effect.");
25192 }
25193 }
25194
25195 var _error2 = clearCaughtError();
25196
25197 captureCommitPhaseError(nextEffect, _error2);
25198 nextEffect = nextEffect.nextEffect;
25199 }
25200 }
25201 } while (nextEffect !== null);
25202
25203 stopCommitLifeCyclesTimer();
25204 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
25205 // opportunity to paint.
25206
25207 requestPaint();
25208
25209 if (enableSchedulerTracing) {
25210 popInteractions(prevInteractions);
25211 }
25212
25213 executionContext = prevExecutionContext;
25214 } else {
25215 // No effects.
25216 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
25217 // no effects.
25218 // TODO: Maybe there's a better way to report this.
25219
25220 startCommitSnapshotEffectsTimer();
25221 stopCommitSnapshotEffectsTimer();
25222
25223 if (enableProfilerTimer) {
25224 recordCommitTime();
25225 }
25226
25227 startCommitHostEffectsTimer();
25228 stopCommitHostEffectsTimer();
25229 startCommitLifeCyclesTimer();
25230 stopCommitLifeCyclesTimer();
25231 }
25232
25233 stopCommitTimer();
25234 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
25235
25236 if (rootDoesHavePassiveEffects) {
25237 // This commit has passive effects. Stash a reference to them. But don't
25238 // schedule a callback until after flushing layout work.
25239 rootDoesHavePassiveEffects = false;
25240 rootWithPendingPassiveEffects = root;
25241 pendingPassiveEffectsExpirationTime = expirationTime;
25242 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
25243 } else {
25244 // We are done with the effect chain at this point so let's clear the
25245 // nextEffect pointers to assist with GC. If we have passive effects, we'll
25246 // clear this in flushPassiveEffects.
25247 nextEffect = firstEffect;
25248
25249 while (nextEffect !== null) {
25250 var nextNextEffect = nextEffect.nextEffect;
25251 nextEffect.nextEffect = null;
25252 nextEffect = nextNextEffect;
25253 }
25254 } // Check if there's remaining work on this root
25255
25256
25257 var remainingExpirationTime = root.firstPendingTime;
25258
25259 if (remainingExpirationTime !== NoWork) {
25260 if (enableSchedulerTracing) {
25261 if (spawnedWorkDuringRender !== null) {
25262 var expirationTimes = spawnedWorkDuringRender;
25263 spawnedWorkDuringRender = null;
25264
25265 for (var i = 0; i < expirationTimes.length; i++) {
25266 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
25267 }
25268 }
25269
25270 schedulePendingInteractions(root, remainingExpirationTime);
25271 }
25272 } else {
25273 // If there's no remaining work, we can clear the set of already failed
25274 // error boundaries.
25275 legacyErrorBoundariesThatAlreadyFailed = null;
25276 }
25277
25278 if (enableSchedulerTracing) {
25279 if (!rootDidHavePassiveEffects) {
25280 // If there are no passive effects, then we can complete the pending interactions.
25281 // Otherwise, we'll wait until after the passive effects are flushed.
25282 // Wait to do this until after remaining work has been scheduled,
25283 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
25284 finishPendingInteractions(root, expirationTime);
25285 }
25286 }
25287
25288 if (remainingExpirationTime === Sync) {
25289 // Count the number of times the root synchronously re-renders without
25290 // finishing. If there are too many, it indicates an infinite update loop.
25291 if (root === rootWithNestedUpdates) {
25292 nestedUpdateCount++;
25293 } else {
25294 nestedUpdateCount = 0;
25295 rootWithNestedUpdates = root;
25296 }
25297 } else {
25298 nestedUpdateCount = 0;
25299 }
25300
25301 onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
25302 // additional work on this root is scheduled.
25303
25304 ensureRootIsScheduled(root);
25305
25306 if (hasUncaughtError) {
25307 hasUncaughtError = false;
25308 var _error3 = firstUncaughtError;
25309 firstUncaughtError = null;
25310 throw _error3;
25311 }
25312
25313 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
25314 // This is a legacy edge case. We just committed the initial mount of
25315 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
25316 // synchronously, but layout updates should be deferred until the end
25317 // of the batch.
25318 return null;
25319 } // If layout work was scheduled, flush it now.
25320
25321
25322 flushSyncCallbackQueue();
25323 return null;
25324}
25325
25326function commitBeforeMutationEffects() {
25327 while (nextEffect !== null) {
25328 var effectTag = nextEffect.effectTag;
25329
25330 if ((effectTag & Snapshot) !== NoEffect) {
25331 setCurrentFiber(nextEffect);
25332 recordEffect();
25333 var current$$1 = nextEffect.alternate;
25334 commitBeforeMutationLifeCycles(current$$1, nextEffect);
25335 resetCurrentFiber();
25336 }
25337
25338 if ((effectTag & Passive) !== NoEffect) {
25339 // If there are passive effects, schedule a callback to flush at
25340 // the earliest opportunity.
25341 if (!rootDoesHavePassiveEffects) {
25342 rootDoesHavePassiveEffects = true;
25343 scheduleCallback(NormalPriority, function () {
25344 flushPassiveEffects();
25345 return null;
25346 });
25347 }
25348 }
25349
25350 nextEffect = nextEffect.nextEffect;
25351 }
25352}
25353
25354function commitMutationEffects(root, renderPriorityLevel) {
25355 // TODO: Should probably move the bulk of this function to commitWork.
25356 while (nextEffect !== null) {
25357 setCurrentFiber(nextEffect);
25358 var effectTag = nextEffect.effectTag;
25359
25360 if (effectTag & ContentReset) {
25361 commitResetTextContent(nextEffect);
25362 }
25363
25364 if (effectTag & Ref) {
25365 var current$$1 = nextEffect.alternate;
25366
25367 if (current$$1 !== null) {
25368 commitDetachRef(current$$1);
25369 }
25370 } // The following switch statement is only concerned about placement,
25371 // updates, and deletions. To avoid needing to add a case for every possible
25372 // bitmap value, we remove the secondary effects from the effect tag and
25373 // switch on that value.
25374
25375
25376 var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
25377
25378 switch (primaryEffectTag) {
25379 case Placement:
25380 {
25381 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25382 // inserted, before any life-cycles like componentDidMount gets called.
25383 // TODO: findDOMNode doesn't rely on this any more but isMounted does
25384 // and isMounted is deprecated anyway so we should be able to kill this.
25385
25386 nextEffect.effectTag &= ~Placement;
25387 break;
25388 }
25389
25390 case PlacementAndUpdate:
25391 {
25392 // Placement
25393 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
25394 // inserted, before any life-cycles like componentDidMount gets called.
25395
25396 nextEffect.effectTag &= ~Placement; // Update
25397
25398 var _current = nextEffect.alternate;
25399 commitWork(_current, nextEffect);
25400 break;
25401 }
25402
25403 case Hydrating:
25404 {
25405 nextEffect.effectTag &= ~Hydrating;
25406 break;
25407 }
25408
25409 case HydratingAndUpdate:
25410 {
25411 nextEffect.effectTag &= ~Hydrating; // Update
25412
25413 var _current2 = nextEffect.alternate;
25414 commitWork(_current2, nextEffect);
25415 break;
25416 }
25417
25418 case Update:
25419 {
25420 var _current3 = nextEffect.alternate;
25421 commitWork(_current3, nextEffect);
25422 break;
25423 }
25424
25425 case Deletion:
25426 {
25427 commitDeletion(root, nextEffect, renderPriorityLevel);
25428 break;
25429 }
25430 } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
25431
25432
25433 recordEffect();
25434 resetCurrentFiber();
25435 nextEffect = nextEffect.nextEffect;
25436 }
25437}
25438
25439function commitLayoutEffects(root, committedExpirationTime) {
25440 // TODO: Should probably move the bulk of this function to commitWork.
25441 while (nextEffect !== null) {
25442 setCurrentFiber(nextEffect);
25443 var effectTag = nextEffect.effectTag;
25444
25445 if (effectTag & (Update | Callback)) {
25446 recordEffect();
25447 var current$$1 = nextEffect.alternate;
25448 commitLifeCycles(root, current$$1, nextEffect, committedExpirationTime);
25449 }
25450
25451 if (effectTag & Ref) {
25452 recordEffect();
25453 commitAttachRef(nextEffect);
25454 }
25455
25456 resetCurrentFiber();
25457 nextEffect = nextEffect.nextEffect;
25458 }
25459}
25460
25461function flushPassiveEffects() {
25462 if (pendingPassiveEffectsRenderPriority !== NoPriority) {
25463 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
25464 pendingPassiveEffectsRenderPriority = NoPriority;
25465 return runWithPriority$2(priorityLevel, flushPassiveEffectsImpl);
25466 }
25467}
25468
25469function flushPassiveEffectsImpl() {
25470 if (rootWithPendingPassiveEffects === null) {
25471 return false;
25472 }
25473
25474 var root = rootWithPendingPassiveEffects;
25475 var expirationTime = pendingPassiveEffectsExpirationTime;
25476 rootWithPendingPassiveEffects = null;
25477 pendingPassiveEffectsExpirationTime = NoWork;
25478
25479 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
25480 {
25481 throw Error("Cannot flush passive effects while already rendering.");
25482 }
25483 }
25484
25485 var prevExecutionContext = executionContext;
25486 executionContext |= CommitContext;
25487 var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root
25488 // fiber, because the root is not part of its own effect list. This could
25489 // change in the future.
25490
25491 var effect = root.current.firstEffect;
25492
25493 while (effect !== null) {
25494 {
25495 setCurrentFiber(effect);
25496 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
25497
25498 if (hasCaughtError()) {
25499 if (!(effect !== null)) {
25500 {
25501 throw Error("Should be working on an effect.");
25502 }
25503 }
25504
25505 var error = clearCaughtError();
25506 captureCommitPhaseError(effect, error);
25507 }
25508
25509 resetCurrentFiber();
25510 }
25511
25512 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
25513
25514 effect.nextEffect = null;
25515 effect = nextNextEffect;
25516 }
25517
25518 if (enableSchedulerTracing) {
25519 popInteractions(prevInteractions);
25520 finishPendingInteractions(root, expirationTime);
25521 }
25522
25523 executionContext = prevExecutionContext;
25524 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
25525 // exceeds the limit, we'll fire a warning.
25526
25527 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
25528 return true;
25529}
25530
25531function isAlreadyFailedLegacyErrorBoundary(instance) {
25532 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
25533}
25534function markLegacyErrorBoundaryAsFailed(instance) {
25535 if (legacyErrorBoundariesThatAlreadyFailed === null) {
25536 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
25537 } else {
25538 legacyErrorBoundariesThatAlreadyFailed.add(instance);
25539 }
25540}
25541
25542function prepareToThrowUncaughtError(error) {
25543 if (!hasUncaughtError) {
25544 hasUncaughtError = true;
25545 firstUncaughtError = error;
25546 }
25547}
25548
25549var onUncaughtError = prepareToThrowUncaughtError;
25550
25551function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
25552 var errorInfo = createCapturedValue(error, sourceFiber);
25553 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
25554 enqueueUpdate(rootFiber, update);
25555 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
25556
25557 if (root !== null) {
25558 ensureRootIsScheduled(root);
25559 schedulePendingInteractions(root, Sync);
25560 }
25561}
25562
25563function captureCommitPhaseError(sourceFiber, error) {
25564 if (sourceFiber.tag === HostRoot) {
25565 // Error was thrown at the root. There is no parent, so the root
25566 // itself should capture it.
25567 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
25568 return;
25569 }
25570
25571 var fiber = sourceFiber.return;
25572
25573 while (fiber !== null) {
25574 if (fiber.tag === HostRoot) {
25575 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
25576 return;
25577 } else if (fiber.tag === ClassComponent) {
25578 var ctor = fiber.type;
25579 var instance = fiber.stateNode;
25580
25581 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
25582 var errorInfo = createCapturedValue(error, sourceFiber);
25583 var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
25584 Sync);
25585 enqueueUpdate(fiber, update);
25586 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
25587
25588 if (root !== null) {
25589 ensureRootIsScheduled(root);
25590 schedulePendingInteractions(root, Sync);
25591 }
25592
25593 return;
25594 }
25595 }
25596
25597 fiber = fiber.return;
25598 }
25599}
25600function pingSuspendedRoot(root, thenable, suspendedTime) {
25601 var pingCache = root.pingCache;
25602
25603 if (pingCache !== null) {
25604 // The thenable resolved, so we no longer need to memoize, because it will
25605 // never be thrown again.
25606 pingCache.delete(thenable);
25607 }
25608
25609 if (workInProgressRoot === root && renderExpirationTime === suspendedTime) {
25610 // Received a ping at the same priority level at which we're currently
25611 // rendering. We might want to restart this render. This should mirror
25612 // the logic of whether or not a root suspends once it completes.
25613 // TODO: If we're rendering sync either due to Sync, Batched or expired,
25614 // we should probably never restart.
25615 // If we're suspended with delay, we'll always suspend so we can always
25616 // restart. If we're suspended without any updates, it might be a retry.
25617 // If it's early in the retry we can restart. We can't know for sure
25618 // whether we'll eventually process an update during this render pass,
25619 // but it's somewhat unlikely that we get to a ping before that, since
25620 // getting to the root most update is usually very fast.
25621 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
25622 // Restart from the root. Don't need to schedule a ping because
25623 // we're already working on this tree.
25624 prepareFreshStack(root, renderExpirationTime);
25625 } else {
25626 // Even though we can't restart right now, we might get an
25627 // opportunity later. So we mark this render as having a ping.
25628 workInProgressRootHasPendingPing = true;
25629 }
25630
25631 return;
25632 }
25633
25634 if (!isRootSuspendedAtTime(root, suspendedTime)) {
25635 // The root is no longer suspended at this time.
25636 return;
25637 }
25638
25639 var lastPingedTime = root.lastPingedTime;
25640
25641 if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
25642 // There's already a lower priority ping scheduled.
25643 return;
25644 } // Mark the time at which this ping was scheduled.
25645
25646
25647 root.lastPingedTime = suspendedTime;
25648
25649 if (root.finishedExpirationTime === suspendedTime) {
25650 // If there's a pending fallback waiting to commit, throw it away.
25651 root.finishedExpirationTime = NoWork;
25652 root.finishedWork = null;
25653 }
25654
25655 ensureRootIsScheduled(root);
25656 schedulePendingInteractions(root, suspendedTime);
25657}
25658
25659function retryTimedOutBoundary(boundaryFiber, retryTime) {
25660 // The boundary fiber (a Suspense component or SuspenseList component)
25661 // previously was rendered in its fallback state. One of the promises that
25662 // suspended it has resolved, which means at least part of the tree was
25663 // likely unblocked. Try rendering again, at a new expiration time.
25664 if (retryTime === NoWork) {
25665 var suspenseConfig = null; // Retries don't carry over the already committed update.
25666
25667 var currentTime = requestCurrentTimeForUpdate();
25668 retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
25669 } // TODO: Special case idle priority?
25670
25671
25672 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
25673
25674 if (root !== null) {
25675 ensureRootIsScheduled(root);
25676 schedulePendingInteractions(root, retryTime);
25677 }
25678}
25679
25680function retryDehydratedSuspenseBoundary(boundaryFiber) {
25681 var suspenseState = boundaryFiber.memoizedState;
25682 var retryTime = NoWork;
25683
25684 if (suspenseState !== null) {
25685 retryTime = suspenseState.retryTime;
25686 }
25687
25688 retryTimedOutBoundary(boundaryFiber, retryTime);
25689}
25690function resolveRetryThenable(boundaryFiber, thenable) {
25691 var retryTime = NoWork; // Default
25692
25693 var retryCache;
25694
25695 if (enableSuspenseServerRenderer) {
25696 switch (boundaryFiber.tag) {
25697 case SuspenseComponent:
25698 retryCache = boundaryFiber.stateNode;
25699 var suspenseState = boundaryFiber.memoizedState;
25700
25701 if (suspenseState !== null) {
25702 retryTime = suspenseState.retryTime;
25703 }
25704
25705 break;
25706
25707 case SuspenseListComponent:
25708 retryCache = boundaryFiber.stateNode;
25709 break;
25710
25711 default:
25712 {
25713 {
25714 throw Error("Pinged unknown suspense boundary type. This is probably a bug in React.");
25715 }
25716 }
25717
25718 }
25719 } else {
25720 retryCache = boundaryFiber.stateNode;
25721 }
25722
25723 if (retryCache !== null) {
25724 // The thenable resolved, so we no longer need to memoize, because it will
25725 // never be thrown again.
25726 retryCache.delete(thenable);
25727 }
25728
25729 retryTimedOutBoundary(boundaryFiber, retryTime);
25730} // Computes the next Just Noticeable Difference (JND) boundary.
25731// The theory is that a person can't tell the difference between small differences in time.
25732// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
25733// difference in the experience. However, waiting for longer might mean that we can avoid
25734// showing an intermediate loading state. The longer we have already waited, the harder it
25735// is to tell small differences in time. Therefore, the longer we've already waited,
25736// the longer we can wait additionally. At some point we have to give up though.
25737// We pick a train model where the next boundary commits at a consistent schedule.
25738// These particular numbers are vague estimates. We expect to adjust them based on research.
25739
25740function jnd(timeElapsed) {
25741 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
25742}
25743
25744function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
25745 var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
25746
25747 if (busyMinDurationMs <= 0) {
25748 return 0;
25749 }
25750
25751 var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
25752
25753 var currentTimeMs = now();
25754 var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
25755 var timeElapsed = currentTimeMs - eventTimeMs;
25756
25757 if (timeElapsed <= busyDelayMs) {
25758 // If we haven't yet waited longer than the initial delay, we don't
25759 // have to wait any additional time.
25760 return 0;
25761 }
25762
25763 var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
25764
25765 return msUntilTimeout;
25766}
25767
25768function checkForNestedUpdates() {
25769 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
25770 nestedUpdateCount = 0;
25771 rootWithNestedUpdates = null;
25772
25773 {
25774 {
25775 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.");
25776 }
25777 }
25778 }
25779
25780 {
25781 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
25782 nestedPassiveUpdateCount = 0;
25783 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.');
25784 }
25785 }
25786}
25787
25788function flushRenderPhaseStrictModeWarningsInDEV() {
25789 {
25790 ReactStrictModeWarnings.flushLegacyContextWarning();
25791
25792 if (warnAboutDeprecatedLifecycles) {
25793 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
25794 }
25795 }
25796}
25797
25798function stopFinishedWorkLoopTimer() {
25799 var didCompleteRoot = true;
25800 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25801 interruptedBy = null;
25802}
25803
25804function stopInterruptedWorkLoopTimer() {
25805 // TODO: Track which fiber caused the interruption.
25806 var didCompleteRoot = false;
25807 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
25808 interruptedBy = null;
25809}
25810
25811function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
25812 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime) {
25813 interruptedBy = fiberThatReceivedUpdate;
25814 }
25815}
25816
25817var didWarnStateUpdateForUnmountedComponent = null;
25818
25819function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
25820 {
25821 var tag = fiber.tag;
25822
25823 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
25824 // Only warn for user-defined components, not internal ones like Suspense.
25825 return;
25826 } // We show the whole stack but dedupe on the top component's name because
25827 // the problematic code almost always lies inside that component.
25828
25829
25830 var componentName = getComponentName(fiber.type) || 'ReactComponent';
25831
25832 if (didWarnStateUpdateForUnmountedComponent !== null) {
25833 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
25834 return;
25835 }
25836
25837 didWarnStateUpdateForUnmountedComponent.add(componentName);
25838 } else {
25839 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
25840 }
25841
25842 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));
25843 }
25844}
25845
25846var beginWork$$1;
25847
25848if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
25849 var dummyFiber = null;
25850
25851 beginWork$$1 = function (current$$1, unitOfWork, expirationTime) {
25852 // If a component throws an error, we replay it again in a synchronously
25853 // dispatched event, so that the debugger will treat it as an uncaught
25854 // error See ReactErrorUtils for more information.
25855 // Before entering the begin phase, copy the work-in-progress onto a dummy
25856 // fiber. If beginWork throws, we'll use this to reset the state.
25857 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
25858
25859 try {
25860 return beginWork$1(current$$1, unitOfWork, expirationTime);
25861 } catch (originalError) {
25862 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
25863 // Don't replay promises. Treat everything else like an error.
25864 throw originalError;
25865 } // Keep this code in sync with handleError; any changes here must have
25866 // corresponding changes there.
25867
25868
25869 resetContextDependencies();
25870 resetHooks(); // Don't reset current debug fiber, since we're about to work on the
25871 // same fiber again.
25872 // Unwind the failed stack frame
25873
25874 unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
25875
25876 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
25877
25878 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
25879 // Reset the profiler timer.
25880 startProfilerTimer(unitOfWork);
25881 } // Run beginWork again.
25882
25883
25884 invokeGuardedCallback(null, beginWork$1, null, current$$1, unitOfWork, expirationTime);
25885
25886 if (hasCaughtError()) {
25887 var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
25888 // Rethrow this error instead of the original one.
25889
25890 throw replayError;
25891 } else {
25892 // This branch is reachable if the render phase is impure.
25893 throw originalError;
25894 }
25895 }
25896 };
25897} else {
25898 beginWork$$1 = beginWork$1;
25899}
25900
25901var didWarnAboutUpdateInRender = false;
25902var didWarnAboutUpdateInGetChildContext = false;
25903
25904function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
25905 {
25906 if (fiber.tag === ClassComponent) {
25907 switch (phase) {
25908 case 'getChildContext':
25909 if (didWarnAboutUpdateInGetChildContext) {
25910 return;
25911 }
25912
25913 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
25914 didWarnAboutUpdateInGetChildContext = true;
25915 break;
25916
25917 case 'render':
25918 if (didWarnAboutUpdateInRender) {
25919 return;
25920 }
25921
25922 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.');
25923 didWarnAboutUpdateInRender = true;
25924 break;
25925 }
25926 }
25927 }
25928} // a 'shared' variable that changes when act() opens/closes in tests.
25929
25930
25931var IsThisRendererActing = {
25932 current: false
25933};
25934function warnIfNotScopedWithMatchingAct(fiber) {
25935 {
25936 if (warnsIfNotActing === true && IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
25937 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));
25938 }
25939 }
25940}
25941function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
25942 {
25943 if (warnsIfNotActing === true && (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25944 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));
25945 }
25946 }
25947}
25948
25949function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
25950 {
25951 if (warnsIfNotActing === true && executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
25952 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));
25953 }
25954 }
25955}
25956
25957var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
25958
25959var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
25960// scheduler is the actual recommendation. The alternative could be a testing build,
25961// a new lib, or whatever; we dunno just yet. This message is for early adopters
25962// to get their tests right.
25963
25964function warnIfUnmockedScheduler(fiber) {
25965 {
25966 if (didWarnAboutUnmockedScheduler === false && unstable_flushAllWithoutAsserting === undefined) {
25967 if (fiber.mode & BatchedMode || fiber.mode & ConcurrentMode) {
25968 didWarnAboutUnmockedScheduler = true;
25969 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');
25970 } else if (warnAboutUnmockedScheduler === true) {
25971 didWarnAboutUnmockedScheduler = true;
25972 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');
25973 }
25974 }
25975 }
25976}
25977var componentsThatTriggeredHighPriSuspend = null;
25978function checkForWrongSuspensePriorityInDEV(sourceFiber) {
25979 {
25980 var currentPriorityLevel = getCurrentPriorityLevel();
25981
25982 if ((sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$2 || currentPriorityLevel === ImmediatePriority)) {
25983 var workInProgressNode = sourceFiber;
25984
25985 while (workInProgressNode !== null) {
25986 // Add the component that triggered the suspense
25987 var current$$1 = workInProgressNode.alternate;
25988
25989 if (current$$1 !== null) {
25990 // TODO: warn component that triggers the high priority
25991 // suspend is the HostRoot
25992 switch (workInProgressNode.tag) {
25993 case ClassComponent:
25994 // Loop through the component's update queue and see whether the component
25995 // has triggered any high priority updates
25996 var updateQueue = current$$1.updateQueue;
25997
25998 if (updateQueue !== null) {
25999 var update = updateQueue.firstUpdate;
26000
26001 while (update !== null) {
26002 var priorityLevel = update.priority;
26003
26004 if (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority) {
26005 if (componentsThatTriggeredHighPriSuspend === null) {
26006 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
26007 } else {
26008 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26009 }
26010
26011 break;
26012 }
26013
26014 update = update.next;
26015 }
26016 }
26017
26018 break;
26019
26020 case FunctionComponent:
26021 case ForwardRef:
26022 case SimpleMemoComponent:
26023 if (workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null) {
26024 var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether
26025 // the component has triggered any high pri updates
26026
26027 while (_update !== null) {
26028 var priority = _update.priority;
26029
26030 if (priority === UserBlockingPriority$2 || priority === ImmediatePriority) {
26031 if (componentsThatTriggeredHighPriSuspend === null) {
26032 componentsThatTriggeredHighPriSuspend = new Set([getComponentName(workInProgressNode.type)]);
26033 } else {
26034 componentsThatTriggeredHighPriSuspend.add(getComponentName(workInProgressNode.type));
26035 }
26036
26037 break;
26038 }
26039
26040 if (_update.next === workInProgressNode.memoizedState.baseUpdate) {
26041 break;
26042 }
26043
26044 _update = _update.next;
26045 }
26046 }
26047
26048 break;
26049
26050 default:
26051 break;
26052 }
26053 }
26054
26055 workInProgressNode = workInProgressNode.return;
26056 }
26057 }
26058 }
26059}
26060
26061function flushSuspensePriorityWarningInDEV() {
26062 {
26063 if (componentsThatTriggeredHighPriSuspend !== null) {
26064 var componentNames = [];
26065 componentsThatTriggeredHighPriSuspend.forEach(function (name) {
26066 return componentNames.push(name);
26067 });
26068 componentsThatTriggeredHighPriSuspend = null;
26069
26070 if (componentNames.length > 0) {
26071 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
26072 componentNames.sort().join(', '));
26073 }
26074 }
26075 }
26076}
26077
26078function computeThreadID(root, expirationTime) {
26079 // Interaction threads are unique per root and expiration time.
26080 return expirationTime * 1000 + root.interactionThreadID;
26081}
26082
26083function markSpawnedWork(expirationTime) {
26084 if (!enableSchedulerTracing) {
26085 return;
26086 }
26087
26088 if (spawnedWorkDuringRender === null) {
26089 spawnedWorkDuringRender = [expirationTime];
26090 } else {
26091 spawnedWorkDuringRender.push(expirationTime);
26092 }
26093}
26094
26095function scheduleInteractions(root, expirationTime, interactions) {
26096 if (!enableSchedulerTracing) {
26097 return;
26098 }
26099
26100 if (interactions.size > 0) {
26101 var pendingInteractionMap = root.pendingInteractionMap;
26102 var pendingInteractions = pendingInteractionMap.get(expirationTime);
26103
26104 if (pendingInteractions != null) {
26105 interactions.forEach(function (interaction) {
26106 if (!pendingInteractions.has(interaction)) {
26107 // Update the pending async work count for previously unscheduled interaction.
26108 interaction.__count++;
26109 }
26110
26111 pendingInteractions.add(interaction);
26112 });
26113 } else {
26114 pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
26115
26116 interactions.forEach(function (interaction) {
26117 interaction.__count++;
26118 });
26119 }
26120
26121 var subscriber = __subscriberRef.current;
26122
26123 if (subscriber !== null) {
26124 var threadID = computeThreadID(root, expirationTime);
26125 subscriber.onWorkScheduled(interactions, threadID);
26126 }
26127 }
26128}
26129
26130function schedulePendingInteractions(root, expirationTime) {
26131 // This is called when work is scheduled on a root.
26132 // It associates the current interactions with the newly-scheduled expiration.
26133 // They will be restored when that expiration is later committed.
26134 if (!enableSchedulerTracing) {
26135 return;
26136 }
26137
26138 scheduleInteractions(root, expirationTime, __interactionsRef.current);
26139}
26140
26141function startWorkOnPendingInteractions(root, expirationTime) {
26142 // This is called when new work is started on a root.
26143 if (!enableSchedulerTracing) {
26144 return;
26145 } // Determine which interactions this batch of work currently includes, So that
26146 // we can accurately attribute time spent working on it, And so that cascading
26147 // work triggered during the render phase will be associated with it.
26148
26149
26150 var interactions = new Set();
26151 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26152 if (scheduledExpirationTime >= expirationTime) {
26153 scheduledInteractions.forEach(function (interaction) {
26154 return interactions.add(interaction);
26155 });
26156 }
26157 }); // Store the current set of interactions on the FiberRoot for a few reasons:
26158 // We can re-use it in hot functions like performConcurrentWorkOnRoot()
26159 // without having to recalculate it. We will also use it in commitWork() to
26160 // pass to any Profiler onRender() hooks. This also provides DevTools with a
26161 // way to access it when the onCommitRoot() hook is called.
26162
26163 root.memoizedInteractions = interactions;
26164
26165 if (interactions.size > 0) {
26166 var subscriber = __subscriberRef.current;
26167
26168 if (subscriber !== null) {
26169 var threadID = computeThreadID(root, expirationTime);
26170
26171 try {
26172 subscriber.onWorkStarted(interactions, threadID);
26173 } catch (error) {
26174 // If the subscriber throws, rethrow it in a separate task
26175 scheduleCallback(ImmediatePriority, function () {
26176 throw error;
26177 });
26178 }
26179 }
26180 }
26181}
26182
26183function finishPendingInteractions(root, committedExpirationTime) {
26184 if (!enableSchedulerTracing) {
26185 return;
26186 }
26187
26188 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
26189 var subscriber;
26190
26191 try {
26192 subscriber = __subscriberRef.current;
26193
26194 if (subscriber !== null && root.memoizedInteractions.size > 0) {
26195 var threadID = computeThreadID(root, committedExpirationTime);
26196 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
26197 }
26198 } catch (error) {
26199 // If the subscriber throws, rethrow it in a separate task
26200 scheduleCallback(ImmediatePriority, function () {
26201 throw error;
26202 });
26203 } finally {
26204 // Clear completed interactions from the pending Map.
26205 // Unless the render was suspended or cascading work was scheduled,
26206 // In which case– leave pending interactions until the subsequent render.
26207 var pendingInteractionMap = root.pendingInteractionMap;
26208 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
26209 // Only decrement the pending interaction count if we're done.
26210 // If there's still work at the current priority,
26211 // That indicates that we are waiting for suspense data.
26212 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
26213 pendingInteractionMap.delete(scheduledExpirationTime);
26214 scheduledInteractions.forEach(function (interaction) {
26215 interaction.__count--;
26216
26217 if (subscriber !== null && interaction.__count === 0) {
26218 try {
26219 subscriber.onInteractionScheduledWorkCompleted(interaction);
26220 } catch (error) {
26221 // If the subscriber throws, rethrow it in a separate task
26222 scheduleCallback(ImmediatePriority, function () {
26223 throw error;
26224 });
26225 }
26226 }
26227 });
26228 }
26229 });
26230 }
26231}
26232
26233var onCommitFiberRoot = null;
26234var onCommitFiberUnmount = null;
26235var hasLoggedError = false;
26236var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
26237function injectInternals(internals) {
26238 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
26239 // No DevTools
26240 return false;
26241 }
26242
26243 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
26244
26245 if (hook.isDisabled) {
26246 // This isn't a real property on the hook, but it can be set to opt out
26247 // of DevTools integration and associated warnings and logs.
26248 // https://github.com/facebook/react/issues/3877
26249 return true;
26250 }
26251
26252 if (!hook.supportsFiber) {
26253 {
26254 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');
26255 } // DevTools exists, even though it doesn't support Fiber.
26256
26257
26258 return true;
26259 }
26260
26261 try {
26262 var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
26263
26264 onCommitFiberRoot = function (root, expirationTime) {
26265 try {
26266 var didError = (root.current.effectTag & DidCapture) === DidCapture;
26267
26268 if (enableProfilerTimer) {
26269 var currentTime = getCurrentTime();
26270 var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
26271 hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
26272 } else {
26273 hook.onCommitFiberRoot(rendererID, root, undefined, didError);
26274 }
26275 } catch (err) {
26276 if (true && !hasLoggedError) {
26277 hasLoggedError = true;
26278 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26279 }
26280 }
26281 };
26282
26283 onCommitFiberUnmount = function (fiber) {
26284 try {
26285 hook.onCommitFiberUnmount(rendererID, fiber);
26286 } catch (err) {
26287 if (true && !hasLoggedError) {
26288 hasLoggedError = true;
26289 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
26290 }
26291 }
26292 };
26293 } catch (err) {
26294 // Catch all errors because it is unsafe to throw during initialization.
26295 {
26296 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
26297 }
26298 } // DevTools exists
26299
26300
26301 return true;
26302}
26303function onCommitRoot(root, expirationTime) {
26304 if (typeof onCommitFiberRoot === 'function') {
26305 onCommitFiberRoot(root, expirationTime);
26306 }
26307}
26308function onCommitUnmount(fiber) {
26309 if (typeof onCommitFiberUnmount === 'function') {
26310 onCommitFiberUnmount(fiber);
26311 }
26312}
26313
26314var hasBadMapPolyfill;
26315
26316{
26317 hasBadMapPolyfill = false;
26318
26319 try {
26320 var nonExtensibleObject = Object.preventExtensions({});
26321 var testMap = new Map([[nonExtensibleObject, null]]);
26322 var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
26323 // https://github.com/rollup/rollup/issues/1771
26324 // TODO: we can remove these if Rollup fixes the bug.
26325
26326 testMap.set(0, 0);
26327 testSet.add(0);
26328 } catch (e) {
26329 // TODO: Consider warning about bad polyfills
26330 hasBadMapPolyfill = true;
26331 }
26332}
26333
26334var debugCounter = 1;
26335
26336function FiberNode(tag, pendingProps, key, mode) {
26337 // Instance
26338 this.tag = tag;
26339 this.key = key;
26340 this.elementType = null;
26341 this.type = null;
26342 this.stateNode = null; // Fiber
26343
26344 this.return = null;
26345 this.child = null;
26346 this.sibling = null;
26347 this.index = 0;
26348 this.ref = null;
26349 this.pendingProps = pendingProps;
26350 this.memoizedProps = null;
26351 this.updateQueue = null;
26352 this.memoizedState = null;
26353 this.dependencies = null;
26354 this.mode = mode; // Effects
26355
26356 this.effectTag = NoEffect;
26357 this.nextEffect = null;
26358 this.firstEffect = null;
26359 this.lastEffect = null;
26360 this.expirationTime = NoWork;
26361 this.childExpirationTime = NoWork;
26362 this.alternate = null;
26363
26364 if (enableProfilerTimer) {
26365 // Note: The following is done to avoid a v8 performance cliff.
26366 //
26367 // Initializing the fields below to smis and later updating them with
26368 // double values will cause Fibers to end up having separate shapes.
26369 // This behavior/bug has something to do with Object.preventExtension().
26370 // Fortunately this only impacts DEV builds.
26371 // Unfortunately it makes React unusably slow for some applications.
26372 // To work around this, initialize the fields below with doubles.
26373 //
26374 // Learn more about this here:
26375 // https://github.com/facebook/react/issues/14365
26376 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
26377 this.actualDuration = Number.NaN;
26378 this.actualStartTime = Number.NaN;
26379 this.selfBaseDuration = Number.NaN;
26380 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
26381 // This won't trigger the performance cliff mentioned above,
26382 // and it simplifies other profiler code (including DevTools).
26383
26384 this.actualDuration = 0;
26385 this.actualStartTime = -1;
26386 this.selfBaseDuration = 0;
26387 this.treeBaseDuration = 0;
26388 } // This is normally DEV-only except www when it adds listeners.
26389 // TODO: remove the User Timing integration in favor of Root Events.
26390
26391
26392 if (enableUserTimingAPI) {
26393 this._debugID = debugCounter++;
26394 this._debugIsCurrentlyTiming = false;
26395 }
26396
26397 {
26398 this._debugSource = null;
26399 this._debugOwner = null;
26400 this._debugNeedsRemount = false;
26401 this._debugHookTypes = null;
26402
26403 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
26404 Object.preventExtensions(this);
26405 }
26406 }
26407} // This is a constructor function, rather than a POJO constructor, still
26408// please ensure we do the following:
26409// 1) Nobody should add any instance methods on this. Instance methods can be
26410// more difficult to predict when they get optimized and they are almost
26411// never inlined properly in static compilers.
26412// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
26413// always know when it is a fiber.
26414// 3) We might want to experiment with using numeric keys since they are easier
26415// to optimize in a non-JIT environment.
26416// 4) We can easily go from a constructor to a createFiber object literal if that
26417// is faster.
26418// 5) It should be easy to port this to a C struct and keep a C implementation
26419// compatible.
26420
26421
26422var createFiber = function (tag, pendingProps, key, mode) {
26423 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
26424 return new FiberNode(tag, pendingProps, key, mode);
26425};
26426
26427function shouldConstruct(Component) {
26428 var prototype = Component.prototype;
26429 return !!(prototype && prototype.isReactComponent);
26430}
26431
26432function isSimpleFunctionComponent(type) {
26433 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
26434}
26435function resolveLazyComponentTag(Component) {
26436 if (typeof Component === 'function') {
26437 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
26438 } else if (Component !== undefined && Component !== null) {
26439 var $$typeof = Component.$$typeof;
26440
26441 if ($$typeof === REACT_FORWARD_REF_TYPE) {
26442 return ForwardRef;
26443 }
26444
26445 if ($$typeof === REACT_MEMO_TYPE) {
26446 return MemoComponent;
26447 }
26448 }
26449
26450 return IndeterminateComponent;
26451} // This is used to create an alternate fiber to do work on.
26452
26453function createWorkInProgress(current, pendingProps, expirationTime) {
26454 var workInProgress = current.alternate;
26455
26456 if (workInProgress === null) {
26457 // We use a double buffering pooling technique because we know that we'll
26458 // only ever need at most two versions of a tree. We pool the "other" unused
26459 // node that we're free to reuse. This is lazily created to avoid allocating
26460 // extra objects for things that are never updated. It also allow us to
26461 // reclaim the extra memory if needed.
26462 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
26463 workInProgress.elementType = current.elementType;
26464 workInProgress.type = current.type;
26465 workInProgress.stateNode = current.stateNode;
26466
26467 {
26468 // DEV-only fields
26469 workInProgress._debugID = current._debugID;
26470 workInProgress._debugSource = current._debugSource;
26471 workInProgress._debugOwner = current._debugOwner;
26472 workInProgress._debugHookTypes = current._debugHookTypes;
26473 }
26474
26475 workInProgress.alternate = current;
26476 current.alternate = workInProgress;
26477 } else {
26478 workInProgress.pendingProps = pendingProps; // We already have an alternate.
26479 // Reset the effect tag.
26480
26481 workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
26482
26483 workInProgress.nextEffect = null;
26484 workInProgress.firstEffect = null;
26485 workInProgress.lastEffect = null;
26486
26487 if (enableProfilerTimer) {
26488 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
26489 // This prevents time from endlessly accumulating in new commits.
26490 // This has the downside of resetting values for different priority renders,
26491 // But works for yielding (the common case) and should support resuming.
26492 workInProgress.actualDuration = 0;
26493 workInProgress.actualStartTime = -1;
26494 }
26495 }
26496
26497 workInProgress.childExpirationTime = current.childExpirationTime;
26498 workInProgress.expirationTime = current.expirationTime;
26499 workInProgress.child = current.child;
26500 workInProgress.memoizedProps = current.memoizedProps;
26501 workInProgress.memoizedState = current.memoizedState;
26502 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26503 // it cannot be shared with the current fiber.
26504
26505 var currentDependencies = current.dependencies;
26506 workInProgress.dependencies = currentDependencies === null ? null : {
26507 expirationTime: currentDependencies.expirationTime,
26508 firstContext: currentDependencies.firstContext,
26509 responders: currentDependencies.responders
26510 }; // These will be overridden during the parent's reconciliation
26511
26512 workInProgress.sibling = current.sibling;
26513 workInProgress.index = current.index;
26514 workInProgress.ref = current.ref;
26515
26516 if (enableProfilerTimer) {
26517 workInProgress.selfBaseDuration = current.selfBaseDuration;
26518 workInProgress.treeBaseDuration = current.treeBaseDuration;
26519 }
26520
26521 {
26522 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
26523
26524 switch (workInProgress.tag) {
26525 case IndeterminateComponent:
26526 case FunctionComponent:
26527 case SimpleMemoComponent:
26528 workInProgress.type = resolveFunctionForHotReloading(current.type);
26529 break;
26530
26531 case ClassComponent:
26532 workInProgress.type = resolveClassForHotReloading(current.type);
26533 break;
26534
26535 case ForwardRef:
26536 workInProgress.type = resolveForwardRefForHotReloading(current.type);
26537 break;
26538
26539 default:
26540 break;
26541 }
26542 }
26543
26544 return workInProgress;
26545} // Used to reuse a Fiber for a second pass.
26546
26547function resetWorkInProgress(workInProgress, renderExpirationTime) {
26548 // This resets the Fiber to what createFiber or createWorkInProgress would
26549 // have set the values to before during the first pass. Ideally this wouldn't
26550 // be necessary but unfortunately many code paths reads from the workInProgress
26551 // when they should be reading from current and writing to workInProgress.
26552 // We assume pendingProps, index, key, ref, return are still untouched to
26553 // avoid doing another reconciliation.
26554 // Reset the effect tag but keep any Placement tags, since that's something
26555 // that child fiber is setting, not the reconciliation.
26556 workInProgress.effectTag &= Placement; // The effect list is no longer valid.
26557
26558 workInProgress.nextEffect = null;
26559 workInProgress.firstEffect = null;
26560 workInProgress.lastEffect = null;
26561 var current = workInProgress.alternate;
26562
26563 if (current === null) {
26564 // Reset to createFiber's initial values.
26565 workInProgress.childExpirationTime = NoWork;
26566 workInProgress.expirationTime = renderExpirationTime;
26567 workInProgress.child = null;
26568 workInProgress.memoizedProps = null;
26569 workInProgress.memoizedState = null;
26570 workInProgress.updateQueue = null;
26571 workInProgress.dependencies = null;
26572
26573 if (enableProfilerTimer) {
26574 // Note: We don't reset the actualTime counts. It's useful to accumulate
26575 // actual time across multiple render passes.
26576 workInProgress.selfBaseDuration = 0;
26577 workInProgress.treeBaseDuration = 0;
26578 }
26579 } else {
26580 // Reset to the cloned values that createWorkInProgress would've.
26581 workInProgress.childExpirationTime = current.childExpirationTime;
26582 workInProgress.expirationTime = current.expirationTime;
26583 workInProgress.child = current.child;
26584 workInProgress.memoizedProps = current.memoizedProps;
26585 workInProgress.memoizedState = current.memoizedState;
26586 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
26587 // it cannot be shared with the current fiber.
26588
26589 var currentDependencies = current.dependencies;
26590 workInProgress.dependencies = currentDependencies === null ? null : {
26591 expirationTime: currentDependencies.expirationTime,
26592 firstContext: currentDependencies.firstContext,
26593 responders: currentDependencies.responders
26594 };
26595
26596 if (enableProfilerTimer) {
26597 // Note: We don't reset the actualTime counts. It's useful to accumulate
26598 // actual time across multiple render passes.
26599 workInProgress.selfBaseDuration = current.selfBaseDuration;
26600 workInProgress.treeBaseDuration = current.treeBaseDuration;
26601 }
26602 }
26603
26604 return workInProgress;
26605}
26606function createHostRootFiber(tag) {
26607 var mode;
26608
26609 if (tag === ConcurrentRoot) {
26610 mode = ConcurrentMode | BatchedMode | StrictMode;
26611 } else if (tag === BatchedRoot) {
26612 mode = BatchedMode | StrictMode;
26613 } else {
26614 mode = NoMode;
26615 }
26616
26617 if (enableProfilerTimer && isDevToolsPresent) {
26618 // Always collect profile timings when DevTools are present.
26619 // This enables DevTools to start capturing timing at any point–
26620 // Without some nodes in the tree having empty base times.
26621 mode |= ProfileMode;
26622 }
26623
26624 return createFiber(HostRoot, null, null, mode);
26625}
26626function createFiberFromTypeAndProps(type, // React$ElementType
26627key, pendingProps, owner, mode, expirationTime) {
26628 var fiber;
26629 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
26630
26631 var resolvedType = type;
26632
26633 if (typeof type === 'function') {
26634 if (shouldConstruct(type)) {
26635 fiberTag = ClassComponent;
26636
26637 {
26638 resolvedType = resolveClassForHotReloading(resolvedType);
26639 }
26640 } else {
26641 {
26642 resolvedType = resolveFunctionForHotReloading(resolvedType);
26643 }
26644 }
26645 } else if (typeof type === 'string') {
26646 fiberTag = HostComponent;
26647 } else {
26648 getTag: switch (type) {
26649 case REACT_FRAGMENT_TYPE:
26650 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
26651
26652 case REACT_CONCURRENT_MODE_TYPE:
26653 fiberTag = Mode;
26654 mode |= ConcurrentMode | BatchedMode | StrictMode;
26655 break;
26656
26657 case REACT_STRICT_MODE_TYPE:
26658 fiberTag = Mode;
26659 mode |= StrictMode;
26660 break;
26661
26662 case REACT_PROFILER_TYPE:
26663 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
26664
26665 case REACT_SUSPENSE_TYPE:
26666 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
26667
26668 case REACT_SUSPENSE_LIST_TYPE:
26669 return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
26670
26671 default:
26672 {
26673 if (typeof type === 'object' && type !== null) {
26674 switch (type.$$typeof) {
26675 case REACT_PROVIDER_TYPE:
26676 fiberTag = ContextProvider;
26677 break getTag;
26678
26679 case REACT_CONTEXT_TYPE:
26680 // This is a consumer
26681 fiberTag = ContextConsumer;
26682 break getTag;
26683
26684 case REACT_FORWARD_REF_TYPE:
26685 fiberTag = ForwardRef;
26686
26687 {
26688 resolvedType = resolveForwardRefForHotReloading(resolvedType);
26689 }
26690
26691 break getTag;
26692
26693 case REACT_MEMO_TYPE:
26694 fiberTag = MemoComponent;
26695 break getTag;
26696
26697 case REACT_LAZY_TYPE:
26698 fiberTag = LazyComponent;
26699 resolvedType = null;
26700 break getTag;
26701
26702 case REACT_FUNDAMENTAL_TYPE:
26703 if (enableFundamentalAPI) {
26704 return createFiberFromFundamental(type, pendingProps, mode, expirationTime, key);
26705 }
26706
26707 break;
26708
26709 case REACT_SCOPE_TYPE:
26710 if (enableScopeAPI) {
26711 return createFiberFromScope(type, pendingProps, mode, expirationTime, key);
26712 }
26713
26714 }
26715 }
26716
26717 var info = '';
26718
26719 {
26720 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
26721 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.';
26722 }
26723
26724 var ownerName = owner ? getComponentName(owner.type) : null;
26725
26726 if (ownerName) {
26727 info += '\n\nCheck the render method of `' + ownerName + '`.';
26728 }
26729 }
26730
26731 {
26732 {
26733 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);
26734 }
26735 }
26736 }
26737 }
26738 }
26739
26740 fiber = createFiber(fiberTag, pendingProps, key, mode);
26741 fiber.elementType = type;
26742 fiber.type = resolvedType;
26743 fiber.expirationTime = expirationTime;
26744 return fiber;
26745}
26746function createFiberFromElement(element, mode, expirationTime) {
26747 var owner = null;
26748
26749 {
26750 owner = element._owner;
26751 }
26752
26753 var type = element.type;
26754 var key = element.key;
26755 var pendingProps = element.props;
26756 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
26757
26758 {
26759 fiber._debugSource = element._source;
26760 fiber._debugOwner = element._owner;
26761 }
26762
26763 return fiber;
26764}
26765function createFiberFromFragment(elements, mode, expirationTime, key) {
26766 var fiber = createFiber(Fragment, elements, key, mode);
26767 fiber.expirationTime = expirationTime;
26768 return fiber;
26769}
26770function createFiberFromFundamental(fundamentalComponent, pendingProps, mode, expirationTime, key) {
26771 var fiber = createFiber(FundamentalComponent, pendingProps, key, mode);
26772 fiber.elementType = fundamentalComponent;
26773 fiber.type = fundamentalComponent;
26774 fiber.expirationTime = expirationTime;
26775 return fiber;
26776}
26777
26778function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) {
26779 var fiber = createFiber(ScopeComponent, pendingProps, key, mode);
26780 fiber.type = scope;
26781 fiber.elementType = scope;
26782 fiber.expirationTime = expirationTime;
26783 return fiber;
26784}
26785
26786function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
26787 {
26788 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
26789 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
26790 }
26791 }
26792
26793 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
26794
26795 fiber.elementType = REACT_PROFILER_TYPE;
26796 fiber.type = REACT_PROFILER_TYPE;
26797 fiber.expirationTime = expirationTime;
26798 return fiber;
26799}
26800
26801function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
26802 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
26803 // This needs to be fixed in getComponentName so that it relies on the tag
26804 // instead.
26805
26806 fiber.type = REACT_SUSPENSE_TYPE;
26807 fiber.elementType = REACT_SUSPENSE_TYPE;
26808 fiber.expirationTime = expirationTime;
26809 return fiber;
26810}
26811function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
26812 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
26813
26814 {
26815 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
26816 // This needs to be fixed in getComponentName so that it relies on the tag
26817 // instead.
26818 fiber.type = REACT_SUSPENSE_LIST_TYPE;
26819 }
26820
26821 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
26822 fiber.expirationTime = expirationTime;
26823 return fiber;
26824}
26825function createFiberFromText(content, mode, expirationTime) {
26826 var fiber = createFiber(HostText, content, null, mode);
26827 fiber.expirationTime = expirationTime;
26828 return fiber;
26829}
26830function createFiberFromHostInstanceForDeletion() {
26831 var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
26832
26833 fiber.elementType = 'DELETED';
26834 fiber.type = 'DELETED';
26835 return fiber;
26836}
26837function createFiberFromDehydratedFragment(dehydratedNode) {
26838 var fiber = createFiber(DehydratedFragment, null, null, NoMode);
26839 fiber.stateNode = dehydratedNode;
26840 return fiber;
26841}
26842function createFiberFromPortal(portal, mode, expirationTime) {
26843 var pendingProps = portal.children !== null ? portal.children : [];
26844 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
26845 fiber.expirationTime = expirationTime;
26846 fiber.stateNode = {
26847 containerInfo: portal.containerInfo,
26848 pendingChildren: null,
26849 // Used by persistent updates
26850 implementation: portal.implementation
26851 };
26852 return fiber;
26853} // Used for stashing WIP properties to replay failed work in DEV.
26854
26855function assignFiberPropertiesInDEV(target, source) {
26856 if (target === null) {
26857 // This Fiber's initial properties will always be overwritten.
26858 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
26859 target = createFiber(IndeterminateComponent, null, null, NoMode);
26860 } // This is intentionally written as a list of all properties.
26861 // We tried to use Object.assign() instead but this is called in
26862 // the hottest path, and Object.assign() was too slow:
26863 // https://github.com/facebook/react/issues/12502
26864 // This code is DEV-only so size is not a concern.
26865
26866
26867 target.tag = source.tag;
26868 target.key = source.key;
26869 target.elementType = source.elementType;
26870 target.type = source.type;
26871 target.stateNode = source.stateNode;
26872 target.return = source.return;
26873 target.child = source.child;
26874 target.sibling = source.sibling;
26875 target.index = source.index;
26876 target.ref = source.ref;
26877 target.pendingProps = source.pendingProps;
26878 target.memoizedProps = source.memoizedProps;
26879 target.updateQueue = source.updateQueue;
26880 target.memoizedState = source.memoizedState;
26881 target.dependencies = source.dependencies;
26882 target.mode = source.mode;
26883 target.effectTag = source.effectTag;
26884 target.nextEffect = source.nextEffect;
26885 target.firstEffect = source.firstEffect;
26886 target.lastEffect = source.lastEffect;
26887 target.expirationTime = source.expirationTime;
26888 target.childExpirationTime = source.childExpirationTime;
26889 target.alternate = source.alternate;
26890
26891 if (enableProfilerTimer) {
26892 target.actualDuration = source.actualDuration;
26893 target.actualStartTime = source.actualStartTime;
26894 target.selfBaseDuration = source.selfBaseDuration;
26895 target.treeBaseDuration = source.treeBaseDuration;
26896 }
26897
26898 target._debugID = source._debugID;
26899 target._debugSource = source._debugSource;
26900 target._debugOwner = source._debugOwner;
26901 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
26902 target._debugNeedsRemount = source._debugNeedsRemount;
26903 target._debugHookTypes = source._debugHookTypes;
26904 return target;
26905}
26906
26907function FiberRootNode(containerInfo, tag, hydrate) {
26908 this.tag = tag;
26909 this.current = null;
26910 this.containerInfo = containerInfo;
26911 this.pendingChildren = null;
26912 this.pingCache = null;
26913 this.finishedExpirationTime = NoWork;
26914 this.finishedWork = null;
26915 this.timeoutHandle = noTimeout;
26916 this.context = null;
26917 this.pendingContext = null;
26918 this.hydrate = hydrate;
26919 this.callbackNode = null;
26920 this.callbackPriority = NoPriority;
26921 this.firstPendingTime = NoWork;
26922 this.firstSuspendedTime = NoWork;
26923 this.lastSuspendedTime = NoWork;
26924 this.nextKnownPendingLevel = NoWork;
26925 this.lastPingedTime = NoWork;
26926 this.lastExpiredTime = NoWork;
26927
26928 if (enableSchedulerTracing) {
26929 this.interactionThreadID = unstable_getThreadID();
26930 this.memoizedInteractions = new Set();
26931 this.pendingInteractionMap = new Map();
26932 }
26933
26934 if (enableSuspenseCallback) {
26935 this.hydrationCallbacks = null;
26936 }
26937}
26938
26939function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
26940 var root = new FiberRootNode(containerInfo, tag, hydrate);
26941
26942 if (enableSuspenseCallback) {
26943 root.hydrationCallbacks = hydrationCallbacks;
26944 } // Cyclic construction. This cheats the type system right now because
26945 // stateNode is any.
26946
26947
26948 var uninitializedFiber = createHostRootFiber(tag);
26949 root.current = uninitializedFiber;
26950 uninitializedFiber.stateNode = root;
26951 return root;
26952}
26953function isRootSuspendedAtTime(root, expirationTime) {
26954 var firstSuspendedTime = root.firstSuspendedTime;
26955 var lastSuspendedTime = root.lastSuspendedTime;
26956 return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
26957}
26958function markRootSuspendedAtTime(root, expirationTime) {
26959 var firstSuspendedTime = root.firstSuspendedTime;
26960 var lastSuspendedTime = root.lastSuspendedTime;
26961
26962 if (firstSuspendedTime < expirationTime) {
26963 root.firstSuspendedTime = expirationTime;
26964 }
26965
26966 if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
26967 root.lastSuspendedTime = expirationTime;
26968 }
26969
26970 if (expirationTime <= root.lastPingedTime) {
26971 root.lastPingedTime = NoWork;
26972 }
26973
26974 if (expirationTime <= root.lastExpiredTime) {
26975 root.lastExpiredTime = NoWork;
26976 }
26977}
26978function markRootUpdatedAtTime(root, expirationTime) {
26979 // Update the range of pending times
26980 var firstPendingTime = root.firstPendingTime;
26981
26982 if (expirationTime > firstPendingTime) {
26983 root.firstPendingTime = expirationTime;
26984 } // Update the range of suspended times. Treat everything lower priority or
26985 // equal to this update as unsuspended.
26986
26987
26988 var firstSuspendedTime = root.firstSuspendedTime;
26989
26990 if (firstSuspendedTime !== NoWork) {
26991 if (expirationTime >= firstSuspendedTime) {
26992 // The entire suspended range is now unsuspended.
26993 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
26994 } else if (expirationTime >= root.lastSuspendedTime) {
26995 root.lastSuspendedTime = expirationTime + 1;
26996 } // This is a pending level. Check if it's higher priority than the next
26997 // known pending level.
26998
26999
27000 if (expirationTime > root.nextKnownPendingLevel) {
27001 root.nextKnownPendingLevel = expirationTime;
27002 }
27003 }
27004}
27005function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
27006 // Update the range of pending times
27007 root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
27008 // equal to this update as unsuspended.
27009
27010 if (finishedExpirationTime <= root.lastSuspendedTime) {
27011 // The entire suspended range is now unsuspended.
27012 root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
27013 } else if (finishedExpirationTime <= root.firstSuspendedTime) {
27014 // Part of the suspended range is now unsuspended. Narrow the range to
27015 // include everything between the unsuspended time (non-inclusive) and the
27016 // last suspended time.
27017 root.firstSuspendedTime = finishedExpirationTime - 1;
27018 }
27019
27020 if (finishedExpirationTime <= root.lastPingedTime) {
27021 // Clear the pinged time
27022 root.lastPingedTime = NoWork;
27023 }
27024
27025 if (finishedExpirationTime <= root.lastExpiredTime) {
27026 // Clear the expired time
27027 root.lastExpiredTime = NoWork;
27028 }
27029}
27030function markRootExpiredAtTime(root, expirationTime) {
27031 var lastExpiredTime = root.lastExpiredTime;
27032
27033 if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
27034 root.lastExpiredTime = expirationTime;
27035 }
27036}
27037
27038// This lets us hook into Fiber to debug what it's doing.
27039// See https://github.com/facebook/react/pull/8033.
27040// This is not part of the public API, not even for React DevTools.
27041// You may only inject a debugTool if you work on React Fiber itself.
27042var ReactFiberInstrumentation = {
27043 debugTool: null
27044};
27045var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
27046
27047var didWarnAboutNestedUpdates;
27048var didWarnAboutFindNodeInStrictMode;
27049
27050{
27051 didWarnAboutNestedUpdates = false;
27052 didWarnAboutFindNodeInStrictMode = {};
27053}
27054
27055function getContextForSubtree(parentComponent) {
27056 if (!parentComponent) {
27057 return emptyContextObject;
27058 }
27059
27060 var fiber = get(parentComponent);
27061 var parentContext = findCurrentUnmaskedContext(fiber);
27062
27063 if (fiber.tag === ClassComponent) {
27064 var Component = fiber.type;
27065
27066 if (isContextProvider(Component)) {
27067 return processChildContext(fiber, Component, parentContext);
27068 }
27069 }
27070
27071 return parentContext;
27072}
27073
27074function findHostInstance(component) {
27075 var fiber = get(component);
27076
27077 if (fiber === undefined) {
27078 if (typeof component.render === 'function') {
27079 {
27080 {
27081 throw Error("Unable to find node on an unmounted component.");
27082 }
27083 }
27084 } else {
27085 {
27086 {
27087 throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
27088 }
27089 }
27090 }
27091 }
27092
27093 var hostFiber = findCurrentHostFiber(fiber);
27094
27095 if (hostFiber === null) {
27096 return null;
27097 }
27098
27099 return hostFiber.stateNode;
27100}
27101
27102function findHostInstanceWithWarning(component, methodName) {
27103 {
27104 var fiber = get(component);
27105
27106 if (fiber === undefined) {
27107 if (typeof component.render === 'function') {
27108 {
27109 {
27110 throw Error("Unable to find node on an unmounted component.");
27111 }
27112 }
27113 } else {
27114 {
27115 {
27116 throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
27117 }
27118 }
27119 }
27120 }
27121
27122 var hostFiber = findCurrentHostFiber(fiber);
27123
27124 if (hostFiber === null) {
27125 return null;
27126 }
27127
27128 if (hostFiber.mode & StrictMode) {
27129 var componentName = getComponentName(fiber.type) || 'Component';
27130
27131 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
27132 didWarnAboutFindNodeInStrictMode[componentName] = true;
27133
27134 if (fiber.mode & StrictMode) {
27135 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));
27136 } else {
27137 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));
27138 }
27139 }
27140 }
27141
27142 return hostFiber.stateNode;
27143 }
27144
27145 return findHostInstance(component);
27146}
27147
27148function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
27149 return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks);
27150}
27151function updateContainer(element, container, parentComponent, callback) {
27152 var current$$1 = container.current;
27153 var currentTime = requestCurrentTimeForUpdate();
27154
27155 {
27156 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
27157 if ('undefined' !== typeof jest) {
27158 warnIfUnmockedScheduler(current$$1);
27159 warnIfNotScopedWithMatchingAct(current$$1);
27160 }
27161 }
27162
27163 var suspenseConfig = requestCurrentSuspenseConfig();
27164 var expirationTime = computeExpirationForFiber(currentTime, current$$1, suspenseConfig);
27165
27166 {
27167 if (ReactFiberInstrumentation_1.debugTool) {
27168 if (current$$1.alternate === null) {
27169 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
27170 } else if (element === null) {
27171 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
27172 } else {
27173 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
27174 }
27175 }
27176 }
27177
27178 var context = getContextForSubtree(parentComponent);
27179
27180 if (container.context === null) {
27181 container.context = context;
27182 } else {
27183 container.pendingContext = context;
27184 }
27185
27186 {
27187 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
27188 didWarnAboutNestedUpdates = true;
27189 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');
27190 }
27191 }
27192
27193 var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
27194 // being called "element".
27195
27196 update.payload = {
27197 element: element
27198 };
27199 callback = callback === undefined ? null : callback;
27200
27201 if (callback !== null) {
27202 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
27203 update.callback = callback;
27204 }
27205
27206 enqueueUpdate(current$$1, update);
27207 scheduleWork(current$$1, expirationTime);
27208 return expirationTime;
27209}
27210function getPublicRootInstance(container) {
27211 var containerFiber = container.current;
27212
27213 if (!containerFiber.child) {
27214 return null;
27215 }
27216
27217 switch (containerFiber.child.tag) {
27218 case HostComponent:
27219 return getPublicInstance(containerFiber.child.stateNode);
27220
27221 default:
27222 return containerFiber.child.stateNode;
27223 }
27224}
27225function attemptSynchronousHydration$1(fiber) {
27226 switch (fiber.tag) {
27227 case HostRoot:
27228 var root = fiber.stateNode;
27229
27230 if (root.hydrate) {
27231 // Flush the first scheduled "update".
27232 flushRoot(root, root.firstPendingTime);
27233 }
27234
27235 break;
27236
27237 case SuspenseComponent:
27238 flushSync(function () {
27239 return scheduleWork(fiber, Sync);
27240 }); // If we're still blocked after this, we need to increase
27241 // the priority of any promises resolving within this
27242 // boundary so that they next attempt also has higher pri.
27243
27244 var retryExpTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
27245 markRetryTimeIfNotHydrated(fiber, retryExpTime);
27246 break;
27247 }
27248}
27249
27250function markRetryTimeImpl(fiber, retryTime) {
27251 var suspenseState = fiber.memoizedState;
27252
27253 if (suspenseState !== null && suspenseState.dehydrated !== null) {
27254 if (suspenseState.retryTime < retryTime) {
27255 suspenseState.retryTime = retryTime;
27256 }
27257 }
27258} // Increases the priority of thennables when they resolve within this boundary.
27259
27260
27261function markRetryTimeIfNotHydrated(fiber, retryTime) {
27262 markRetryTimeImpl(fiber, retryTime);
27263 var alternate = fiber.alternate;
27264
27265 if (alternate) {
27266 markRetryTimeImpl(alternate, retryTime);
27267 }
27268}
27269
27270function attemptUserBlockingHydration$1(fiber) {
27271 if (fiber.tag !== SuspenseComponent) {
27272 // We ignore HostRoots here because we can't increase
27273 // their priority and they should not suspend on I/O,
27274 // since you have to wrap anything that might suspend in
27275 // Suspense.
27276 return;
27277 }
27278
27279 var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
27280 scheduleWork(fiber, expTime);
27281 markRetryTimeIfNotHydrated(fiber, expTime);
27282}
27283function attemptContinuousHydration$1(fiber) {
27284 if (fiber.tag !== SuspenseComponent) {
27285 // We ignore HostRoots here because we can't increase
27286 // their priority and they should not suspend on I/O,
27287 // since you have to wrap anything that might suspend in
27288 // Suspense.
27289 return;
27290 }
27291
27292 var expTime = computeContinuousHydrationExpiration(requestCurrentTimeForUpdate());
27293 scheduleWork(fiber, expTime);
27294 markRetryTimeIfNotHydrated(fiber, expTime);
27295}
27296function attemptHydrationAtCurrentPriority$1(fiber) {
27297 if (fiber.tag !== SuspenseComponent) {
27298 // We ignore HostRoots here because we can't increase
27299 // their priority other than synchronously flush it.
27300 return;
27301 }
27302
27303 var currentTime = requestCurrentTimeForUpdate();
27304 var expTime = computeExpirationForFiber(currentTime, fiber, null);
27305 scheduleWork(fiber, expTime);
27306 markRetryTimeIfNotHydrated(fiber, expTime);
27307}
27308function findHostInstanceWithNoPortals(fiber) {
27309 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
27310
27311 if (hostFiber === null) {
27312 return null;
27313 }
27314
27315 if (hostFiber.tag === FundamentalComponent) {
27316 return hostFiber.stateNode.instance;
27317 }
27318
27319 return hostFiber.stateNode;
27320}
27321
27322var shouldSuspendImpl = function (fiber) {
27323 return false;
27324};
27325
27326function shouldSuspend(fiber) {
27327 return shouldSuspendImpl(fiber);
27328}
27329var overrideHookState = null;
27330var overrideProps = null;
27331var scheduleUpdate = null;
27332var setSuspenseHandler = null;
27333
27334{
27335 var copyWithSetImpl = function (obj, path, idx, value) {
27336 if (idx >= path.length) {
27337 return value;
27338 }
27339
27340 var key = path[idx];
27341 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
27342
27343 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
27344 return updated;
27345 };
27346
27347 var copyWithSet = function (obj, path, value) {
27348 return copyWithSetImpl(obj, path, 0, value);
27349 }; // Support DevTools editable values for useState and useReducer.
27350
27351
27352 overrideHookState = function (fiber, id, path, value) {
27353 // For now, the "id" of stateful hooks is just the stateful hook index.
27354 // This may change in the future with e.g. nested hooks.
27355 var currentHook = fiber.memoizedState;
27356
27357 while (currentHook !== null && id > 0) {
27358 currentHook = currentHook.next;
27359 id--;
27360 }
27361
27362 if (currentHook !== null) {
27363 var newState = copyWithSet(currentHook.memoizedState, path, value);
27364 currentHook.memoizedState = newState;
27365 currentHook.baseState = newState; // We aren't actually adding an update to the queue,
27366 // because there is no update we can add for useReducer hooks that won't trigger an error.
27367 // (There's no appropriate action type for DevTools overrides.)
27368 // As a result though, React will see the scheduled update as a noop and bailout.
27369 // Shallow cloning props works as a workaround for now to bypass the bailout check.
27370
27371 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
27372 scheduleWork(fiber, Sync);
27373 }
27374 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
27375
27376
27377 overrideProps = function (fiber, path, value) {
27378 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
27379
27380 if (fiber.alternate) {
27381 fiber.alternate.pendingProps = fiber.pendingProps;
27382 }
27383
27384 scheduleWork(fiber, Sync);
27385 };
27386
27387 scheduleUpdate = function (fiber) {
27388 scheduleWork(fiber, Sync);
27389 };
27390
27391 setSuspenseHandler = function (newShouldSuspendImpl) {
27392 shouldSuspendImpl = newShouldSuspendImpl;
27393 };
27394}
27395
27396function injectIntoDevTools(devToolsConfig) {
27397 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
27398 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
27399 return injectInternals(_assign({}, devToolsConfig, {
27400 overrideHookState: overrideHookState,
27401 overrideProps: overrideProps,
27402 setSuspenseHandler: setSuspenseHandler,
27403 scheduleUpdate: scheduleUpdate,
27404 currentDispatcherRef: ReactCurrentDispatcher,
27405 findHostInstanceByFiber: function (fiber) {
27406 var hostFiber = findCurrentHostFiber(fiber);
27407
27408 if (hostFiber === null) {
27409 return null;
27410 }
27411
27412 return hostFiber.stateNode;
27413 },
27414 findFiberByHostInstance: function (instance) {
27415 if (!findFiberByHostInstance) {
27416 // Might not be implemented by the renderer.
27417 return null;
27418 }
27419
27420 return findFiberByHostInstance(instance);
27421 },
27422 // React Refresh
27423 findHostInstancesForRefresh: findHostInstancesForRefresh,
27424 scheduleRefresh: scheduleRefresh,
27425 scheduleRoot: scheduleRoot,
27426 setRefreshHandler: setRefreshHandler,
27427 // Enables DevTools to append owner stacks to error messages in DEV mode.
27428 getCurrentFiber: function () {
27429 return current;
27430 }
27431 }));
27432}
27433
27434// This file intentionally does *not* have the Flow annotation.
27435// Don't add it. See `./inline-typed.js` for an explanation.
27436
27437function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
27438implementation) {
27439 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
27440 return {
27441 // This tag allow us to uniquely identify this as a React Portal
27442 $$typeof: REACT_PORTAL_TYPE,
27443 key: key == null ? null : '' + key,
27444 children: children,
27445 containerInfo: containerInfo,
27446 implementation: implementation
27447 };
27448}
27449
27450// TODO: this is special because it gets imported during build.
27451
27452var ReactVersion = '16.11.0';
27453
27454// TODO: This type is shared between the reconciler and ReactDOM, but will
27455// eventually be lifted out to the renderer.
27456setAttemptSynchronousHydration(attemptSynchronousHydration$1);
27457setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);
27458setAttemptContinuousHydration(attemptContinuousHydration$1);
27459setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
27460var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
27461var topLevelUpdateWarnings;
27462var warnOnInvalidCallback;
27463var didWarnAboutUnstableCreatePortal = false;
27464
27465{
27466 if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
27467 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
27468 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
27469 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');
27470 }
27471
27472 topLevelUpdateWarnings = function (container) {
27473 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
27474 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
27475
27476 if (hostInstance) {
27477 !(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;
27478 }
27479 }
27480
27481 var isRootRenderedBySomeReact = !!container._reactRootContainer;
27482 var rootEl = getReactRootElementInContainer(container);
27483 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
27484 !(!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;
27485 !(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;
27486 };
27487
27488 warnOnInvalidCallback = function (callback, callerName) {
27489 !(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;
27490 };
27491}
27492
27493setRestoreImplementation(restoreControlledState$$1);
27494
27495function createRootImpl(container, tag, options) {
27496 // Tag is either LegacyRoot or Concurrent Root
27497 var hydrate = options != null && options.hydrate === true;
27498 var hydrationCallbacks = options != null && options.hydrationOptions || null;
27499 var root = createContainer(container, tag, hydrate, hydrationCallbacks);
27500 markContainerAsRoot(root.current, container);
27501
27502 if (hydrate && tag !== LegacyRoot) {
27503 var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
27504 eagerlyTrapReplayableEvents(doc);
27505 }
27506
27507 return root;
27508}
27509
27510function ReactSyncRoot(container, tag, options) {
27511 this._internalRoot = createRootImpl(container, tag, options);
27512}
27513
27514function ReactRoot(container, options) {
27515 this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
27516}
27517
27518ReactRoot.prototype.render = ReactSyncRoot.prototype.render = function (children, callback) {
27519 var root = this._internalRoot;
27520 callback = callback === undefined ? null : callback;
27521
27522 {
27523 warnOnInvalidCallback(callback, 'render');
27524 }
27525
27526 updateContainer(children, root, null, callback);
27527};
27528
27529ReactRoot.prototype.unmount = ReactSyncRoot.prototype.unmount = function (callback) {
27530 var root = this._internalRoot;
27531 callback = callback === undefined ? null : callback;
27532
27533 {
27534 warnOnInvalidCallback(callback, 'render');
27535 }
27536
27537 updateContainer(null, root, null, callback);
27538};
27539/**
27540 * True if the supplied DOM node is a valid node element.
27541 *
27542 * @param {?DOMElement} node The candidate DOM node.
27543 * @return {boolean} True if the DOM is a valid DOM node.
27544 * @internal
27545 */
27546
27547
27548function isValidContainer(node) {
27549 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 '));
27550}
27551
27552function getReactRootElementInContainer(container) {
27553 if (!container) {
27554 return null;
27555 }
27556
27557 if (container.nodeType === DOCUMENT_NODE) {
27558 return container.documentElement;
27559 } else {
27560 return container.firstChild;
27561 }
27562}
27563
27564function shouldHydrateDueToLegacyHeuristic(container) {
27565 var rootElement = getReactRootElementInContainer(container);
27566 return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
27567}
27568
27569setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
27570var warnedAboutHydrateAPI = false;
27571
27572function legacyCreateRootFromDOMContainer(container, forceHydrate) {
27573 var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
27574
27575 if (!shouldHydrate) {
27576 var warned = false;
27577 var rootSibling;
27578
27579 while (rootSibling = container.lastChild) {
27580 {
27581 if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
27582 warned = true;
27583 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.');
27584 }
27585 }
27586
27587 container.removeChild(rootSibling);
27588 }
27589 }
27590
27591 {
27592 if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
27593 warnedAboutHydrateAPI = true;
27594 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.');
27595 }
27596 } // Legacy roots are not batched.
27597
27598
27599 return new ReactSyncRoot(container, LegacyRoot, shouldHydrate ? {
27600 hydrate: true
27601 } : undefined);
27602}
27603
27604function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
27605 {
27606 topLevelUpdateWarnings(container);
27607 warnOnInvalidCallback(callback === undefined ? null : callback, 'render');
27608 } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
27609 // member of intersection type." Whyyyyyy.
27610
27611
27612 var root = container._reactRootContainer;
27613 var fiberRoot;
27614
27615 if (!root) {
27616 // Initial mount
27617 root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
27618 fiberRoot = root._internalRoot;
27619
27620 if (typeof callback === 'function') {
27621 var originalCallback = callback;
27622
27623 callback = function () {
27624 var instance = getPublicRootInstance(fiberRoot);
27625 originalCallback.call(instance);
27626 };
27627 } // Initial mount should not be batched.
27628
27629
27630 unbatchedUpdates(function () {
27631 updateContainer(children, fiberRoot, parentComponent, callback);
27632 });
27633 } else {
27634 fiberRoot = root._internalRoot;
27635
27636 if (typeof callback === 'function') {
27637 var _originalCallback = callback;
27638
27639 callback = function () {
27640 var instance = getPublicRootInstance(fiberRoot);
27641
27642 _originalCallback.call(instance);
27643 };
27644 } // Update
27645
27646
27647 updateContainer(children, fiberRoot, parentComponent, callback);
27648 }
27649
27650 return getPublicRootInstance(fiberRoot);
27651}
27652
27653function createPortal$$1(children, container) {
27654 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
27655
27656 if (!isValidContainer(container)) {
27657 {
27658 throw Error("Target container is not a DOM element.");
27659 }
27660 } // TODO: pass ReactDOM portal implementation as third argument
27661
27662
27663 return createPortal$1(children, container, null, key);
27664}
27665
27666var ReactDOM = {
27667 createPortal: createPortal$$1,
27668 findDOMNode: function (componentOrElement) {
27669 {
27670 var owner = ReactCurrentOwner.current;
27671
27672 if (owner !== null && owner.stateNode !== null) {
27673 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
27674 !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;
27675 owner.stateNode._warnedAboutRefsInRender = true;
27676 }
27677 }
27678
27679 if (componentOrElement == null) {
27680 return null;
27681 }
27682
27683 if (componentOrElement.nodeType === ELEMENT_NODE) {
27684 return componentOrElement;
27685 }
27686
27687 {
27688 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
27689 }
27690
27691 return findHostInstance(componentOrElement);
27692 },
27693 hydrate: function (element, container, callback) {
27694 if (!isValidContainer(container)) {
27695 {
27696 throw Error("Target container is not a DOM element.");
27697 }
27698 }
27699
27700 {
27701 !!container._reactHasBeenPassedToCreateRootDEV ? 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)?') : void 0;
27702 } // TODO: throw or warn if we couldn't hydrate?
27703
27704
27705 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
27706 },
27707 render: function (element, container, callback) {
27708 if (!isValidContainer(container)) {
27709 {
27710 throw Error("Target container is not a DOM element.");
27711 }
27712 }
27713
27714 {
27715 !!container._reactHasBeenPassedToCreateRootDEV ? 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)?') : void 0;
27716 }
27717
27718 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
27719 },
27720 unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) {
27721 if (!isValidContainer(containerNode)) {
27722 {
27723 throw Error("Target container is not a DOM element.");
27724 }
27725 }
27726
27727 if (!(parentComponent != null && has$1(parentComponent))) {
27728 {
27729 throw Error("parentComponent must be a valid React Component");
27730 }
27731 }
27732
27733 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
27734 },
27735 unmountComponentAtNode: function (container) {
27736 if (!isValidContainer(container)) {
27737 {
27738 throw Error("unmountComponentAtNode(...): Target container is not a DOM element.");
27739 }
27740 }
27741
27742 {
27743 !!container._reactHasBeenPassedToCreateRootDEV ? 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()?') : void 0;
27744 }
27745
27746 if (container._reactRootContainer) {
27747 {
27748 var rootEl = getReactRootElementInContainer(container);
27749 var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
27750 !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0;
27751 } // Unmount should not be batched.
27752
27753
27754 unbatchedUpdates(function () {
27755 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
27756 container._reactRootContainer = null;
27757 });
27758 }); // If you call unmountComponentAtNode twice in quick succession, you'll
27759 // get `true` twice. That's probably fine?
27760
27761 return true;
27762 } else {
27763 {
27764 var _rootEl = getReactRootElementInContainer(container);
27765
27766 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
27767
27768 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
27769 !!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;
27770 }
27771
27772 return false;
27773 }
27774 },
27775 // Temporary alias since we already shipped React 16 RC with it.
27776 // TODO: remove in React 17.
27777 unstable_createPortal: function () {
27778 if (!didWarnAboutUnstableCreatePortal) {
27779 didWarnAboutUnstableCreatePortal = true;
27780 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.');
27781 }
27782
27783 return createPortal$$1.apply(void 0, arguments);
27784 },
27785 unstable_batchedUpdates: batchedUpdates$1,
27786 flushSync: flushSync,
27787 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
27788 // Keep in sync with ReactDOMUnstableNativeDependencies.js
27789 // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
27790 Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
27791 }
27792};
27793
27794function createRoot(container, options) {
27795 if (!isValidContainer(container)) {
27796 {
27797 throw Error("createRoot(...): Target container is not a DOM element.");
27798 }
27799 }
27800
27801 warnIfReactDOMContainerInDEV(container);
27802 return new ReactRoot(container, options);
27803}
27804
27805function createSyncRoot(container, options) {
27806 if (!isValidContainer(container)) {
27807 {
27808 throw Error("createRoot(...): Target container is not a DOM element.");
27809 }
27810 }
27811
27812 warnIfReactDOMContainerInDEV(container);
27813 return new ReactSyncRoot(container, BatchedRoot, options);
27814}
27815
27816function warnIfReactDOMContainerInDEV(container) {
27817 {
27818 !!container._reactRootContainer ? warningWithoutStack$1(false, 'You are calling ReactDOM.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.') : void 0;
27819 container._reactHasBeenPassedToCreateRootDEV = true;
27820 }
27821}
27822
27823if (exposeConcurrentModeAPIs) {
27824 ReactDOM.createRoot = createRoot;
27825 ReactDOM.createSyncRoot = createSyncRoot;
27826 ReactDOM.unstable_discreteUpdates = discreteUpdates$1;
27827 ReactDOM.unstable_flushDiscreteUpdates = flushDiscreteUpdates;
27828 ReactDOM.unstable_flushControlled = flushControlled;
27829
27830 ReactDOM.unstable_scheduleHydration = function (target) {
27831 if (target) {
27832 queueExplicitHydrationTarget(target);
27833 }
27834 };
27835}
27836
27837var foundDevTools = injectIntoDevTools({
27838 findFiberByHostInstance: getClosestInstanceFromNode,
27839 bundleType: 1,
27840 version: ReactVersion,
27841 rendererPackageName: 'react-dom'
27842});
27843
27844{
27845 if (!foundDevTools && canUseDOM && window.top === window.self) {
27846 // If we're in Chrome or Firefox, provide a download link if not installed.
27847 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
27848 var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
27849
27850 if (/^(https?|file):$/.test(protocol)) {
27851 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');
27852 }
27853 }
27854 }
27855}
27856
27857
27858
27859var ReactDOM$2 = Object.freeze({
27860 default: ReactDOM
27861});
27862
27863var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2;
27864
27865// TODO: decide on the top-level export form.
27866// This is hacky but makes it work with both Rollup and Jest.
27867
27868
27869var reactDom = ReactDOM$3.default || ReactDOM$3;
27870
27871return reactDom;
27872
27873})));