diff --git a/Libraries/Renderer/REVISION b/Libraries/Renderer/REVISION index b660dbcbc40f42..a297e61c412391 100644 --- a/Libraries/Renderer/REVISION +++ b/Libraries/Renderer/REVISION @@ -1 +1 @@ -85d05b3a4d439c504ee43652d586ee253a01faf6 \ No newline at end of file +4eeee358e12c1408a4b40830bb7bb6956cf26b47 \ No newline at end of file diff --git a/Libraries/Renderer/implementations/ReactFabric-dev.fb.js b/Libraries/Renderer/implementations/ReactFabric-dev.fb.js index ad652486bf7276..1f81ae70321fff 100644 --- a/Libraries/Renderer/implementations/ReactFabric-dev.fb.js +++ b/Libraries/Renderer/implementations/ReactFabric-dev.fb.js @@ -22,15 +22,6 @@ var Scheduler = require("scheduler"); var checkPropTypes = require("prop-types/checkPropTypes"); var tracing = require("scheduler/tracing"); -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. - -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} - /** * Use invariant() to assert state which your program assumes to be true. * @@ -46,76 +37,69 @@ function ReactError(error) { * Injectable ordering of event plugins. */ var eventPluginOrder = null; - /** * Injectable mapping from names to event plugin modules. */ -var namesToPlugins = {}; +var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ + function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } + for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); - (function() { - if (!(pluginIndex > -1)) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) - ); - } - })(); + + if (!(pluginIndex > -1)) { + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + if (plugins[pluginIndex]) { continue; } - (function() { - if (!pluginModule.extractEvents) { - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) - ); - } - })(); + + if (!pluginModule.extractEvents) { + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + } + plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { - (function() { - if ( - !publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ) - ) { - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) - ); - } - })(); + if ( + !publishEventForPlugin( + publishedEvents[eventName], + pluginModule, + eventName + ) + ) { + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } } } } - /** * Publishes an event so that it can be dispatched by the supplied plugin. * @@ -124,21 +108,19 @@ function recomputePluginOrdering() { * @return {boolean} True if the event was successfully published. * @private */ + function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - (function() { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName + - "`." - ) - ); - } - })(); - eventNameDispatchConfigs[eventName] = dispatchConfig; + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." + ); + } + eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { @@ -150,6 +132,7 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); } } + return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( @@ -159,9 +142,9 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); return true; } + return false; } - /** * Publishes a registration name that is used to identify dispatched events. * @@ -169,18 +152,16 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { * @param {object} PluginModule Plugin publishing the event. * @private */ + function publishRegistrationName(registrationName, pluginModule, eventName) { - (function() { - if (!!registrationNameModules[registrationName]) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) - ); - } - })(); + if (!!registrationNameModules[registrationName]) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + registrationNameModules[registrationName] = pluginModule; registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; @@ -189,7 +170,6 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { var lowerCasedName = registrationName.toLowerCase(); } } - /** * Registers plugins so that they can extract and dispatch events. * @@ -199,23 +179,23 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { /** * Ordered list of injected plugins. */ -var plugins = []; +var plugins = []; /** * Mapping from event name to dispatch config */ -var eventNameDispatchConfigs = {}; +var eventNameDispatchConfigs = {}; /** * Mapping from registration name to plugin module */ -var registrationNameModules = {}; +var registrationNameModules = {}; /** * Mapping from registration name to event name */ -var registrationNameDependencies = {}; +var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available @@ -234,21 +214,17 @@ var registrationNameDependencies = {}; * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ + function injectEventPluginOrder(injectedEventPluginOrder) { - (function() { - if (!!eventPluginOrder) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) - ); - } - })(); - // Clone the ordering so it cannot be dynamically mutated. + if (!!eventPluginOrder) { + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." + ); + } // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); } - /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. @@ -259,32 +235,34 @@ function injectEventPluginOrder(injectedEventPluginOrder) { * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ + function injectEventPluginsByName(injectedNamesToPlugins) { var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } + var pluginModule = injectedNamesToPlugins[pluginName]; + if ( !namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule ) { - (function() { - if (!!namesToPlugins[pluginName]) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) - ); - } - })(); + if (!!namesToPlugins[pluginName]) { + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } + if (isOrderingDirty) { recomputePluginOrdering(); } @@ -302,6 +280,7 @@ var invokeGuardedCallbackImpl = function( f ) { var funcArgs = Array.prototype.slice.call(arguments, 3); + try { func.apply(context, funcArgs); } catch (error) { @@ -328,7 +307,6 @@ var invokeGuardedCallbackImpl = function( // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if ( @@ -354,52 +332,45 @@ var invokeGuardedCallbackImpl = function( // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebookincubator/create-react-app/issues/3482 // So we preemptively throw with a better message instead. - (function() { - if (!(typeof document !== "undefined")) { - throw ReactError( - Error( - "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." - ) - ); - } - })(); - var evt = document.createEvent("Event"); + if (!(typeof document !== "undefined")) { + 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." + ); + } - // Keeps track of whether the user-provided callback threw an error. We + var evt = document.createEvent("Event"); // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. - var didError = true; - // Keeps track of the value of window.event so that we can reset it + var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. - var windowEvent = window.event; - // Keeps track of the descriptor of window.event to restore it after event + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 + var windowEventDescriptor = Object.getOwnPropertyDescriptor( window, "event" - ); - - // Create an event handler for our fake event. We will synchronously + ); // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - - // We check for window.hasOwnProperty('event') to prevent the + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. + if ( typeof window.event !== "undefined" && window.hasOwnProperty("event") @@ -409,9 +380,7 @@ var invokeGuardedCallbackImpl = function( func.apply(context, funcArgs); didError = false; - } - - // Create a global error event handler. We use this to capture the value + } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of @@ -422,17 +391,20 @@ var invokeGuardedCallbackImpl = function( // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. + + var error; // Use this to track whether the error event is ever called. + var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } + if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. @@ -445,17 +417,14 @@ var invokeGuardedCallbackImpl = function( } } } - } + } // Create a fake event type. - // Create a fake event type. - var evtType = "react-" + (name ? name : "invokeguardedcallback"); + var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - // Attach our event handlers window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); - - // Synchronously dispatch our fake event. If the user-provided function + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); @@ -483,10 +452,10 @@ var invokeGuardedCallbackImpl = function( "See https://fb.me/react-crossorigin-error for more information." ); } + this.onError(error); - } + } // Remove our event listeners - // Remove our event listeners window.removeEventListener("error", handleWindowError); }; @@ -496,21 +465,17 @@ var invokeGuardedCallbackImpl = function( var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// Used by Fiber to simulate a try-catch. var hasError = false; -var caughtError = null; +var caughtError = null; // Used by event system to capture/rethrow the first error. -// Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; - var reporter = { onError: function(error) { hasError = true; caughtError = error; } }; - /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. @@ -524,12 +489,12 @@ var reporter = { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } - /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. @@ -540,6 +505,7 @@ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallbackAndCatchFirstError( name, func, @@ -552,19 +518,21 @@ function invokeGuardedCallbackAndCatchFirstError( f ) { invokeGuardedCallback.apply(this, arguments); + if (hasError) { var error = clearCaughtError(); + if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } - /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ + function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; @@ -573,11 +541,9 @@ function rethrowCaughtError() { throw error; } } - function hasCaughtError() { return hasError; } - function clearCaughtError() { if (hasError) { var error = caughtError; @@ -585,15 +551,11 @@ function clearCaughtError() { caughtError = null; return error; } else { - (function() { - { - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -603,14 +565,13 @@ function clearCaughtError() { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - var warningWithoutStack = function() {}; { warningWithoutStack = function(condition, format) { for ( var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), + args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++ @@ -624,25 +585,28 @@ var warningWithoutStack = function() {}; "message argument" ); } + if (args.length > 8) { // Check before the condition to catch violations early. throw new Error( "warningWithoutStack() currently supports at most 8 arguments." ); } + if (condition) { return; } + if (typeof console !== "undefined") { var argsWithFormat = args.map(function(item) { return "" + item; }); - argsWithFormat.unshift("Warning: " + format); - - // We intentionally don't use spread (or .apply) directly because it + argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 + Function.prototype.apply.call(console.error, console, argsWithFormat); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -663,7 +627,6 @@ var warningWithoutStack$1 = warningWithoutStack; var getFiberCurrentPropsFromNode = null; var getInstanceFromNode = null; var getNodeFromInstance = null; - function setComponentTree( getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, @@ -672,6 +635,7 @@ function setComponentTree( getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode = getInstanceFromNodeImpl; getNodeFromInstance = getNodeFromInstanceImpl; + { !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1( @@ -682,70 +646,69 @@ function setComponentTree( : void 0; } } +var validateEventDispatches; -var validateEventDispatches = void 0; { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, "EventPluginUtils: Invalid `event`.") : void 0; }; } - /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ + function executeDispatch(event, listener, inst) { var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } - /** * Standard/simple iteration through an event's collected dispatches. */ + function executeDispatchesInOrder(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, dispatchListeners, dispatchInstances); } + event._dispatchListeners = null; event._dispatchInstances = null; } - /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. @@ -753,18 +716,21 @@ function executeDispatchesInOrder(event) { * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ + function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } @@ -774,19 +740,19 @@ function executeDispatchesInOrderStopAtTrueImpl(event) { return dispatchInstances; } } + return null; } - /** * @see executeDispatchesInOrderStopAtTrueImpl */ + function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } - /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make @@ -796,17 +762,19 @@ function executeDispatchesInOrderStopAtTrue(event) { * * @return {*} The return value of executing the single dispatch. */ + function executeDirectDispatch(event) { { validateEventDispatches(event); } + var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - (function() { - if (!!Array.isArray(dispatchListener)) { - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); - } - })(); + + if (!!Array.isArray(dispatchListener)) { + throw Error("executeDirectDispatch(...): Invalid `event`."); + } + event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -816,11 +784,11 @@ function executeDirectDispatch(event) { event._dispatchInstances = null; return res; } - /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ + function hasDispatches(event) { return !!event._dispatchListeners; } @@ -839,27 +807,23 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } + current.push(next); return current; } @@ -893,14 +857,15 @@ function forEachAccumulated(arr, cb, scope) { * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ -var eventQueue = null; +var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ + var executeDispatchesAndRelease = function(event) { if (event) { executeDispatchesInOrder(event); @@ -910,6 +875,7 @@ var executeDispatchesAndRelease = function(event) { } } }; + var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(e); }; @@ -917,10 +883,9 @@ var executeDispatchesAndReleaseTopLevel = function(e) { function runEventsInBatch(events) { if (events !== null) { eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more + } // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. + var processingEventQueue = eventQueue; eventQueue = null; @@ -929,16 +894,13 @@ function runEventsInBatch(events) { } forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - (function() { - if (!!eventQueue) { - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) - ); - } - })(); - // This would be a good time to rethrow if any of the event handlers threw. + + if (!!eventQueue) { + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + } // This would be a good time to rethrow if any of the event handlers threw. + rethrowCaughtError(); } @@ -964,11 +926,11 @@ function shouldPreventMouseEvent(name, type, props) { case "onMouseUp": case "onMouseUpCapture": return !!(props.disabled && isInteractive(type)); + default: return false; } } - /** * This is a unified interface for event plugins to be installed and configured. * @@ -995,6 +957,7 @@ function shouldPreventMouseEvent(name, type, props) { /** * Methods for injecting dependencies. */ + var injection = { /** * @param {array} InjectedEventPluginOrder @@ -1007,47 +970,48 @@ var injection = { */ injectEventPluginsByName: injectEventPluginsByName }; - /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ -function getListener(inst, registrationName) { - var listener = void 0; - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not +function getListener(inst, registrationName) { + var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon + var stateNode = inst.stateNode; + if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } + var props = getFiberCurrentPropsFromNode(stateNode); + if (!props) { // Work in progress. return null; } + listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - (function() { - if (!(!listener || typeof listener === "function")) { - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) - ); - } - })(); + + if (!(!listener || typeof listener === "function")) { + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + return listener; } - /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. @@ -1055,28 +1019,35 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ + function extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = null; + for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; + if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); + if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } + return events; } @@ -1084,13 +1055,15 @@ function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); runEventsInBatch(events); } @@ -1098,8 +1071,11 @@ function runExtractedPluginEventsInBatch( var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + var HostComponent = 5; var HostText = 6; var Fragment = 7; @@ -1113,101 +1089,111 @@ var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; -var DehydratedSuspenseComponent = 18; +var DehydratedFragment = 18; var SuspenseListComponent = 19; var FundamentalComponent = 20; +var ScopeComponent = 21; function getParent(inst) { do { - inst = inst.return; - // TODO: If this is a HostRoot we might want to bail out. + inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); + if (inst) { return inst; } + return null; } - /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ + function getLowestCommonAncestor(instA, instB) { var depthA = 0; + for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } + var depthB = 0; + for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; - } + } // If A is deeper, crawl up. - // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; - } + } // If B is deeper, crawl up. - // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; - } + } // Walk in lockstep until we find a match. - // Walk in lockstep until we find a match. var depth = depthA; + while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } + instA = getParent(instA); instB = getParent(instB); } + return null; } - /** * Return if A is an ancestor of B. */ + function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } + instB = getParent(instB); } + return false; } - /** * Return the parent instance of the passed-in instance. */ + function getParentInstance(inst) { return getParent(inst); } - /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ + function traverseTwoPhase(inst, fn, arg) { var path = []; + while (inst) { path.push(inst); inst = getParent(inst); } - var i = void 0; + + var i; + for (i = path.length; i-- > 0; ) { fn(path[i], "captured", arg); } + for (i = 0; i < path.length; i++) { fn(path[i], "bubbled", arg); } } - /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. @@ -1225,7 +1211,6 @@ function listenerAtPhase(inst, event, propagationPhase) { event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } - /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which @@ -1242,13 +1227,16 @@ function listenerAtPhase(inst, event, propagationPhase) { * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ + function accumulateDirectionalDispatches(inst, phase, event) { { !inst ? warningWithoutStack$1(false, "Dispatching inst must not be null") : void 0; } + var listener = listenerAtPhase(inst, event, phase); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1257,7 +1245,6 @@ function accumulateDirectionalDispatches(inst, phase, event) { event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } - /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through @@ -1265,15 +1252,16 @@ function accumulateDirectionalDispatches(inst, phase, event) { * single traversal for the entire collection of events because each event may * have a different target. */ + function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } - /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ + function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; @@ -1281,16 +1269,17 @@ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } - /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ + function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1300,12 +1289,12 @@ function accumulateDispatches(inst, ignoredDirection, event) { } } } - /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ + function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); @@ -1315,7 +1304,6 @@ function accumulateDirectDispatchesSingle(event) { function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } - function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } @@ -1325,13 +1313,12 @@ function accumulateDirectDispatches(events) { } /* eslint valid-typeof: 0 */ - var EVENT_POOL_SIZE = 10; - /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ + var EventInterface = { type: null, target: null, @@ -1356,7 +1343,6 @@ function functionThatReturnsTrue() { function functionThatReturnsFalse() { return false; } - /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. @@ -1375,6 +1361,7 @@ function functionThatReturnsFalse() { * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ + function SyntheticEvent( dispatchConfig, targetInst, @@ -1393,16 +1380,19 @@ function SyntheticEvent( this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; - var Interface = this.constructor.Interface; + for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } + { delete this[propName]; // this has a getter/setter for warnings } + var normalize = Interface[propName]; + if (normalize) { this[propName] = normalize(nativeEvent); } else { @@ -1418,11 +1408,13 @@ function SyntheticEvent( nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } + this.isPropagationStopped = functionThatReturnsFalse; return this; } @@ -1431,6 +1423,7 @@ Object.assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; + if (!event) { return; } @@ -1440,11 +1433,12 @@ Object.assign(SyntheticEvent.prototype, { } else if (typeof event.returnValue !== "unknown") { event.returnValue = false; } + this.isDefaultPrevented = functionThatReturnsTrue; }, - stopPropagation: function() { var event = this.nativeEvent; + if (!event) { return; } @@ -1484,6 +1478,7 @@ Object.assign(SyntheticEvent.prototype, { */ destructor: function() { var Interface = this.constructor.Interface; + for (var propName in Interface) { { Object.defineProperty( @@ -1493,6 +1488,7 @@ Object.assign(SyntheticEvent.prototype, { ); } } + this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; @@ -1500,6 +1496,7 @@ Object.assign(SyntheticEvent.prototype, { this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; + { Object.defineProperty( this, @@ -1535,35 +1532,33 @@ Object.assign(SyntheticEvent.prototype, { } } }); - SyntheticEvent.Interface = EventInterface; - /** * Helper to reduce boilerplate when creating subclasses. */ + SyntheticEvent.extend = function(Interface) { var Super = this; var E = function() {}; + E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } + Object.assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; - Class.Interface = Object.assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); - return Class; }; addEventPoolingTo(SyntheticEvent); - /** * Helper to nullify syntheticEvent instance properties when destructing * @@ -1571,6 +1566,7 @@ addEventPoolingTo(SyntheticEvent); * @param {?object} getVal * @return {object} defineProperty object */ + function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === "function"; return { @@ -1613,6 +1609,7 @@ function getPooledWarningPropertyDefinition(propName, getVal) { function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; + if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call( @@ -1624,6 +1621,7 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { ); return instance; } + return new EventConstructor( dispatchConfig, targetInst, @@ -1634,16 +1632,15 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - (function() { - if (!(event instanceof EventConstructor)) { - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) - ); - } - })(); + + if (!(event instanceof EventConstructor)) { + throw Error( + "Trying to release an event instance into a pool of a different type." + ); + } + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } @@ -1660,6 +1657,7 @@ function addEventPoolingTo(EventConstructor) { * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ + var ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function(nativeEvent) { return null; // Actually doesn't even look at the native event. @@ -1672,19 +1670,15 @@ var TOP_TOUCH_END = "topTouchEnd"; var TOP_TOUCH_CANCEL = "topTouchCancel"; var TOP_SCROLL = "topScroll"; var TOP_SELECTION_CHANGE = "topSelectionChange"; - function isStartish(topLevelType) { return topLevelType === TOP_TOUCH_START; } - function isMoveish(topLevelType) { return topLevelType === TOP_TOUCH_MOVE; } - function isEndish(topLevelType) { return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL; } - var startDependencies = [TOP_TOUCH_START]; var moveDependencies = [TOP_TOUCH_MOVE]; var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END]; @@ -1713,11 +1707,11 @@ function timestampForTouch(touch) { // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } - /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ + function createTouchRecord(touch) { return { touchActive: true, @@ -1749,11 +1743,10 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - (function() { - if (!(identifier != null)) { - throw ReactError(Error("Touch object is missing identifier.")); - } - })(); + if (!(identifier != null)) { + throw Error("Touch object is missing identifier."); + } + { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1765,22 +1758,26 @@ function getTouchIdentifier(_ref) { ) : void 0; } + return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; + if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1802,6 +1799,7 @@ function recordTouchMove(touch) { function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1832,9 +1830,11 @@ function printTouch(touch) { function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + if (touchBank.length > MAX_TOUCH_BANK) { printed += " (original size: " + touchBank.length + ")"; } + return printed; } @@ -1845,6 +1845,7 @@ var ResponderTouchHistoryStore = { } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; @@ -1852,14 +1853,17 @@ var ResponderTouchHistoryStore = { } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; + if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } + { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; !(activeRecord != null && activeRecord.touchActive) @@ -1869,7 +1873,6 @@ var ResponderTouchHistoryStore = { } } }, - touchHistory: touchHistory }; @@ -1880,23 +1883,19 @@ var ResponderTouchHistoryStore = { * * @return {*|array<*>} An accumulation of items. */ + function accumulate(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulate(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { return current.concat(next); } @@ -1912,17 +1911,19 @@ function accumulate(current, next) { * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ -var responderInst = null; +var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ + var trackedTouchCount = 0; var changeResponder = function(nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; + if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange( oldResponderInst, @@ -2025,7 +2026,6 @@ var eventTypes = { dependencies: [] } }; - /** * * Responder System: @@ -2228,17 +2228,15 @@ function setResponderAndExtractTransfer( ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder - : eventTypes.scrollShouldSetResponder; + : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. - // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst - : getLowestCommonAncestor(responderInst, targetInst); - - // When capturing/bubbling the "shouldSet" event, we want to skip the target + : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. + var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent.getPooled( shouldSetEventType, @@ -2247,12 +2245,15 @@ function setResponderAndExtractTransfer( nativeEventTarget ); shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; + if (skipOverBubbleShouldSetFrom) { accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { accumulateTwoPhaseDispatches(shouldSetEvent); } + var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent); + if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } @@ -2260,7 +2261,8 @@ function setResponderAndExtractTransfer( if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } - var extracted = void 0; + + var extracted; var grantEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, wantsResponderInst, @@ -2268,9 +2270,9 @@ function setResponderAndExtractTransfer( nativeEventTarget ); grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; - accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch(grantEvent) === true; + if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderTerminationRequest, @@ -2284,6 +2286,7 @@ function setResponderAndExtractTransfer( var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent); + if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } @@ -2314,9 +2317,9 @@ function setResponderAndExtractTransfer( extracted = accumulate(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } + return extracted; } - /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer @@ -2325,10 +2328,10 @@ function setResponderAndExtractTransfer( * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ + function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return ( - topLevelInst && - // responderIgnoreScroll: We are trying to migrate away from specifically + topLevelInst && // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead ((topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll) || @@ -2337,7 +2340,6 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { isMoveish(topLevelType)) ); } - /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. @@ -2345,22 +2347,28 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ + function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; + if (!touches || touches.length === 0) { return true; } + for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; + if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = getInstanceFromNode(target); + if (isAncestor(responderInst, targetInst)) { return false; } } } + return true; } @@ -2369,7 +2377,6 @@ var ResponderEventPlugin = { _getResponder: function() { return responderInst; }, - eventTypes: eventTypes, /** @@ -2381,7 +2388,8 @@ var ResponderEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (isStartish(topLevelType)) { trackedTouchCount += 1; @@ -2389,7 +2397,7 @@ var ResponderEventPlugin = { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ); return null; @@ -2397,7 +2405,6 @@ var ResponderEventPlugin = { } ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); - var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer( topLevelType, @@ -2405,8 +2412,7 @@ var ResponderEventPlugin = { nativeEvent, nativeEventTarget ) - : null; - // Responder may or may not have transferred on a new touch start/move. + : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional @@ -2416,6 +2422,7 @@ var ResponderEventPlugin = { // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). + var isResponderTouchStart = responderInst && isStartish(topLevelType); var isResponderTouchMove = responderInst && isMoveish(topLevelType); var isResponderTouchEnd = responderInst && isEndish(topLevelType); @@ -2451,6 +2458,7 @@ var ResponderEventPlugin = { : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { var finalEvent = ResponderSyntheticEvent.getPooled( finalTouch, @@ -2466,9 +2474,7 @@ var ResponderEventPlugin = { return extracted; }, - GlobalResponderHandler: null, - injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler @@ -2481,14 +2487,12 @@ var ResponderEventPlugin = { } }; -// Module provided by RN: var customBubblingEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customBubblingEventTypes; var customDirectEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customDirectEventTypes; - var ReactNativeBridgeEventPlugin = { eventTypes: {}, @@ -2499,29 +2503,30 @@ var ReactNativeBridgeEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (targetInst == null) { // Probably a node belonging to another renderer's tree. return null; } + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; var directDispatchConfig = customDirectEventTypes[topLevelType]; - (function() { - if (!(bubbleDispatchConfig || directDispatchConfig)) { - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) - ); - } - })(); + + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget ); + if (bubbleDispatchConfig) { accumulateTwoPhaseDispatches(event); } else if (directDispatchConfig) { @@ -2529,6 +2534,7 @@ var ReactNativeBridgeEventPlugin = { } else { return null; } + return event; } }; @@ -2548,12 +2554,13 @@ var ReactNativeEventPluginOrder = [ /** * Inject module for resolving DOM hierarchy and plugin ordering. */ -injection.injectEventPluginOrder(ReactNativeEventPluginOrder); +injection.injectEventPluginOrder(ReactNativeEventPluginOrder); /** * Some important event plugins included by default (without having to require * them). */ + injection.injectEventPluginsByName({ ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin @@ -2565,11 +2572,11 @@ function getInstanceFromInstance(instanceHandle) { function getTagFromInstance(inst) { var tag = inst.stateNode.canonical._nativeTag; - (function() { - if (!tag) { - throw ReactError(Error("All native instances should have a tag.")); - } - })(); + + if (!tag) { + throw Error("All native instances should have a tag."); + } + return tag; } @@ -2597,7 +2604,6 @@ setComponentTree( getInstanceFromInstance, getTagFromInstance ); - ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactFabricGlobalResponderHandler ); @@ -2627,16 +2633,16 @@ function set(key, value) { } var ReactSharedInternals = - React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -// Prevent newer renderers from RTE when used with older react package versions. + React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentDispatcher")) { ReactSharedInternals.ReactCurrentDispatcher = { current: null }; } + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null @@ -2646,7 +2652,6 @@ if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === "function" && Symbol.for; - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 0xeacb; @@ -2655,8 +2660,7 @@ var REACT_STRICT_MODE_TYPE = hasSymbol : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; -// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_CONCURRENT_MODE_TYPE = hasSymbol @@ -2675,30 +2679,105 @@ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 0xead6; - +var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } + var maybeIterator = (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { return maybeIterator; } + return null; } +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = warningWithoutStack$1; + +{ + warning = function(condition, format) { + if (condition) { + return; + } + + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args + + for ( + var _len = arguments.length, + args = new Array(_len > 2 ? _len - 2 : 0), + _key = 2; + _key < _len; + _key++ + ) { + args[_key - 2] = arguments[_key]; + } + + warningWithoutStack$1.apply( + void 0, + [false, format + "%s"].concat(args, [stack]) + ); + }; +} + +var warning$1 = warning; + +var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; - function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then( + function(moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; + + { + if (defaultExport === undefined) { + 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 + ); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, + function(error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + } + ); + } +} function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ""; @@ -2713,6 +2792,7 @@ function getComponentName(type) { // Host root, text node or just invalid type. return null; } + { if (typeof type.tag === "number") { warningWithoutStack$1( @@ -2722,78 +2802,127 @@ function getComponentName(type) { ); } } + if (typeof type === "function") { return type.displayName || type.name || null; } + if (typeof type === "string") { return type; } + switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; + case REACT_PORTAL_TYPE: return "Portal"; + case REACT_PROFILER_TYPE: return "Profiler"; + case REACT_STRICT_MODE_TYPE: return "StrictMode"; + case REACT_SUSPENSE_TYPE: return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } + if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return "Context.Consumer"; + case REACT_PROVIDER_TYPE: return "Context.Provider"; + case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: return getComponentName(type.type); + case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); + if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; } } } + return null; } // Don't change these two values. They're used by React Dev Tools. -var NoEffect = /* */ 0; -var PerformedWork = /* */ 1; - -// You can change the rest (and add more). -var Placement = /* */ 2; -var Update = /* */ 4; -var PlacementAndUpdate = /* */ 6; -var Deletion = /* */ 8; -var ContentReset = /* */ 16; -var Callback = /* */ 32; -var DidCapture = /* */ 64; -var Ref = /* */ 128; -var Snapshot = /* */ 256; -var Passive = /* */ 512; - -// Passive & Update & Callback & Ref & Snapshot -var LifecycleEffectMask = /* */ 932; - -// Union of all host effects -var HostEffectMask = /* */ 1023; - -var Incomplete = /* */ 1024; -var ShouldCapture = /* */ 2048; +var NoEffect = + /* */ + 0; +var PerformedWork = + /* */ + 1; // You can change the rest (and add more). + +var Placement = + /* */ + 2; +var Update = + /* */ + 4; +var PlacementAndUpdate = + /* */ + 6; +var Deletion = + /* */ + 8; +var ContentReset = + /* */ + 16; +var Callback = + /* */ + 32; +var DidCapture = + /* */ + 64; +var Ref = + /* */ + 128; +var Snapshot = + /* */ + 256; +var Passive = + /* */ + 512; +var Hydrating = + /* */ + 1024; +var HydratingAndUpdate = + /* */ + 1028; // Passive & Update & Callback & Ref & Snapshot + +var LifecycleEffectMask = + /* */ + 932; // Union of all host effects + +var HostEffectMask = + /* */ + 2047; +var Incomplete = + /* */ + 2048; +var ShouldCapture = + /* */ + 4096; // Re-export dynamic flags from the fbsource version. var _require = require("../shims/ReactFeatureFlags"); - -var debugRenderPhaseSideEffects = _require.debugRenderPhaseSideEffects; +var debugRenderPhaseSideEffects = _require.debugRenderPhaseSideEffects; // The rest of the flags are static for better dead code elimination. var enableUserTimingAPI = true; var enableProfilerTimer = true; @@ -2806,61 +2935,64 @@ var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; var warnAboutDeprecatedLifecycles = true; var enableFlareAPI = false; var enableFundamentalAPI = false; +var enableScopeAPI = false; var warnAboutUnmockedScheduler = true; -var revertPassiveEffectsChange = false; var flushSuspenseFallbacksInTests = true; -var enableUserBlockingEvents = false; var enableSuspenseCallback = false; var warnAboutDefaultPropsOnFunctionComponents = false; var warnAboutStringRefs = false; var disableLegacyContext = false; var disableSchedulerTimeoutBasedOnReactExpirationTime = false; - // Only used in www builds. -var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; +// Flow magic to verify the exports of this file match the original version. -function isFiberMountedImpl(fiber) { +var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; +function getNearestMountedFiber(fiber) { var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node.return) { - node = node.return; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; + var nextNode = node; + + do { + node = nextNode; + + if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; } - } + + nextNode = node.return; + } while (nextNode); } else { while (node.return) { node = node.return; } } + if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. - return UNMOUNTED; + + return null; } function isFiberMounted(fiber) { - return isFiberMountedImpl(fiber) === MOUNTED; + return getNearestMountedFiber(fiber) === fiber; } - function isMounted(component) { { var owner = ReactCurrentOwner$1.current; + if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; @@ -2880,90 +3012,93 @@ function isMounted(component) { } var fiber = get(component); + if (!fiber) { return false; } - return isFiberMountedImpl(fiber) === MOUNTED; + + return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { - (function() { - if (!(isFiberMountedImpl(fiber) === MOUNTED)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); - } - })(); + if (!(getNearestMountedFiber(fiber) === fiber)) { + throw Error("Unable to find node on an unmounted component."); + } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; + if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. - var state = isFiberMountedImpl(fiber); - (function() { - if (!(state !== UNMOUNTED)) { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - if (state === MOUNTING) { + var nearestMounted = getNearestMountedFiber(fiber); + + if (!(nearestMounted !== null)) { + throw Error("Unable to find node on an unmounted component."); + } + + if (nearestMounted !== fiber) { return null; } + return fiber; - } - // If we have two possible branches, we'll walk backwards up to the root + } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. + var a = fiber; var b = alternate; + while (true) { var parentA = a.return; + if (parentA === null) { // We're at the root. break; } + var parentB = parentA.alternate; + if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; + if (nextParent !== null) { a = b = nextParent; continue; - } - // If there's no parent, we're at the root. - break; - } + } // If there's no parent, we're at the root. - // If both copies of the parent fiber point to the same child, we can + break; + } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. + if (parentA.child === parentB.child) { var child = parentA.child; + while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } + if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } + child = child.sibling; - } - // We should never have an alternate for any mounting node. So the only + } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); + + { + throw Error("Unable to find node on an unmounted component."); + } } if (a.return !== b.return) { @@ -2981,6 +3116,7 @@ function findCurrentFiberUsingSlowPath(fiber) { // Search parent A's child set var didFindChild = false; var _child = parentA.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -2988,17 +3124,21 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentB; break; } + if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } + _child = _child.sibling; } + if (!didFindChild) { // Search parent B's child set _child = parentB.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3006,59 +3146,53 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentA; break; } + if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } + _child = _child.sibling; } - (function() { - if (!didFindChild) { - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) - ); - } - })(); + + if (!didFindChild) { + 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." + ); + } } } - (function() { - if (!(a.alternate === b)) { - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - (function() { - if (!(a.tag === HostRoot)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (!(a.alternate === b)) { + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - })(); + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. + + if (!(a.tag === HostRoot)) { + throw Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; - } - // Otherwise B has to be current branch. + } // Otherwise B has to be current branch. + return alternate; } - function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { return null; - } + } // Next we'll drill down this component to find the first HostComponent/Text. - // Next we'll drill down this component to find the first HostComponent/Text. var node = currentParent; + while (true) { if (node.tag === HostComponent || node.tag === HostText) { return node; @@ -3067,20 +3201,24 @@ function findCurrentHostFiber(parent) { node = node.child; continue; } + if (node === currentParent) { return null; } + while (!node.sibling) { if (!node.return || node.return === currentParent) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. + } // Flow needs the return null here, but ESLint complains about it. // eslint-disable-next-line no-unreachable + return null; } @@ -3092,24 +3230,20 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return function() { if (!callback) { return undefined; - } - // This protects against createClass() components. + } // This protects against createClass() components. // We don't know if there is code depending on it. // We intentionally don't use isMounted() because even accessing // isMounted property on a React ES6 class will trigger a warning. + if (typeof context.__isMounted === "boolean") { if (!context.__isMounted) { return undefined; } - } - - // FIXME: there used to be other branches that protected + } // FIXME: there used to be other branches that protected // against unmounted host components. But RN host components don't // define isMounted() anymore, so those checks didn't do anything. - // They caused false positive warning noise so we removed them: // https://github.com/facebook/react-native/issues/18868#issuecomment-413579095 - // However, this means that the callback is NOT guaranteed to be safe // for host components. The solution we should implement is to make // UIManager.measure() and similar calls truly cancelable. Then we @@ -3118,7 +3252,6 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return callback.apply(context, arguments); }; } - function throwOnStylesProp(component, props) { if (props.styles !== undefined) { var owner = component._owner || null; @@ -3128,6 +3261,7 @@ function throwOnStylesProp(component, props) { name + "`, did " + "you mean `style` (singular)?"; + if (owner && owner.constructor && owner.constructor.displayName) { msg += "\n\nCheck the `" + @@ -3135,10 +3269,10 @@ function throwOnStylesProp(component, props) { "` parent " + " component."; } + throw new Error(msg); } } - function warnForStyleProps(props, validAttributes) { for (var key in validAttributes.style) { if (!(validAttributes[key] || props[key] === undefined)) { @@ -3157,7 +3291,6 @@ function warnForStyleProps(props, validAttributes) { // Modules provided by RN: var emptyObject = {}; - /** * Create a payload that contains all the updates between two sets of props. * @@ -3188,6 +3321,7 @@ function restoreDeletedValuesInNestedArray( ) { if (Array.isArray(node)) { var i = node.length; + while (i-- && removedKeyCount > 0) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3197,16 +3331,20 @@ function restoreDeletedValuesInNestedArray( } } else if (node && removedKeyCount > 0) { var obj = node; + for (var propKey in removedKeys) { if (!removedKeys[propKey]) { continue; } + var nextProp = obj[propKey]; + if (nextProp === undefined) { continue; } var attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3214,6 +3352,7 @@ function restoreDeletedValuesInNestedArray( if (typeof nextProp === "function") { nextProp = true; } + if (typeof nextProp === "undefined") { nextProp = null; } @@ -3232,6 +3371,7 @@ function restoreDeletedValuesInNestedArray( : nextProp; updatePayload[propKey] = nextValue; } + removedKeys[propKey] = false; removedKeyCount--; } @@ -3246,7 +3386,8 @@ function diffNestedArrayProperty( ) { var minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; - var i = void 0; + var i; + for (i = 0; i < minLength; i++) { // Diff any items in the array in the forward direction. Repeated keys // will be overwritten by later values. @@ -3257,6 +3398,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < prevArray.length; i++) { // Clear out all remaining properties. updatePayload = clearNestedProperty( @@ -3265,6 +3407,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < nextArray.length; i++) { // Add all remaining properties. updatePayload = addNestedProperty( @@ -3273,6 +3416,7 @@ function diffNestedArrayProperty( validAttributes ); } + return updatePayload; } @@ -3292,9 +3436,11 @@ function diffNestedProperty( if (nextProp) { return addNestedProperty(updatePayload, nextProp, validAttributes); } + if (prevProp) { return clearNestedProperty(updatePayload, prevProp, validAttributes); } + return updatePayload; } @@ -3315,10 +3461,8 @@ function diffNestedProperty( if (Array.isArray(prevProp)) { return diffProperties( - updatePayload, - // $FlowFixMe - We know that this is always an object when the input is. - ReactNativePrivateInterface.flattenStyle(prevProp), - // $FlowFixMe - We know that this isn't an array because of above flow. + updatePayload, // $FlowFixMe - We know that this is always an object when the input is. + ReactNativePrivateInterface.flattenStyle(prevProp), // $FlowFixMe - We know that this isn't an array because of above flow. nextProp, validAttributes ); @@ -3326,18 +3470,17 @@ function diffNestedProperty( return diffProperties( updatePayload, - prevProp, - // $FlowFixMe - We know that this is always an object when the input is. + prevProp, // $FlowFixMe - We know that this is always an object when the input is. ReactNativePrivateInterface.flattenStyle(nextProp), validAttributes ); } - /** * addNestedProperty takes a single set of props and valid attribute * attribute configurations. It processes each prop and adds it to the * updatePayload. */ + function addNestedProperty(updatePayload, nextProp, validAttributes) { if (!nextProp) { return updatePayload; @@ -3359,11 +3502,11 @@ function addNestedProperty(updatePayload, nextProp, validAttributes) { return updatePayload; } - /** * clearNestedProperty takes a single set of props and valid attributes. It * adds a null sentinel to the updatePayload, for each prop key. */ + function clearNestedProperty(updatePayload, prevProp, validAttributes) { if (!prevProp) { return updatePayload; @@ -3382,44 +3525,45 @@ function clearNestedProperty(updatePayload, prevProp, validAttributes) { validAttributes ); } + return updatePayload; } - /** * diffProperties takes two sets of props and a set of valid attributes * and write to updatePayload the values that changed or were deleted. * If no updatePayload is provided, a new one is created and returned if * anything changed. */ + function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { - var attributeConfig = void 0; - var nextProp = void 0; - var prevProp = void 0; + var attributeConfig; + var nextProp; + var prevProp; for (var propKey in nextProps) { attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } prevProp = prevProps[propKey]; - nextProp = nextProps[propKey]; - - // functions are converted to booleans as markers that the associated + nextProp = nextProps[propKey]; // functions are converted to booleans as markers that the associated // events should be sent from native. + if (typeof nextProp === "function") { - nextProp = true; - // If nextProp is not a function, then don't bother changing prevProp + nextProp = true; // If nextProp is not a function, then don't bother changing prevProp // since nextProp will win and go into the updatePayload regardless. + if (typeof prevProp === "function") { prevProp = true; } - } - - // An explicit value of undefined is treated as a null because it overrides + } // An explicit value of undefined is treated as a null because it overrides // any other preceding value. + if (typeof nextProp === "undefined") { nextProp = null; + if (typeof prevProp === "undefined") { prevProp = null; } @@ -3434,7 +3578,6 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // value diffed. Since we're now later in the nested arrays our value is // more important so we need to calculate it and override the existing // value. It doesn't matter if nothing changed, we'll set it anyway. - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case @@ -3450,14 +3593,14 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { : nextProp; updatePayload[propKey] = nextValue; } + continue; } if (prevProp === nextProp) { continue; // nothing changed - } + } // Pattern match on: attributeConfig - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case if (defaultDiffer(prevProp, nextProp)) { @@ -3474,25 +3617,28 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { (typeof attributeConfig.diff === "function" ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + if (shouldUpdate) { var _nextValue = typeof attributeConfig.process === "function" ? attributeConfig.process(nextProp) : nextProp; + (updatePayload || (updatePayload = {}))[propKey] = _nextValue; } } else { // default: fallthrough case when nested properties are defined removedKeys = null; - removedKeyCount = 0; - // We think that attributeConfig is not CustomAttributeConfiguration at + removedKeyCount = 0; // We think that attributeConfig is not CustomAttributeConfiguration at // this point so we assume it must be AttributeConfiguration. + updatePayload = diffNestedProperty( updatePayload, prevProp, nextProp, attributeConfig ); + if (removedKeyCount > 0 && updatePayload) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3502,16 +3648,17 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { removedKeys = null; } } - } - - // Also iterate through all the previous props to catch any that have been + } // Also iterate through all the previous props to catch any that have been // removed and make sure native gets the signal so it can reset them to the // default. + for (var _propKey in prevProps) { if (nextProps[_propKey] !== undefined) { continue; // we've already covered this key in the previous pass } + attributeConfig = validAttributes[_propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3522,10 +3669,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { } prevProp = prevProps[_propKey]; + if (prevProp === undefined) { continue; // was already empty anyway - } - // Pattern match on: attributeConfig + } // Pattern match on: attributeConfig + if ( typeof attributeConfig !== "object" || typeof attributeConfig.diff === "function" || @@ -3534,9 +3682,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // case: CustomAttributeConfiguration | !Object // Flag the leaf property for removal by sending a sentinel. (updatePayload || (updatePayload = {}))[_propKey] = null; + if (!removedKeys) { removedKeys = {}; } + if (!removedKeys[_propKey]) { removedKeys[_propKey] = true; removedKeyCount++; @@ -3552,21 +3702,22 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ); } } + return updatePayload; } - /** * addProperties adds all the valid props to the payload after being processed. */ + function addProperties(updatePayload, props, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, emptyObject, props, validAttributes); } - /** * clearProperties clears all the previous props by adding a null sentinel * to the payload for each valid key. */ + function clearProperties(updatePayload, prevProps, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); @@ -3579,7 +3730,6 @@ function create(props, validAttributes) { validAttributes ); } - function diff(prevProps, nextProps, validAttributes) { return diffProperties( null, // updatePayload @@ -3589,7 +3739,7 @@ function diff(prevProps, nextProps, validAttributes) { ); } -// Use to restore controlled state after a change event has fired. +var PLUGIN_EVENT_SYSTEM = 1; var restoreImpl = null; var restoreTarget = null; @@ -3599,19 +3749,18 @@ function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { // Unmounted return; } - (function() { - if (!(typeof restoreImpl === "function")) { - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof restoreImpl === "function")) { + 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." + ); + } + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, props); } @@ -3619,17 +3768,17 @@ function restoreStateOfTarget(target) { function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } - function restoreStateIfNeeded() { if (!restoreTarget) { return; } + var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; - restoreStateOfTarget(target); + if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); @@ -3637,23 +3786,25 @@ function restoreStateIfNeeded() { } } -// Used as a way to call batchedUpdates when we don't have a reference to // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. - // Defaults + var batchedUpdatesImpl = function(fn, bookkeeping) { return fn(bookkeeping); }; + var discreteUpdatesImpl = function(fn, a, b, c) { return fn(a, b, c); }; + var flushDiscreteUpdatesImpl = function() {}; -var batchedEventUpdatesImpl = batchedUpdatesImpl; +var batchedEventUpdatesImpl = batchedUpdatesImpl; var isInsideEventHandler = false; +var isBatchingEventUpdates = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important @@ -3661,6 +3812,7 @@ function finishEventHandler() { // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React @@ -3676,7 +3828,9 @@ function batchedUpdates(fn, bookkeeping) { // fully completes before restoring state. return fn(bookkeeping); } + isInsideEventHandler = true; + try { return batchedUpdatesImpl(fn, bookkeeping); } finally { @@ -3684,35 +3838,48 @@ function batchedUpdates(fn, bookkeeping) { finishEventHandler(); } } - function batchedEventUpdates(fn, a, b) { - if (isInsideEventHandler) { + if (isBatchingEventUpdates) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(a, b); } - isInsideEventHandler = true; + + isBatchingEventUpdates = true; + try { return batchedEventUpdatesImpl(fn, a, b); } finally { - isInsideEventHandler = false; + isBatchingEventUpdates = false; finishEventHandler(); } -} +} // This is for the React Flare event system + +function executeUserEventHandler(fn, value) { + var previouslyInEventHandler = isInsideEventHandler; + try { + isInsideEventHandler = true; + var type = typeof value === "object" && value !== null ? value.type : ""; + invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value); + } finally { + isInsideEventHandler = previouslyInEventHandler; + } +} function discreteUpdates(fn, a, b, c) { var prevIsInsideEventHandler = isInsideEventHandler; isInsideEventHandler = true; + try { return discreteUpdatesImpl(fn, a, b, c); } finally { isInsideEventHandler = prevIsInsideEventHandler; + if (!isInsideEventHandler) { finishEventHandler(); } } } - var lastFlushedEventTimeStamp = 0; function flushDiscreteUpdatesIfNeeded(timeStamp) { // event.timeStamp isn't overly reliable due to inconsistencies in @@ -3737,7 +3904,6 @@ function flushDiscreteUpdatesIfNeeded(timeStamp) { flushDiscreteUpdatesImpl(); } } - function setBatchingImplementation( _batchedUpdatesImpl, _discreteUpdatesImpl, @@ -3750,176 +3916,99 @@ function setBatchingImplementation( batchedEventUpdatesImpl = _batchedEventUpdatesImpl; } -function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } /** * Class only exists for its Flow type. */ -var ReactNativeComponent = (function(_React$Component) { - _inherits(ReactNativeComponent, _React$Component); - - function ReactNativeComponent() { - _classCallCheck$1(this, ReactNativeComponent); - - return _possibleConstructorReturn( - this, - _React$Component.apply(this, arguments) - ); - } - - ReactNativeComponent.prototype.blur = function blur() {}; +var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.focus = function focus() {}; + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } - ReactNativeComponent.prototype.measure = function measure(callback) {}; + var _proto = ReactNativeComponent.prototype; - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) {}; + _proto.blur = function blur() {}; - ReactNativeComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail - ) {}; + _proto.focus = function focus() {}; - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) {}; + _proto.measure = function measure(callback) {}; - return ReactNativeComponent; -})(React.Component); + _proto.measureInWindow = function measureInWindow(callback) {}; -// This type is only used for FlowTests. It shouldn't be imported directly + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) {}; -/** - * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync. - * It can also provide types for ReactNative applications that use NMM or refs. - */ + _proto.setNativeProps = function setNativeProps(nativeProps) {}; -/** - * Flat ReactNative renderer bundles are too big for Flow to parse efficiently. - * Provide minimal Flow typing for the high-level RN API and call it a day. - */ + return ReactNativeComponent; + })(React.Component); // This type is only used for FlowTests. It shouldn't be imported directly var DiscreteEvent = 0; var UserBlockingEvent = 1; var ContinuousEvent = 2; -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warning = warningWithoutStack$1; - -{ - warning = function(condition, format) { - if (condition) { - return; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - // eslint-disable-next-line react-internal/warning-and-invariant-args - - for ( - var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key]; - } - - warningWithoutStack$1.apply( - undefined, - [false, format + "%s"].concat(args, [stack]) - ); - }; -} - -var warning$1 = warning; - -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; var runWithPriority = Scheduler.unstable_runWithPriority; var _nativeFabricUIManage$2 = nativeFabricUIManager; var measureInWindow = _nativeFabricUIManage$2.measureInWindow; - -var activeTimeouts = new Map(); var rootEventTypesToEventResponderInstances = new Map(); -var ownershipChangeListeners = new Set(); - -var globalOwner = null; - var currentTimeStamp = 0; -var currentTimers = new Map(); var currentInstance = null; -var currentEventQueue = null; -var currentEventQueuePriority = ContinuousEvent; -var currentTimerIDCounter = 0; - var eventResponderContext = { dispatchEvent: function(eventValue, eventListener, eventPriority) { validateResponderContext(); validateEventValue(eventValue); - if (eventPriority < currentEventQueuePriority) { - currentEventQueuePriority = eventPriority; + + switch (eventPriority) { + case DiscreteEvent: { + flushDiscreteUpdatesIfNeeded(currentTimeStamp); + discreteUpdates(function() { + return executeUserEventHandler(eventListener, eventValue); + }); + break; + } + + case UserBlockingEvent: { + runWithPriority(UserBlockingPriority, function() { + return executeUserEventHandler(eventListener, eventValue); + }); + break; + } + + case ContinuousEvent: { + executeUserEventHandler(eventListener, eventValue); + break; + } } - currentEventQueue.push(createEventQueueItem(eventValue, eventListener)); }, isTargetWithinNode: function(childTarget, parentTarget) { validateResponderContext(); var childFiber = getFiberFromTarget(childTarget); var parentFiber = getFiberFromTarget(parentTarget); - var node = childFiber; + while (node !== null) { if (node === parentFiber) { return true; } + node = node.return; } + return false; }, getTargetBoundingRect: function(target, callback) { @@ -3934,6 +4023,7 @@ var eventResponderContext = { }, addRootEventTypes: function(rootEventTypes) { validateResponderContext(); + for (var i = 0; i < rootEventTypes.length; i++) { var rootEventType = rootEventTypes[i]; var eventResponderInstance = currentInstance; @@ -3942,85 +4032,51 @@ var eventResponderContext = { }, removeRootEventTypes: function(rootEventTypes) { validateResponderContext(); + for (var i = 0; i < rootEventTypes.length; i++) { var rootEventType = rootEventTypes[i]; - var rootEventResponders = rootEventTypesToEventResponderInstances.get( rootEventType ); var rootEventTypesSet = currentInstance.rootEventTypes; + if (rootEventTypesSet !== null) { rootEventTypesSet.delete(rootEventType); } + if (rootEventResponders !== undefined) { rootEventResponders.delete(currentInstance); } } }, - setTimeout: function(func, delay) { + getTimeStamp: function() { validateResponderContext(); - if (currentTimers === null) { - currentTimers = new Map(); - } - var timeout = currentTimers.get(delay); - - var timerId = currentTimerIDCounter++; - if (timeout === undefined) { - var _timers = new Map(); - var _id = setTimeout(function() { - processTimers(_timers, delay); - }, delay); - timeout = { - id: _id, - timers: _timers - }; - currentTimers.set(delay, timeout); - } - timeout.timers.set(timerId, { - instance: currentInstance, - func: func, - id: timerId, - timeStamp: currentTimeStamp - }); - activeTimeouts.set(timerId, timeout); - return timerId; + return currentTimeStamp; }, - clearTimeout: function(timerId) { + getResponderNode: function() { validateResponderContext(); - var timeout = activeTimeouts.get(timerId); + var responderFiber = currentInstance.fiber; - if (timeout !== undefined) { - var _timers2 = timeout.timers; - _timers2.delete(timerId); - if (_timers2.size === 0) { - clearTimeout(timeout.id); - } + if (responderFiber.tag === ScopeComponent) { + return null; } - }, - getTimeStamp: function() { - validateResponderContext(); - return currentTimeStamp; + + return responderFiber.stateNode; } }; -function createEventQueueItem(value, listener) { - return { - value: value, - listener: listener - }; -} - function validateEventValue(eventValue) { if (typeof eventValue === "object" && eventValue !== null) { var target = eventValue.target, type = eventValue.type, - _timeStamp = eventValue.timeStamp; + timeStamp = eventValue.timeStamp; - if (target == null || type == null || _timeStamp == null) { + if (target == null || type == null || timeStamp == null) { throw new Error( 'context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.' ); } + var showWarning = function(name) { { warning$1( @@ -4032,27 +4088,31 @@ function validateEventValue(eventValue) { ); } }; + eventValue.preventDefault = function() { { showWarning("preventDefault()"); } }; + eventValue.stopPropagation = function() { { showWarning("stopPropagation()"); } }; + eventValue.isDefaultPrevented = function() { { showWarning("isDefaultPrevented()"); } }; + eventValue.isPropagationStopped = function() { { showWarning("isPropagationStopped()"); } - }; - // $FlowFixMe: we don't need value, Flow thinks we do + }; // $FlowFixMe: we don't need value, Flow thinks we do + Object.defineProperty(eventValue, "nativeEvent", { get: function() { { @@ -4067,143 +4127,48 @@ function getFiberFromTarget(target) { if (target === null) { return null; } - return target.canonical._internalInstanceHandle || null; -} -function processTimers(timers, delay) { - var timersArr = Array.from(timers.values()); - currentEventQueuePriority = ContinuousEvent; - try { - for (var i = 0; i < timersArr.length; i++) { - var _timersArr$i = timersArr[i], - _instance = _timersArr$i.instance, - _func = _timersArr$i.func, - _id2 = _timersArr$i.id, - _timeStamp2 = _timersArr$i.timeStamp; - - currentInstance = _instance; - currentEventQueue = []; - currentTimeStamp = _timeStamp2 + delay; - try { - _func(); - } finally { - activeTimeouts.delete(_id2); - } - } - processEventQueue(); - } finally { - currentTimers = null; - currentInstance = null; - currentEventQueue = null; - currentTimeStamp = 0; - } + return target.canonical._internalInstanceHandle || null; } function createFabricResponderEvent(topLevelType, nativeEvent, target) { return { nativeEvent: nativeEvent, - responderTarget: target, target: target, type: topLevelType }; } function validateResponderContext() { - (function() { - if (!(currentEventQueue && currentInstance)) { - throw ReactError( - Error( - "An event responder context was used outside of an event cycle. Use context.setTimeout() to use asynchronous responder context outside of event cycle ." - ) - ); - } - })(); -} - -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic -function processEventQueue() { - var eventQueue = currentEventQueue; - if (eventQueue.length === 0) { - return; - } - switch (currentEventQueuePriority) { - case DiscreteEvent: { - flushDiscreteUpdatesIfNeeded(currentTimeStamp); - discreteUpdates(function() { - batchedEventUpdates(processEvents, eventQueue); - }); - break; - } - case UserBlockingEvent: { - if (enableUserBlockingEvents) { - runWithPriority( - UserBlockingPriority, - batchedEventUpdates.bind(null, processEvents, eventQueue) - ); - } else { - batchedEventUpdates(processEvents, eventQueue); - } - break; - } - case ContinuousEvent: { - batchedEventUpdates(processEvents, eventQueue); - break; - } - } -} - -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic -function releaseOwnershipForEventResponderInstance(eventResponderInstance) { - if (globalOwner === eventResponderInstance) { - globalOwner = null; - triggerOwnershipListeners(); - return true; + if (!currentInstance) { + throw Error( + "An event responder context was used outside of an event cycle." + ); } - return false; -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic -function processEvents(eventQueue) { - for (var i = 0, length = eventQueue.length; i < length; i++) { - var _eventQueue$i = eventQueue[i], - _value = _eventQueue$i.value, - _listener = _eventQueue$i.listener; - - var type = typeof _value === "object" && _value !== null ? _value.type : ""; - invokeGuardedCallbackAndCatchFirstError(type, _listener, undefined, _value); - } -} -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic function responderEventTypesContainType(eventTypes, type) { for (var i = 0, len = eventTypes.length; i < len; i++) { if (eventTypes[i] === type) { return true; } } + return false; } function validateResponderTargetEventTypes(eventType, responder) { - var targetEventTypes = responder.targetEventTypes; - // Validate the target event type exists on the responder + var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder if (targetEventTypes !== null) { return responderEventTypesContainType(targetEventTypes, eventType); } - return false; -} - -function validateOwnership(responderInstance) { - return globalOwner === null || globalOwner === responderInstance; -} -// TODO this function is almost an exact copy of the DOM version, we should + return false; +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function traverseAndHandleEventResponderInstances( eventType, targetFiber, @@ -4212,7 +4177,6 @@ function traverseAndHandleEventResponderInstances( // Trigger event responders in this order: // - Bubble target responder phase // - Root responder phase - var responderEvent = createFabricResponderEvent( eventType, nativeEvent, @@ -4220,180 +4184,131 @@ function traverseAndHandleEventResponderInstances( ); var visitedResponders = new Set(); var node = targetFiber; + while (node !== null) { var _node = node, dependencies = _node.dependencies, tag = _node.tag; - if (tag === HostComponent && dependencies !== null) { + if ( + (tag === HostComponent || tag === ScopeComponent) && + dependencies !== null + ) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for (var i = 0, length = responderInstances.length; i < length; i++) { var responderInstance = responderInstances[i]; + var props = responderInstance.props, + responder = responderInstance.responder, + state = responderInstance.state; - if (validateOwnership(responderInstance)) { - var props = responderInstance.props, - responder = responderInstance.responder, - state = responderInstance.state, - target = responderInstance.target; + if ( + !visitedResponders.has(responder) && + validateResponderTargetEventTypes(eventType, responder) + ) { + var onEvent = responder.onEvent; + visitedResponders.add(responder); - if ( - !visitedResponders.has(responder) && - validateResponderTargetEventTypes(eventType, responder) - ) { - var onEvent = responder.onEvent; - visitedResponders.add(responder); - if (onEvent !== null) { - currentInstance = responderInstance; - responderEvent.responderTarget = target; - onEvent(responderEvent, eventResponderContext, props, state); - } + if (onEvent !== null) { + currentInstance = responderInstance; + onEvent(responderEvent, eventResponderContext, props, state); } } } } } + node = node.return; - } - // Root phase + } // Root phase + var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( eventType ); + if (rootEventResponderInstances !== undefined) { var _responderInstances = Array.from(rootEventResponderInstances); for (var _i = 0; _i < _responderInstances.length; _i++) { var _responderInstance = _responderInstances[_i]; - if (!validateOwnership(_responderInstance)) { - continue; - } - var _props = _responderInstance.props, - _responder = _responderInstance.responder, - _state = _responderInstance.state, - _target = _responderInstance.target; + var props = _responderInstance.props, + responder = _responderInstance.responder, + state = _responderInstance.state; + var onRootEvent = responder.onRootEvent; - var onRootEvent = _responder.onRootEvent; if (onRootEvent !== null) { currentInstance = _responderInstance; - responderEvent.responderTarget = _target; - onRootEvent(responderEvent, eventResponderContext, _props, _state); + onRootEvent(responderEvent, eventResponderContext, props, state); } } } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function dispatchEventForResponderEventSystem( topLevelType, targetFiber, nativeEvent ) { - var previousEventQueue = currentEventQueue; var previousInstance = currentInstance; - var previousTimers = currentTimers; - var previousTimeStamp = currentTimeStamp; - var previousEventQueuePriority = currentEventQueuePriority; - currentTimers = null; - currentEventQueue = []; - currentEventQueuePriority = ContinuousEvent; - // We might want to control timeStamp another way here + var previousTimeStamp = currentTimeStamp; // We might want to control timeStamp another way here + currentTimeStamp = Date.now(); + try { - traverseAndHandleEventResponderInstances( - topLevelType, - targetFiber, - nativeEvent - ); - processEventQueue(); + batchedEventUpdates(function() { + traverseAndHandleEventResponderInstances( + topLevelType, + targetFiber, + nativeEvent + ); + }); } finally { - currentTimers = previousTimers; currentInstance = previousInstance; - currentEventQueue = previousEventQueue; currentTimeStamp = previousTimeStamp; - currentEventQueuePriority = previousEventQueuePriority; } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic -function triggerOwnershipListeners() { - var listeningInstances = Array.from(ownershipChangeListeners); - var previousInstance = currentInstance; - var previousEventQueuePriority = currentEventQueuePriority; - var previousEventQueue = currentEventQueue; - try { - for (var i = 0; i < listeningInstances.length; i++) { - var _instance2 = listeningInstances[i]; - var props = _instance2.props, - responder = _instance2.responder, - state = _instance2.state; - - currentInstance = _instance2; - currentEventQueuePriority = ContinuousEvent; - currentEventQueue = []; - var onOwnershipChange = responder.onOwnershipChange; - if (onOwnershipChange !== null) { - onOwnershipChange(eventResponderContext, props, state); - } - } - processEventQueue(); - } finally { - currentInstance = previousInstance; - currentEventQueue = previousEventQueue; - currentEventQueuePriority = previousEventQueuePriority; - } -} -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic function mountEventResponder(responder, responderInstance, props, state) { - if (responder.onOwnershipChange !== null) { - ownershipChangeListeners.add(responderInstance); - } var onMount = responder.onMount; + if (onMount !== null) { - currentEventQueuePriority = ContinuousEvent; currentInstance = responderInstance; - currentEventQueue = []; + try { - onMount(eventResponderContext, props, state); - processEventQueue(); + batchedEventUpdates(function() { + onMount(eventResponderContext, props, state); + }); } finally { - currentEventQueue = null; currentInstance = null; - currentTimers = null; } } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function unmountEventResponder(responderInstance) { var responder = responderInstance.responder; var onUnmount = responder.onUnmount; + if (onUnmount !== null) { var props = responderInstance.props, state = responderInstance.state; - - currentEventQueue = []; - currentEventQueuePriority = ContinuousEvent; currentInstance = responderInstance; + try { - onUnmount(eventResponderContext, props, state); - processEventQueue(); + batchedEventUpdates(function() { + onUnmount(eventResponderContext, props, state); + }); } finally { - currentEventQueue = null; currentInstance = null; - currentTimers = null; } } - releaseOwnershipForEventResponderInstance(responderInstance); - if (responder.onOwnershipChange !== null) { - ownershipChangeListeners.delete(responderInstance); - } + var rootEventTypesSet = responderInstance.rootEventTypes; + if (rootEventTypesSet !== null) { var rootEventTypes = Array.from(rootEventTypesSet); @@ -4402,6 +4317,7 @@ function unmountEventResponder(responderInstance) { var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( topLevelEventType ); + if (rootEventResponderInstances !== undefined) { rootEventResponderInstances.delete(responderInstance); } @@ -4413,6 +4329,7 @@ function registerRootEventType(rootEventType, responderInstance) { var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( rootEventType ); + if (rootEventResponderInstances === undefined) { rootEventResponderInstances = new Set(); rootEventTypesToEventResponderInstances.set( @@ -4420,21 +4337,21 @@ function registerRootEventType(rootEventType, responderInstance) { rootEventResponderInstances ); } + var rootEventTypesSet = responderInstance.rootEventTypes; + if (rootEventTypesSet === null) { rootEventTypesSet = responderInstance.rootEventTypes = new Set(); } - (function() { - if (!!rootEventTypesSet.has(rootEventType)) { - throw ReactError( - Error( - 'addRootEventTypes() found a duplicate root event type of "' + - rootEventType + - '". This might be because the event type exists in the event responder "rootEventTypes" array or because of a previous addRootEventTypes() using this root event type.' - ) - ); - } - })(); + + if (!!rootEventTypesSet.has(rootEventType)) { + 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.' + ); + } + rootEventTypesSet.add(rootEventType); rootEventResponderInstances.add(responderInstance); } @@ -4451,39 +4368,35 @@ function addRootEventTypesForResponderInstance( function dispatchEvent(target, topLevelType, nativeEvent) { var targetFiber = target; + if (enableFlareAPI) { // React Flare event system dispatchEventForResponderEventSystem(topLevelType, target, nativeEvent); } + batchedUpdates(function() { // Heritage plugin event system runExtractedPluginEventsInBatch( topLevelType, targetFiber, nativeEvent, - nativeEvent.target + nativeEvent.target, + PLUGIN_EVENT_SYSTEM ); - }); - // React Native doesn't use ReactControlledComponent but if it did, here's + }); // React Native doesn't use ReactControlledComponent but if it did, here's // where it would do it. } -// Renderers that don't support mutation // can re-export everything from this module. function shim() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} + { + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Mutation (when unsupported) -// Mutation (when unsupported) var supportsMutation = false; var appendChild = shim; var appendChildToContainer = shim; @@ -4500,22 +4413,15 @@ var hideTextInstance = shim; var unhideInstance = shim; var unhideTextInstance = shim; -// Renderers that don't support hydration // can re-export everything from this module. function shim$1() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} - -// Hydration (when unsupported) + { + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Hydration (when unsupported) var supportsHydration = false; var canHydrateInstance = shim$1; @@ -4528,7 +4434,10 @@ var getNextHydratableSibling = shim$1; var getFirstHydratableChild = shim$1; var hydrateInstance = shim$1; var hydrateTextInstance = shim$1; +var hydrateSuspenseInstance = shim$1; var getNextHydratableInstanceAfterSuspenseInstance = shim$1; +var commitHydratedContainer = shim$1; +var commitHydratedSuspenseInstance = shim$1; var clearSuspenseBoundary = shim$1; var clearSuspenseBoundaryFromContainer = shim$1; var didNotMatchHydratedContainerTextInstance = shim$1; @@ -4542,13 +4451,6 @@ var didNotFindHydratableInstance = shim$1; var didNotFindHydratableTextInstance = shim$1; var didNotFindHydratableSuspenseInstance = shim$1; -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -// Modules provided by RN: var _nativeFabricUIManage$1 = nativeFabricUIManager; var createNode = _nativeFabricUIManage$1.createNode; var cloneNode = _nativeFabricUIManage$1.cloneNode; @@ -4565,9 +4467,7 @@ var fabricMeasure = _nativeFabricUIManage$1.measure; var fabricMeasureInWindow = _nativeFabricUIManage$1.measureInWindow; var fabricMeasureLayout = _nativeFabricUIManage$1.measureLayout; var getViewConfigForType = - ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; - -// Counter for uniquely identifying views. + ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; // Counter for uniquely identifying views. // % 10 === 1 means it is a rootTag. // % 2 === 0 means it is a Fabric tag. // This means that they never overlap. @@ -4581,93 +4481,90 @@ if (registerEventHandler) { */ registerEventHandler(dispatchEvent); } - /** * This is used for refs on host components. */ -var ReactFabricHostComponent = (function() { - function ReactFabricHostComponent( - tag, - viewConfig, - props, - internalInstanceHandle - ) { - _classCallCheck(this, ReactFabricHostComponent); +var ReactFabricHostComponent = + /*#__PURE__*/ + (function() { + function ReactFabricHostComponent( + tag, + viewConfig, + props, + internalInstanceHandle + ) { + this._nativeTag = tag; + this.viewConfig = viewConfig; + this.currentProps = props; + this._internalInstanceHandle = internalInstanceHandle; + } - this._nativeTag = tag; - this.viewConfig = viewConfig; - this.currentProps = props; - this._internalInstanceHandle = internalInstanceHandle; - } + var _proto = ReactFabricHostComponent.prototype; - ReactFabricHostComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); - }; + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); + }; - ReactFabricHostComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); - }; + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + this._nativeTag + ); + }; - ReactFabricHostComponent.prototype.measure = function measure(callback) { - fabricMeasure( - this._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; + _proto.measure = function measure(callback) { + fabricMeasure( + this._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactFabricHostComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - fabricMeasureInWindow( - this._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; + _proto.measureInWindow = function measureInWindow(callback) { + fabricMeasureInWindow( + this._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactFabricHostComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - if ( - typeof relativeToNativeNode === "number" || - !(relativeToNativeNode instanceof ReactFabricHostComponent) - ) { + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) /* currently unused */ + { + if ( + typeof relativeToNativeNode === "number" || + !(relativeToNativeNode instanceof ReactFabricHostComponent) + ) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a ref to a native component." + ); + return; + } + + fabricMeasureLayout( + this._internalInstanceHandle.stateNode.node, + relativeToNativeNode._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + }; + + _proto.setNativeProps = function setNativeProps(nativeProps) { warningWithoutStack$1( false, - "Warning: ref.measureLayout must be called with a ref to a native component." + "Warning: setNativeProps is not currently supported in Fabric" ); - return; - } - - fabricMeasureLayout( - this._internalInstanceHandle.stateNode.node, - relativeToNativeNode._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; - - ReactFabricHostComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - - return; - }; + }; - return ReactFabricHostComponent; -})(); + return ReactFabricHostComponent; + })(); // eslint-disable-next-line no-unused-expressions function appendInitialChild(parentInstance, child) { appendChildNode(parentInstance.node, child.node); } - function createInstance( type, props, @@ -4677,7 +4574,6 @@ function createInstance( ) { var tag = nextReactTag; nextReactTag += 2; - var viewConfig = getViewConfigForType(type); { @@ -4691,7 +4587,6 @@ function createInstance( } var updatePayload = create(props, viewConfig.validAttributes); - var node = createNode( tag, // reactTag viewConfig.uiViewClassName, // viewName @@ -4699,50 +4594,42 @@ function createInstance( updatePayload, // props internalInstanceHandle // internalInstanceHandle ); - var component = new ReactFabricHostComponent( tag, viewConfig, props, internalInstanceHandle ); - return { node: node, canonical: component }; } - function createTextInstance( text, rootContainerInstance, hostContext, internalInstanceHandle ) { - (function() { - if (!hostContext.isInAParentText) { - throw ReactError( - Error("Text strings must be rendered within a component.") - ); - } - })(); + if (!hostContext.isInAParentText) { + throw Error("Text strings must be rendered within a component."); + } var tag = nextReactTag; nextReactTag += 2; - var node = createNode( tag, // reactTag "RCTRawText", // viewName rootContainerInstance, // rootTag - { text: text }, // props + { + text: text + }, // props internalInstanceHandle // instance handle ); - return { node: node }; } - function finalizeInitialChildren( parentInstance, type, @@ -4752,11 +4639,11 @@ function finalizeInitialChildren( ) { return false; } - function getRootHostContext(rootContainerInstance) { - return { isInAParentText: false }; + return { + isInAParentText: false + }; } - function getChildHostContext(parentHostContext, type, rootContainerInstance) { var prevIsInAParentText = parentHostContext.isInAParentText; var isInAParentText = @@ -4767,20 +4654,19 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { type === "RCTVirtualText"; if (prevIsInAParentText !== isInAParentText) { - return { isInAParentText: isInAParentText }; + return { + isInAParentText: isInAParentText + }; } else { return parentHostContext; } } - function getPublicInstance(instance) { return instance.canonical; } - function prepareForCommit(containerInfo) { // Noop } - function prepareUpdate( instance, type, @@ -4790,22 +4676,19 @@ function prepareUpdate( hostContext ) { var viewConfig = instance.canonical.viewConfig; - var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); - // TODO: If the event handlers have changed, we need to update the current props + var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); // TODO: If the event handlers have changed, we need to update the current props // in the commit phase but there is no host config hook to do it yet. // So instead we hack it by updating it in the render phase. + instance.canonical.currentProps = newProps; return updatePayload; } - function resetAfterCommit(containerInfo) { // Noop } - function shouldDeprioritizeSubtree(type, props) { return false; } - function shouldSetTextContent(type, props) { // TODO (bvaughn) Revisit this decision. // Always returning false simplifies the createInstance() implementation, @@ -4814,24 +4697,18 @@ function shouldSetTextContent(type, props) { // It's not clear to me which is better so I'm deferring for now. // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 return false; -} +} // The Fabric renderer is secondary to the existing React Native renderer. -// The Fabric renderer is secondary to the existing React Native renderer. -var isPrimaryRenderer = false; +var isPrimaryRenderer = false; // The Fabric renderer shouldn't trigger missing act() warnings -// The Fabric renderer shouldn't trigger missing act() warnings var warnsIfNotActing = false; - var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; -var noTimeout = -1; - -// ------------------- +var noTimeout = -1; // ------------------- // Persistence // ------------------- var supportsPersistence = true; - function cloneInstance( instance, updatePayload, @@ -4843,7 +4720,8 @@ function cloneInstance( recyclableInstance ) { var node = instance.node; - var clone = void 0; + var clone; + if (keepChildren) { if (updatePayload !== null) { clone = cloneNodeWithNewProps(node, updatePayload); @@ -4857,17 +4735,21 @@ function cloneInstance( clone = cloneNodeWithNewChildren(node); } } + return { node: clone, canonical: instance.canonical }; } - function cloneHiddenInstance(instance, type, props, internalInstanceHandle) { var viewConfig = instance.canonical.viewConfig; var node = instance.node; var updatePayload = create( - { style: { display: "none" } }, + { + style: { + display: "none" + } + }, viewConfig.validAttributes ); return { @@ -4875,19 +4757,15 @@ function cloneHiddenInstance(instance, type, props, internalInstanceHandle) { canonical: instance.canonical }; } - function cloneHiddenTextInstance(instance, text, internalInstanceHandle) { throw new Error("Not yet implemented."); } - function createContainerChildSet(container) { return createChildNodeSet(container); } - function appendChildToContainerChildSet(childSet, child) { appendChildNodeToSet(childSet, child.node); } - function finalizeContainerChildren(container, newChildren) { completeRoot(container, newChildren); } @@ -4897,8 +4775,7 @@ function mountResponderInstance( responderInstance, props, state, - instance, - rootContainerInstance + instance ) { if (enableFlareAPI) { var rootEventTypes = responder.rootEventTypes; @@ -4906,55 +4783,55 @@ function mountResponderInstance( if (rootEventTypes !== null) { addRootEventTypesForResponderInstance(responderInstance, rootEventTypes); } + mountEventResponder(responder, responderInstance, props, state); } } - function unmountResponderInstance(responderInstance) { if (enableFlareAPI) { // TODO stop listening to targetEventTypes unmountEventResponder(responderInstance); } } - function getFundamentalComponentInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } - function mountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function shouldUpdateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function updateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function unmountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function cloneFundamentalInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } +function getInstanceFromNode$1(node) { + throw new Error("Not yet implemented."); +} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; - var describeComponentFrame = function(name, source, ownerName) { var sourceInfo = ""; + if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ""); + { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); + if (match) { var pathBeforeSlash = match[1]; + if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ""); fileName = folderName + "/" + fileName; @@ -4962,10 +4839,12 @@ var describeComponentFrame = function(name, source, ownerName) { } } } + sourceInfo = " (at " + fileName + ":" + source.lineNumber + ")"; } else if (ownerName) { sourceInfo = " (created by " + ownerName + ")"; } + return "\n in " + (name || "Unknown") + sourceInfo; }; @@ -4980,14 +4859,17 @@ function describeFiber(fiber) { case ContextProvider: case ContextConsumer: return ""; + default: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName(fiber.type); var ownerName = null; + if (owner) { ownerName = getComponentName(owner.type); } + return describeComponentFrame(name, source, ownerName); } } @@ -4995,41 +4877,43 @@ function describeFiber(fiber) { function getStackByFiberInDevAndProd(workInProgress) { var info = ""; var node = workInProgress; + do { info += describeFiber(node); node = node.return; } while (node); + return info; } - var current = null; var phase = null; - function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { return getComponentName(owner.type); } } + return null; } - function getCurrentFiberStackInDev() { { if (current === null) { return ""; - } - // Safe because if current fiber exists, we are reconciling, + } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. + return getStackByFiberInDevAndProd(current); } + return ""; } - function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; @@ -5037,7 +4921,6 @@ function resetCurrentFiber() { phase = null; } } - function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; @@ -5045,7 +4928,6 @@ function setCurrentFiber(fiber) { phase = null; } } - function setCurrentPhase(lifeCyclePhase) { { phase = lifeCyclePhase; @@ -5061,28 +4943,26 @@ var supportsUserTiming = 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. + typeof performance.clearMeasures === "function"; // Keep track of current fiber so that we know the path to unwind on pause. // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? -var currentFiber = null; -// If we're in the middle of user code, which fiber and method is it? + +var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). + var currentPhase = null; -var currentPhaseFiber = null; -// Did lifecycle hook schedule an update? This is often a performance problem, +var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. + var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; -var isWaitingForCallback = false; -// During commits, we only show a measurement once per method name // to avoid stretch the commit phase with measurement overhead. + var labelsInCurrentCommit = new Set(); var formatMarkName = function(markName) { @@ -5106,14 +4986,14 @@ var clearMark = function(markName) { var endMark = function(label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); + try { performance.measure(formattedLabel, formattedMarkName); - } catch (err) {} - // If previous mark was missing for some reason, this will throw. + } catch (err) {} // If previous mark was missing for some reason, this will throw. // This could only happen if React crashed in an unexpected place earlier. // Don't pile on with more errors. - // Clear marks immediately to avoid growing buffer. + performance.clearMarks(formattedMarkName); performance.clearMeasures(formattedLabel); }; @@ -5144,8 +5024,8 @@ var beginFiberMark = function(fiber, phase) { // want to stretch the commit phase beyond necessary. return false; } - labelsInCurrentCommit.add(label); + labelsInCurrentCommit.add(label); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; @@ -5182,6 +5062,7 @@ var shouldIgnoreFiber = function(fiber) { case ContextConsumer: case Mode: return true; + default: return false; } @@ -5191,6 +5072,7 @@ var clearPendingPhaseMeasurement = function() { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } + currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; @@ -5200,10 +5082,12 @@ var pauseTimers = function() { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; + while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } + fiber = fiber.return; } }; @@ -5212,6 +5096,7 @@ var resumeTimersRecursively = function(fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } + if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } @@ -5229,12 +5114,12 @@ function recordEffect() { effectCountInCurrentCommit++; } } - function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } + if ( currentPhase !== null && currentPhase !== "componentWillMount" && @@ -5245,143 +5130,125 @@ function recordScheduleUpdate() { } } -function startRequestCallbackTimer() { - if (enableUserTimingAPI) { - if (supportsUserTiming && !isWaitingForCallback) { - isWaitingForCallback = true; - beginMark("(Waiting for async callback...)"); - } - } -} - -function stopRequestCallbackTimer(didExpire) { - if (enableUserTimingAPI) { - if (supportsUserTiming) { - isWaitingForCallback = false; - var warning = didExpire - ? "Update expired; will flush synchronously" - : null; - endMark( - "(Waiting for async callback...)", - "(Waiting for async callback...)", - warning - ); - } - } -} - function startWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, this is the fiber to unwind from. + } // If we pause, this is the fiber to unwind from. + currentFiber = fiber; + if (!beginFiberMark(fiber, null)) { return; } + fiber._debugIsCurrentlyTiming = true; } } - function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // Remember we shouldn't complete measurement for this fiber. + } // Remember we shouldn't complete measurement for this fiber. // Otherwise flamechart will be deep even for small updates. + fiber._debugIsCurrentlyTiming = false; clearFiberMark(fiber, null); } } - function stopWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; endFiberMark(fiber, null, null); } } - function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; var warning = - fiber.tag === SuspenseComponent || - fiber.tag === DehydratedSuspenseComponent + fiber.tag === SuspenseComponent ? "Rendering was suspended" : "An error was thrown inside this error boundary"; endFiberMark(fiber, null, warning); } } - function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + clearPendingPhaseMeasurement(); + if (!beginFiberMark(fiber, phase)) { return; } + currentPhaseFiber = fiber; currentPhase = phase; } } - function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? "Scheduled a cascading update" : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } + currentPhase = null; currentPhaseFiber = null; } } - function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; + if (!supportsUserTiming) { return; } - commitCountInCurrentWorkLoop = 0; - // This is top level call. + + commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. - beginMark("(React Tree Reconciliation)"); - // Resume any measurements that were in progress during the last loop. + + beginMark("(React Tree Reconciliation)"); // Resume any measurements that were in progress during the last loop. + resumeTimers(); } } - function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var warning = null; + if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = "A top-level update interrupted the previous render"; @@ -5393,28 +5260,28 @@ function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { } else if (commitCountInCurrentWorkLoop > 1) { warning = "There were cascading updates"; } + commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? "(React Tree Reconciliation: Completed Root)" - : "(React Tree Reconciliation: Yielded)"; - // Pause any measurements until the next loop. + : "(React Tree Reconciliation: Yielded)"; // Pause any measurements until the next loop. + pauseTimers(); endMark(label, "(React Tree Reconciliation)", warning); } } - function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark("(Committing Changes)"); } } - function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { @@ -5422,35 +5289,36 @@ function stopCommitTimer() { } var warning = null; + if (hasScheduledUpdateInCurrentCommit) { warning = "Lifecycle hook scheduled a cascading update"; } else if (commitCountInCurrentWorkLoop > 0) { warning = "Caused by a cascading update in earlier commit"; } + hasScheduledUpdateInCurrentCommit = false; commitCountInCurrentWorkLoop++; isCommitting = false; labelsInCurrentCommit.clear(); - endMark("(Committing Changes)", "(Committing Changes)", warning); } } - function startCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Snapshot Effects)"); } } - function stopCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5460,22 +5328,22 @@ function stopCommitSnapshotEffectsTimer() { ); } } - function startCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Host Effects)"); } } - function stopCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5485,22 +5353,22 @@ function stopCommitHostEffectsTimer() { ); } } - function startCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Calling Lifecycle Methods)"); } } - function stopCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5512,8 +5380,7 @@ function stopCommitLifeCyclesTimer() { } var valueStack = []; - -var fiberStack = void 0; +var fiberStack; { fiberStack = []; @@ -5532,6 +5399,7 @@ function pop(cursor, fiber) { { warningWithoutStack$1(false, "Unexpected pop."); } + return; } @@ -5542,7 +5410,6 @@ function pop(cursor, fiber) { } cursor.current = valueStack[index]; - valueStack[index] = null; { @@ -5554,7 +5421,6 @@ function pop(cursor, fiber) { function push(cursor, value, fiber) { index++; - valueStack[index] = cursor.current; { @@ -5564,24 +5430,24 @@ function push(cursor, value, fiber) { cursor.current = value; } -var warnedAboutMissingGetChildContext = void 0; +var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; + { Object.freeze(emptyContextObject); -} +} // A cursor to the current merged context object on the stack. -// A cursor to the current merged context object on the stack. -var contextStackCursor = createCursor(emptyContextObject); -// A cursor to a boolean indicating whether the context has changed. -var didPerformWorkStackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. +var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. + +var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. + var previousContext = emptyContextObject; function getUnmaskedContext( @@ -5599,6 +5465,7 @@ function getUnmaskedContext( // previous (parent) context instead for a context provider. return previousContext; } + return contextStackCursor.current; } } @@ -5619,14 +5486,15 @@ function getMaskedContext(workInProgress, unmaskedContext) { } else { var type = workInProgress.type; var contextTypes = type.contextTypes; + if (!contextTypes) { return emptyContextObject; - } - - // Avoid recreating masked context unless unmasked context has changed. + } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. + var instance = workInProgress.stateNode; + if ( instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext @@ -5635,6 +5503,7 @@ function getMaskedContext(workInProgress, unmaskedContext) { } var context = {}; + for (var key in contextTypes) { context[key] = unmaskedContext[key]; } @@ -5648,10 +5517,9 @@ function getMaskedContext(workInProgress, unmaskedContext) { name, getCurrentFiberStackInDev ); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. + if (instance) { cacheContext(workInProgress, unmaskedContext, context); } @@ -5699,15 +5567,11 @@ function pushTopLevelContextObject(fiber, context, didChange) { if (disableLegacyContext) { return; } else { - (function() { - if (!(contextStackCursor.current === emptyContextObject)) { - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(contextStackCursor.current === emptyContextObject)) { + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." + ); + } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -5719,10 +5583,9 @@ function processChildContext(fiber, type, parentContext) { return parentContext; } else { var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== "function") { { var componentName = getComponentName(type) || "Unknown"; @@ -5739,41 +5602,42 @@ function processChildContext(fiber, type, parentContext) { ); } } + return parentContext; } - var childContext = void 0; + var childContext; + { setCurrentPhase("getChildContext"); } + startPhaseTimer(fiber, "getChildContext"); childContext = instance.getChildContext(); stopPhaseTimer(); + { setCurrentPhase(null); } + for (var contextKey in childContext) { - (function() { - if (!(contextKey in childContextTypes)) { - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) - ); - } - })(); + if (!(contextKey in childContextTypes)) { + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } } + { var name = getComponentName(type) || "Unknown"; checkPropTypes( childContextTypes, childContext, "child context", - name, - // In practice, there is one case in which we won't get a stack. It's when + name, // In practice, there is one case in which we won't get a stack. It's when // somebody calls unstable_renderSubtreeIntoContainer() and we process // context from the parent component instance. The stack will be missing // because it's outside of the reconciliation, and so the pointer has not @@ -5782,7 +5646,7 @@ function processChildContext(fiber, type, parentContext) { ); } - return Object.assign({}, parentContext, childContext); + return Object.assign({}, parentContext, {}, childContext); } } @@ -5790,16 +5654,15 @@ function pushContextProvider(workInProgress) { if (disableLegacyContext) { return false; } else { - var instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. + var memoizedMergedChildContext = (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - - // Remember the parent context so we can merge with it later. + emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. + previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push( @@ -5807,7 +5670,6 @@ function pushContextProvider(workInProgress) { didPerformWorkStackCursor.current, workInProgress ); - return true; } } @@ -5817,15 +5679,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { return; } else { var instance = workInProgress.stateNode; - (function() { - if (!instance) { - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!instance) { + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." + ); + } if (didChange) { // Merge parent and own context. @@ -5836,13 +5695,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { type, previousContext ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. + pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. + push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { @@ -5858,40 +5716,38 @@ function findCurrentUnmaskedContext(fiber) { } else { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - (function() { - if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + 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." + ); + } var node = fiber; + do { switch (node.tag) { case HostRoot: return node.stateNode.context; + case ClassComponent: { var Component = node.type; + if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } + break; } } + node = node.return; } while (node !== null); - (function() { - { - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -5919,77 +5775,69 @@ if (enableSchedulerTracing) { // Provide explicit error message when production+profiling bundle of e.g. // react-dom is used with production (non-profiling) bundle of // scheduler/tracing - (function() { - if ( - !( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null - ) - ) { - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) - ); - } - })(); + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + 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" + ); + } } -var fakeCallbackNode = {}; - -// Except for NoPriority, these correspond to Scheduler priorities. We use +var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use // ascending numbers so we can compare them like numbers. They start at 90 to // avoid clashing with Scheduler's priorities. + var ImmediatePriority = 99; var UserBlockingPriority$1 = 98; var NormalPriority = 97; var LowPriority = 96; -var IdlePriority = 95; -// NoPriority is the absence of priority. Also React-only. -var NoPriority = 90; +var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only. +var NoPriority = 90; var shouldYield = Scheduler_shouldYield; -var requestPaint = - // Fall back gracefully if we're running an older version of Scheduler. +var requestPaint = // Fall back gracefully if we're running an older version of Scheduler. Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function() {}; - var syncQueue = null; var immediateQueueCallbackNode = null; var isFlushingSyncQueue = false; -var initialTimeMs = Scheduler_now(); - -// If the initial timestamp is reasonably small, use Scheduler's `now` directly. +var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly. // This will be the case for modern browsers that support `performance.now`. In // older browsers, Scheduler falls back to `Date.now`, which returns a Unix // timestamp. In that case, subtract the module initialization time to simulate // the behavior of performance.now and keep our times small enough to fit // within 32 bits. // TODO: Consider lifting this into Scheduler. + var now = initialTimeMs < 10000 ? Scheduler_now : function() { return Scheduler_now() - initialTimeMs; }; - function getCurrentPriorityLevel() { switch (Scheduler_getCurrentPriorityLevel()) { case Scheduler_ImmediatePriority: return ImmediatePriority; + case Scheduler_UserBlockingPriority: return UserBlockingPriority$1; + case Scheduler_NormalPriority: return NormalPriority; + case Scheduler_LowPriority: return LowPriority; + case Scheduler_IdlePriority: return IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5997,20 +5845,22 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { switch (reactPriorityLevel) { case ImmediatePriority: return Scheduler_ImmediatePriority; + case UserBlockingPriority$1: return Scheduler_UserBlockingPriority; + case NormalPriority: return Scheduler_NormalPriority; + case LowPriority: return Scheduler_LowPriority; + case IdlePriority: return Scheduler_IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -6018,18 +5868,16 @@ function runWithPriority$1(reactPriorityLevel, fn) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_runWithPriority(priorityLevel, fn); } - function scheduleCallback(reactPriorityLevel, callback, options) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_scheduleCallback(priorityLevel, callback, options); } - function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { - syncQueue = [callback]; - // Flush the queue in the next tick, at the earliest. + syncQueue = [callback]; // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl @@ -6039,19 +5887,21 @@ function scheduleSyncCallback(callback) { // we already scheduled one when we created the queue. syncQueue.push(callback); } + return fakeCallbackNode; } - function cancelCallback(callbackNode) { if (callbackNode !== fakeCallbackNode) { Scheduler_cancelCallback(callbackNode); } } - function flushSyncCallbackQueue() { if (immediateQueueCallbackNode !== null) { - Scheduler_cancelCallback(immediateQueueCallbackNode); + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); } + flushSyncCallbackQueueImpl(); } @@ -6060,12 +5910,14 @@ function flushSyncCallbackQueueImpl() { // Prevent re-entrancy. isFlushingSyncQueue = true; var i = 0; + try { var _isSync = true; var queue = syncQueue; runWithPriority$1(ImmediatePriority, function() { for (; i < queue.length; i++) { var callback = queue[i]; + do { callback = callback(_isSync); } while (callback !== null); @@ -6076,8 +5928,8 @@ function flushSyncCallbackQueueImpl() { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); - } - // Resume flushing in the next tick + } // Resume flushing in the next tick + Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueue @@ -6090,9 +5942,9 @@ function flushSyncCallbackQueueImpl() { } var NoMode = 0; -var StrictMode = 1; -// TODO: Remove BatchedMode and ConcurrentMode by reading from the root +var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root // tag instead + var BatchedMode = 2; var ConcurrentMode = 4; var ProfileMode = 8; @@ -6102,20 +5954,27 @@ var ProfileMode = 8; // 0b111111111111111111111111111111 var MAX_SIGNED_31_BIT_INT = 1073741823; -var NoWork = 0; -var Never = 1; +var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that +// Never work can be committed in an inconsistent state without tearing the UI. +// The main example is offscreen content, like a hidden subtree. So one possible +// name is Offscreen. However, it also includes dehydrated Suspense boundaries, +// which are inconsistent in the sense that they haven't finished yet, but +// aren't visibly inconsistent because the server rendered HTML matches what the +// hydrated tree would look like. + +var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in +// order to be consistent. + +var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle var Sync = MAX_SIGNED_31_BIT_INT; var Batched = Sync - 1; - var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = Batched - 1; +var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms. -// 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0); } - function expirationTimeToMs(expirationTime) { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } @@ -6132,13 +5991,11 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { bucketSizeMs / UNIT_SIZE ) ); -} - -// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update +} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update // the names to reflect. + var LOW_PRIORITY_EXPIRATION = 5000; var LOW_PRIORITY_BATCH_SIZE = 250; - function computeAsyncExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -6146,7 +6003,6 @@ function computeAsyncExpiration(currentTime) { LOW_PRIORITY_BATCH_SIZE ); } - function computeSuspenseExpiration(currentTime, timeoutMs) { // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time? return computeExpirationBucket( @@ -6154,9 +6010,7 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { timeoutMs, LOW_PRIORITY_BATCH_SIZE ); -} - -// We intentionally set a higher expiration time for interactive updates in +} // We intentionally set a higher expiration time for interactive updates in // dev than in production. // // If the main thread is being blocked so long that you hit the expiration, @@ -6167,9 +6021,9 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { // // In production we opt for better UX at the risk of masking scheduling // problems, by expiring fast. + var HIGH_PRIORITY_EXPIRATION = 500; var HIGH_PRIORITY_BATCH_SIZE = 100; - function computeInteractiveExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -6182,24 +6036,27 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (expirationTime === Sync) { return ImmediatePriority; } - if (expirationTime === Never) { + + if (expirationTime === Never || expirationTime === Idle) { return IdlePriority; } + var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime); + if (msUntil <= 0) { return ImmediatePriority; } + if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) { return UserBlockingPriority$1; } + if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) { return NormalPriority; - } - - // TODO: Handle LowPriority - + } // TODO: Handle LowPriority // Assume anything lower has idle priority + return IdlePriority; } @@ -6213,15 +6070,17 @@ function is(x, y) { ); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = typeof Object.is === "function" ? Object.is : is; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ + function shallowEqual(objA, objB) { - if (is(objA, objB)) { + if (is$1(objA, objB)) { return true; } @@ -6239,13 +6098,12 @@ function shallowEqual(objA, objB) { if (keysA.length !== keysB.length) { return false; - } + } // Test for A's keys different from B. - // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if ( !hasOwnProperty.call(objB, keysA[i]) || - !is(objA[keysA[i]], objB[keysA[i]]) + !is$1(objA[keysA[i]], objB[keysA[i]]) ) { return false; } @@ -6267,14 +6125,13 @@ function shallowEqual(objA, objB) { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - -var lowPriorityWarning = function() {}; +var lowPriorityWarningWithoutStack = function() {}; { var printWarning = function(format) { for ( var _len = arguments.length, - args = Array(_len > 1 ? _len - 1 : 0), + args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ @@ -6288,9 +6145,11 @@ var lowPriorityWarning = function() {}; format.replace(/%s/g, function() { return args[argIndex++]; }); + if (typeof console !== "undefined") { console.warn(message); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -6299,17 +6158,18 @@ var lowPriorityWarning = function() {}; } catch (x) {} }; - lowPriorityWarning = function(condition, format) { + lowPriorityWarningWithoutStack = function(condition, format) { if (format === undefined) { throw new Error( - "`lowPriorityWarning(condition, format, ...args)` requires a warning " + + "`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning " + "message argument" ); } + if (!condition) { for ( var _len2 = arguments.length, - args = Array(_len2 > 2 ? _len2 - 2 : 0), + args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++ @@ -6317,12 +6177,12 @@ var lowPriorityWarning = function() {}; args[_key2 - 2] = arguments[_key2]; } - printWarning.apply(undefined, [format].concat(args)); + printWarning.apply(void 0, [format].concat(args)); } }; } -var lowPriorityWarning$1 = lowPriorityWarning; +var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack; var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function(fiber, instance) {}, @@ -6335,12 +6195,13 @@ var ReactStrictModeWarnings = { { var findStrictRoot = function(fiber) { var maybeStrictRoot = null; - var node = fiber; + while (node !== null) { if (node.mode & StrictMode) { maybeStrictRoot = node; } + node = node.return; } @@ -6360,9 +6221,8 @@ var ReactStrictModeWarnings = { var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function( @@ -6375,8 +6235,7 @@ var ReactStrictModeWarnings = { } if ( - typeof instance.componentWillMount === "function" && - // Don't warn about react-lifecycles-compat polyfilled components. + typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true ) { pendingComponentWillMountWarnings.push(fiber); @@ -6421,6 +6280,7 @@ var ReactStrictModeWarnings = { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); + if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function(fiber) { componentWillMountUniqueNames.add( @@ -6432,6 +6292,7 @@ var ReactStrictModeWarnings = { } var UNSAFE_componentWillMountUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { UNSAFE_componentWillMountUniqueNames.add( @@ -6443,6 +6304,7 @@ var ReactStrictModeWarnings = { } var componentWillReceivePropsUniqueNames = new Set(); + if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { componentWillReceivePropsUniqueNames.add( @@ -6450,11 +6312,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add( @@ -6462,11 +6324,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); + if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function(fiber) { componentWillUpdateUniqueNames.add( @@ -6474,11 +6336,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { UNSAFE_componentWillUpdateUniqueNames.add( @@ -6486,18 +6348,16 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - - // Finally, we flush all the warnings + } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' + if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); warningWithoutStack$1( false, "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6508,11 +6368,12 @@ var ReactStrictModeWarnings = { var _sortedNames = setToSortedString( UNSAFE_componentWillReceivePropsUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6526,11 +6387,12 @@ var ReactStrictModeWarnings = { var _sortedNames2 = setToSortedString( UNSAFE_componentWillUpdateUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6540,10 +6402,10 @@ var ReactStrictModeWarnings = { if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillMount has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6559,10 +6421,10 @@ var ReactStrictModeWarnings = { componentWillReceivePropsUniqueNames ); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6579,10 +6441,10 @@ var ReactStrictModeWarnings = { if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6594,9 +6456,8 @@ var ReactStrictModeWarnings = { } }; - var pendingLegacyContextWarning = new Map(); + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function( @@ -6604,6 +6465,7 @@ var ReactStrictModeWarnings = { instance ) { var strictRoot = findStrictRoot(fiber); + if (strictRoot === null) { warningWithoutStack$1( false, @@ -6611,9 +6473,8 @@ var ReactStrictModeWarnings = { "This error is likely caused by a bug in React. Please file an issue." ); return; - } + } // Dedup strategy: Warn once per component. - // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } @@ -6629,6 +6490,7 @@ var ReactStrictModeWarnings = { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } + warningsForRoot.push(fiber); } }; @@ -6640,20 +6502,18 @@ var ReactStrictModeWarnings = { uniqueNames.add(getComponentName(fiber.type) || "Component"); didWarnAboutLegacyContext.add(fiber.type); }); - var sortedNames = setToSortedString(uniqueNames); var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); - warningWithoutStack$1( false, - "Legacy context API has been detected within a strict-mode tree: %s" + + "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:" + - "\nhttps://fb.me/react-legacy-context", - strictRootComponentStack, - sortedNames + "\n\nLearn more about this warning here: https://fb.me/react-legacy-context" + + "%s", + sortedNames, + strictRootComponentStack ); }); }; @@ -6669,47 +6529,43 @@ var ReactStrictModeWarnings = { }; } -// Resolves type to a family. - -// Used by React Refresh runtime through DevTools Global Hook. +var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -var resolveFamily = null; -// $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; - var setRefreshHandler = function(handler) { { resolveFamily = handler; } }; - function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } - function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if ( @@ -6721,24 +6577,27 @@ function resolveForwardRefForHotReloading(type) { // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); + if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; + if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } + return syntheticType; } } + return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { @@ -6747,11 +6606,9 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } var prevType = fiber.elementType; - var nextType = element.type; + var nextType = element.type; // If we got here, we know types aren't === equal. - // If we got here, we know types aren't === equal. var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof @@ -6762,8 +6619,10 @@ function isCompatibleFamilyForHotReloading(fiber, element) { if (typeof nextType === "function") { needsCompareFamilies = true; } + break; } + case FunctionComponent: { if (typeof nextType === "function") { needsCompareFamilies = true; @@ -6774,16 +6633,20 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } + break; } + case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { @@ -6793,13 +6656,14 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + default: return false; - } + } // Check if both types have a family and it's the same one. - // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. @@ -6807,50 +6671,52 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } + return false; } } - function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } + if (typeof WeakSet !== "function") { return; } + if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } + failedBoundaries.add(fiber); } } - var scheduleRefresh = function(root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } - var _staleFamilies = update.staleFamilies, - _updatedFamilies = update.updatedFamilies; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function() { scheduleFibersWithFamiliesRecursively( root.current, - _updatedFamilies, - _staleFamilies + updatedFamilies, + staleFamilies ); }); } }; - var scheduleRoot = function(root, element) { { if (root.context !== emptyContextObject) { @@ -6859,8 +6725,11 @@ var scheduleRoot = function(root, element) { // Just ignore. We'll delete this with _renderSubtree code path later. return; } + flushPassiveEffects(); - updateContainerAtExpirationTime(element, root, null, Sync, null); + syncUpdates(function() { + updateContainer(element, root, null, null); + }); } }; @@ -6875,17 +6744,19 @@ function scheduleFibersWithFamiliesRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } @@ -6896,8 +6767,10 @@ function scheduleFibersWithFamiliesRecursively( var needsRender = false; var needsRemount = false; + if (candidateType !== null) { var family = resolveFamily(candidateType); + if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; @@ -6910,6 +6783,7 @@ function scheduleFibersWithFamiliesRecursively( } } } + if (failedBoundaries !== null) { if ( failedBoundaries.has(fiber) || @@ -6922,9 +6796,11 @@ function scheduleFibersWithFamiliesRecursively( if (needsRemount) { fiber._debugNeedsRemount = true; } + if (needsRemount || needsRender) { scheduleWork(fiber, Sync); } + if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively( child, @@ -6932,6 +6808,7 @@ function scheduleFibersWithFamiliesRecursively( staleFamilies ); } + if (sibling !== null) { scheduleFibersWithFamiliesRecursively( sibling, @@ -6969,22 +6846,25 @@ function findHostInstancesForMatchingFibersRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } var didMatch = false; + if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; @@ -7023,26 +6903,32 @@ function findHostInstancesForFiberShallowly(fiber, hostInstances) { fiber, hostInstances ); + if (foundHostInstances) { return; - } - // If we didn't find any host children, fallback to closest host parent. + } // If we didn't find any host children, fallback to closest host parent. + var node = fiber; + while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; + case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; + case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } + if (node.return === null) { throw new Error("Expected to reach root first."); } + node = node.return; } } @@ -7052,30 +6938,35 @@ function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; + while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; - hostInstances.add(node.stateNode); - // There may still be more, so keep searching. + hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === fiber) { return foundHostInstances; } + while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } + return false; } @@ -7084,78 +6975,31 @@ function resolveDefaultProps(Component, baseProps) { // Resolve default props. Taken from ReactElement var props = Object.assign({}, baseProps); var defaultProps = Component.defaultProps; + for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } + return props; } + return baseProps; } - function readLazyComponentType(lazyComponent) { - var status = lazyComponent._status; - var result = lazyComponent._result; - switch (status) { - case Resolved: { - var Component = result; - return Component; - } - case Rejected: { - var error = result; - throw error; - } - case Pending: { - var thenable = result; - throw thenable; - } - default: { - lazyComponent._status = Pending; - var ctor = lazyComponent._ctor; - var _thenable = ctor(); - _thenable.then( - function(moduleObject) { - if (lazyComponent._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === undefined) { - 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 - ); - } - } - lazyComponent._status = Resolved; - lazyComponent._result = defaultExport; - } - }, - function(error) { - if (lazyComponent._status === Pending) { - lazyComponent._status = Rejected; - lazyComponent._result = error; - } - } - ); - // Handle synchronous thenables. - switch (lazyComponent._status) { - case Resolved: - return lazyComponent._result; - case Rejected: - throw lazyComponent._result; - } - lazyComponent._result = _thenable; - throw _thenable; - } + initializeLazyComponentType(lazyComponent); + + if (lazyComponent._status !== Resolved) { + throw lazyComponent._result; } + + return lazyComponent._result; } var valueCursor = createCursor(null); +var rendererSigil; -var rendererSigil = void 0; { // Use this to detect multiple renderers using the same context rendererSigil = {}; @@ -7164,39 +7008,35 @@ var rendererSigil = void 0; var currentlyRenderingFiber = null; var lastContextDependency = null; var lastContextWithAllBitsObserved = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; + { isDisallowedContextReadInDEV = false; } } - function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } - function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } - function pushProvider(providerFiber, nextValue) { var context = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; + { !( context._currentRenderer === undefined || @@ -7213,8 +7053,8 @@ function pushProvider(providerFiber, nextValue) { } } else { push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; + { !( context._currentRenderer2 === undefined || @@ -7231,22 +7071,19 @@ function pushProvider(providerFiber, nextValue) { } } } - function popProvider(providerFiber) { var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - var context = providerFiber.type._context; + if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } - function calculateChangedBits(context, newValue, oldValue) { - if (is(oldValue, newValue)) { + if (is$1(oldValue, newValue)) { // No change return 0; } else { @@ -7265,18 +7102,21 @@ function calculateChangedBits(context, newValue, oldValue) { ) : void 0; } + return changedBits | 0; } } - function scheduleWorkOnParentPath(parent, renderExpirationTime) { // Update the child expiration time of all the ancestors, including // the alternates. var node = parent; + while (node !== null) { var alternate = node.alternate; + if (node.childExpirationTime < renderExpirationTime) { node.childExpirationTime = renderExpirationTime; + if ( alternate !== null && alternate.childExpirationTime < renderExpirationTime @@ -7293,10 +7133,10 @@ function scheduleWorkOnParentPath(parent, renderExpirationTime) { // ancestor path already has sufficient priority. break; } + node = node.return; } } - function propagateContextChange( workInProgress, context, @@ -7304,19 +7144,21 @@ function propagateContextChange( renderExpirationTime ) { var fiber = workInProgress.child; + if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } + while (fiber !== null) { - var nextFiber = void 0; + var nextFiber = void 0; // Visit this fiber. - // Visit this fiber. var list = fiber.dependencies; + if (list !== null) { nextFiber = fiber.child; - var dependency = list.firstContext; + while (dependency !== null) { // Check if the context matches. if ( @@ -7324,22 +7166,23 @@ function propagateContextChange( (dependency.observedBits & changedBits) !== 0 ) { // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var update = createUpdate(renderExpirationTime, null); - update.tag = ForceUpdate; - // TODO: Because we don't have a work-in-progress, this will add the + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. + enqueueUpdate(fiber, update); } if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } + var alternate = fiber.alternate; + if ( alternate !== null && alternate.expirationTime < renderExpirationTime @@ -7347,17 +7190,16 @@ function propagateContextChange( alternate.expirationTime = renderExpirationTime; } - scheduleWorkOnParentPath(fiber.return, renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. - // Mark the expiration time on the list, too. if (list.expirationTime < renderExpirationTime) { list.expirationTime = renderExpirationTime; - } - - // Since we already found a match, we can stop traversing the + } // Since we already found a match, we can stop traversing the // dependency list. + break; } + dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { @@ -7365,26 +7207,36 @@ function propagateContextChange( nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if ( enableSuspenseServerRenderer && - fiber.tag === DehydratedSuspenseComponent + fiber.tag === DehydratedFragment ) { - // If a dehydrated suspense component is in this subtree, we don't know + // If a dehydrated suspense bounudary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is - // mark it as having updates on its children. - if (fiber.expirationTime < renderExpirationTime) { - fiber.expirationTime = renderExpirationTime; + // mark it as having updates. + var parentSuspense = fiber.return; + + if (!(parentSuspense !== null)) { + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + } + + if (parentSuspense.expirationTime < renderExpirationTime) { + parentSuspense.expirationTime = renderExpirationTime; } - var _alternate = fiber.alternate; + + var _alternate = parentSuspense.alternate; + if ( _alternate !== null && _alternate.expirationTime < renderExpirationTime ) { _alternate.expirationTime = renderExpirationTime; - } - // This is intentionally passing this fiber as the parent + } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. - scheduleWorkOnParentPath(fiber, renderExpirationTime); + + scheduleWorkOnParentPath(parentSuspense, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. @@ -7397,46 +7249,49 @@ function propagateContextChange( } else { // No child. Traverse to next sibling. nextFiber = fiber; + while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } + var sibling = nextFiber.sibling; + if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; - } - // No more siblings. Traverse up. + } // No more siblings. Traverse up. + nextFiber = nextFiber.return; } } + fiber = nextFiber; } } - function prepareToReadContext(workInProgress, renderExpirationTime) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; - var dependencies = workInProgress.dependencies; + if (dependencies !== null) { var firstContext = dependencies.firstContext; + if (firstContext !== null) { if (dependencies.expirationTime >= renderExpirationTime) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); - } - // Reset the work-in-progress list + } // Reset the work-in-progress list + dependencies.firstContext = null; } } } - function readContext(context, observedBits) { { // This warning would fire if you read context inside a Hook like useMemo. @@ -7457,7 +7312,8 @@ function readContext(context, observedBits) { } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { - var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. + var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types. + if ( typeof observedBits !== "number" || observedBits === MAX_SIGNED_31_BIT_INT @@ -7476,17 +7332,12 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - (function() { - if (!(currentlyRenderingFiber !== null)) { - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) - ); - } - })(); + if (!(currentlyRenderingFiber !== null)) { + 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()." + ); + } // This is the first dependency for this component. Create a new list. - // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { expirationTime: NoWork, @@ -7498,6 +7349,7 @@ function readContext(context, observedBits) { lastContextDependency = lastContextDependency.next = contextItem; } } + return isPrimaryRenderer ? context._currentValue : context._currentValue2; } @@ -7577,19 +7429,16 @@ function readContext(context, observedBits) { // updates when preceding updates are skipped, the final result is deterministic // regardless of priority. Intermediate state may vary according to system // resources, but the final state is always the same. - var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; -var CaptureUpdate = 3; - -// Global state that is reset at the beginning of calling `processUpdateQueue`. +var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. -var hasForceUpdate = false; -var didWarnUpdateInsideUpdate = void 0; -var currentlyProcessingQueue = void 0; +var hasForceUpdate = false; +var didWarnUpdateInsideUpdate; +var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; @@ -7616,15 +7465,12 @@ function cloneUpdateQueue(currentQueue) { baseState: currentQueue.baseState, firstUpdate: currentQueue.firstUpdate, lastUpdate: currentQueue.lastUpdate, - // TODO: With resuming, if we bail out and resuse the child tree, we should // keep these effects. firstCapturedUpdate: null, lastCapturedUpdate: null, - firstEffect: null, lastEffect: null, - firstCapturedEffect: null, lastCapturedEffect: null }; @@ -7635,17 +7481,17 @@ function createUpdate(expirationTime, suspenseConfig) { var update = { expirationTime: expirationTime, suspenseConfig: suspenseConfig, - tag: UpdateState, payload: null, callback: null, - next: null, nextEffect: null }; + { update.priority = getCurrentPriorityLevel(); } + return update; } @@ -7663,12 +7509,14 @@ function appendUpdateToQueue(queue, update) { function enqueueUpdate(fiber, update) { // Update queues are created lazily. var alternate = fiber.alternate; - var queue1 = void 0; - var queue2 = void 0; + var queue1; + var queue2; + if (alternate === null) { // There's only one fiber. queue1 = fiber.updateQueue; queue2 = null; + if (queue1 === null) { queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); } @@ -7676,6 +7524,7 @@ function enqueueUpdate(fiber, update) { // There are two owners. queue1 = fiber.updateQueue; queue2 = alternate.updateQueue; + if (queue1 === null) { if (queue2 === null) { // Neither fiber has an update queue. Create new ones. @@ -7696,6 +7545,7 @@ function enqueueUpdate(fiber, update) { } } } + if (queue2 === null || queue1 === queue2) { // There's only a single queue. appendUpdateToQueue(queue1, update); @@ -7710,8 +7560,8 @@ function enqueueUpdate(fiber, update) { } else { // Both queues are non-empty. The last update is the same in both lists, // because of structural sharing. So, only append to one of the lists. - appendUpdateToQueue(queue1, update); - // But we still need to update the `lastUpdate` pointer of queue2. + appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2. + queue2.lastUpdate = update; } } @@ -7734,11 +7584,11 @@ function enqueueUpdate(fiber, update) { } } } - function enqueueCapturedUpdate(workInProgress, update) { // Captured updates go into a separate list, and only on the work-in- // progress queue. var workInProgressQueue = workInProgress.updateQueue; + if (workInProgressQueue === null) { workInProgressQueue = workInProgress.updateQueue = createUpdateQueue( workInProgress.memoizedState @@ -7751,9 +7601,8 @@ function enqueueCapturedUpdate(workInProgress, update) { workInProgress, workInProgressQueue ); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. if (workInProgressQueue.lastCapturedUpdate === null) { // This is the first render phase update workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update; @@ -7765,6 +7614,7 @@ function enqueueCapturedUpdate(workInProgress, update) { function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { var current = workInProgress.alternate; + if (current !== null) { // If the work-in-progress queue is equal to the current queue, // we need to clone it first. @@ -7772,6 +7622,7 @@ function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { queue = workInProgress.updateQueue = cloneUpdateQueue(queue); } } + return queue; } @@ -7785,68 +7636,82 @@ function getStateFromUpdate( ) { switch (update.tag) { case ReplaceState: { - var _payload = update.payload; - if (typeof _payload === "function") { + var payload = update.payload; + + if (typeof payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload.call(instance, prevState, nextProps); + payload.call(instance, prevState, nextProps); } } - var nextState = _payload.call(instance, prevState, nextProps); + + var nextState = payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } + return nextState; - } - // State object - return _payload; + } // State object + + return payload; } + case CaptureUpdate: { workInProgress.effectTag = (workInProgress.effectTag & ~ShouldCapture) | DidCapture; } // Intentional fallthrough + case UpdateState: { - var _payload2 = update.payload; - var partialState = void 0; - if (typeof _payload2 === "function") { + var _payload = update.payload; + var partialState; + + if (typeof _payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload2.call(instance, prevState, nextProps); + _payload.call(instance, prevState, nextProps); } } - partialState = _payload2.call(instance, prevState, nextProps); + + partialState = _payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } } else { // Partial state object - partialState = _payload2; + partialState = _payload; } + if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + return Object.assign({}, prevState, partialState); } + case ForceUpdate: { hasForceUpdate = true; return prevState; } } + return prevState; } @@ -7858,50 +7723,47 @@ function processUpdateQueue( renderExpirationTime ) { hasForceUpdate = false; - queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue); { currentlyProcessingQueue = queue; - } + } // These values may change as we process the queue. - // These values may change as we process the queue. var newBaseState = queue.baseState; var newFirstUpdate = null; - var newExpirationTime = NoWork; + var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result. - // Iterate through the list of updates to compute the result. var update = queue.firstUpdate; var resultState = newBaseState; + while (update !== null) { var updateExpirationTime = update.expirationTime; + if (updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstUpdate === null) { // This is the first skipped update. It will be the first update in // the new list. - newFirstUpdate = update; - // Since this is the first update that was skipped, the current result + newFirstUpdate = update; // Since this is the first update that was skipped, the current result // is the new base state. + newBaseState = resultState; - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < updateExpirationTime) { newExpirationTime = updateExpirationTime; } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. // TODO: We should skip this update if it was already committed but currently // we have no way of detecting the difference between a committed and suspended // update here. - markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); + markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result. - // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -7910,11 +7772,13 @@ function processUpdateQueue( props, instance ); - var _callback = update.callback; - if (_callback !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var callback = update.callback; + + if (callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastEffect === null) { queue.firstEffect = queue.lastEffect = update; } else { @@ -7922,30 +7786,31 @@ function processUpdateQueue( queue.lastEffect = update; } } - } - // Continue to the next update. + } // Continue to the next update. + update = update.next; - } + } // Separately, iterate though the list of captured updates. - // Separately, iterate though the list of captured updates. var newFirstCapturedUpdate = null; update = queue.firstCapturedUpdate; + while (update !== null) { var _updateExpirationTime = update.expirationTime; + if (_updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstCapturedUpdate === null) { // This is the first skipped captured update. It will be the first // update in the new list. - newFirstCapturedUpdate = update; - // If this is the first update that was skipped, the current result is + newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is // the new base state. + if (newFirstUpdate === null) { newBaseState = resultState; } - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < _updateExpirationTime) { newExpirationTime = _updateExpirationTime; } @@ -7960,11 +7825,13 @@ function processUpdateQueue( props, instance ); - var _callback2 = update.callback; - if (_callback2 !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var _callback = update.callback; + + if (_callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastCapturedEffect === null) { queue.firstCapturedEffect = queue.lastCapturedEffect = update; } else { @@ -7973,17 +7840,20 @@ function processUpdateQueue( } } } + update = update.next; } if (newFirstUpdate === null) { queue.lastUpdate = null; } + if (newFirstCapturedUpdate === null) { queue.lastCapturedUpdate = null; } else { workInProgress.effectTag |= Callback; } + if (newFirstUpdate === null && newFirstCapturedUpdate === null) { // We processed every update, without skipping. That means the new base // state is the same as the result state. @@ -7992,15 +7862,15 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; - queue.firstCapturedUpdate = newFirstCapturedUpdate; - - // Set the remaining expiration time to be whatever is remaining in the queue. + queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. + + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; @@ -8010,27 +7880,22 @@ function processUpdateQueue( } function callCallback(callback, context) { - (function() { - if (!(typeof callback === "function")) { - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - callback - ) - ); - } - })(); + if (!(typeof callback === "function")) { + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } - function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } - function commitUpdateQueue( finishedWork, finishedQueue, @@ -8046,53 +7911,50 @@ function commitUpdateQueue( if (finishedQueue.lastUpdate !== null) { finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate; finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate; - } - // Clear the list of captured updates. + } // Clear the list of captured updates. + finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null; - } + } // Commit the effects - // Commit the effects commitUpdateEffects(finishedQueue.firstEffect, instance); finishedQueue.firstEffect = finishedQueue.lastEffect = null; - commitUpdateEffects(finishedQueue.firstCapturedEffect, instance); finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null; } function commitUpdateEffects(effect, instance) { while (effect !== null) { - var _callback3 = effect.callback; - if (_callback3 !== null) { + var callback = effect.callback; + + if (callback !== null) { effect.callback = null; - callCallback(_callback3, instance); + callCallback(callback, instance); } + effect = effect.nextEffect; } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - function requestCurrentSuspenseConfig() { return ReactCurrentBatchConfig.suspense; } var fakeInternalInstance = {}; -var isArray$1 = Array.isArray; - -// React.Component uses a shared frozen object by default. +var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. -var emptyRefsObject = new React.Component().refs; -var didWarnAboutStateAssignmentForComponent = void 0; -var didWarnAboutUninitializedState = void 0; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; -var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; -var didWarnAboutUndefinedDerivedState = void 0; -var warnOnUndefinedDerivedState = void 0; -var warnOnInvalidCallback = void 0; -var didWarnAboutDirectlyAssigningPropsToState = void 0; -var didWarnAboutContextTypeAndContextTypes = void 0; -var didWarnAboutInvalidateContextType = void 0; +var emptyRefsObject = new React.Component().refs; +var didWarnAboutStateAssignmentForComponent; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; { didWarnAboutStateAssignmentForComponent = new Set(); @@ -8103,14 +7965,15 @@ var didWarnAboutInvalidateContextType = void 0; didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function(callback, callerName) { if (callback === null || typeof callback === "function") { return; } + var key = callerName + "_" + callback; + if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); warningWithoutStack$1( @@ -8126,6 +7989,7 @@ var didWarnAboutInvalidateContextType = void 0; warnOnUndefinedDerivedState = function(type, partialState) { if (partialState === undefined) { var componentName = getComponentName(type) || "Component"; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); warningWithoutStack$1( @@ -8136,25 +8000,20 @@ var didWarnAboutInvalidateContextType = void 0; ); } } - }; - - // This is so gross but it's at least non-critical and can be removed if + }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. + Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - (function() { - { - throw ReactError( - Error( - "_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)." - ) - ); - } - })(); + { + 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)." + ); + } } }); Object.freeze(fakeInternalInstance); @@ -8183,22 +8042,21 @@ function applyDerivedStateFromProps( { warnOnUndefinedDerivedState(ctor, partialState); - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + var memoizedState = partialState === null || partialState === undefined ? prevState : Object.assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; - - // Once the update queue is empty, persist the derived state onto the + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. + var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null && workInProgress.expirationTime === NoWork) { updateQueue.baseState = memoizedState; } } - var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { @@ -8210,19 +8068,17 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.payload = payload; + if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, "setState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -8235,7 +8091,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ReplaceState; update.payload = payload; @@ -8244,12 +8099,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "replaceState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -8262,7 +8115,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ForceUpdate; @@ -8270,12 +8122,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "forceUpdate"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); } @@ -8291,6 +8141,7 @@ function checkShouldComponentUpdate( nextContext ) { var instance = workInProgress.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { startPhaseTimer(workInProgress, "shouldComponentUpdate"); var shouldUpdate = instance.shouldComponentUpdate( @@ -8325,6 +8176,7 @@ function checkShouldComponentUpdate( function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; + { var name = getComponentName(ctor) || "Component"; var renderPresent = instance.render; @@ -8400,6 +8252,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (ctor.contextTypes) { warningWithoutStack$1( false, @@ -8446,6 +8299,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ) : void 0; + if ( ctor.prototype && ctor.prototype.isPureReactComponent && @@ -8459,6 +8313,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { getComponentName(ctor) || "A pure component" ); } + var noComponentDidUnmount = typeof instance.componentDidUnmount !== "function"; !noComponentDidUnmount @@ -8569,6 +8424,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { ) : void 0; var _state = instance.state; + if (_state && (typeof _state !== "object" || isArray$1(_state))) { warningWithoutStack$1( false, @@ -8576,6 +8432,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (typeof instance.getChildContext === "function") { !(typeof ctor.childContextTypes === "object") ? warningWithoutStack$1( @@ -8591,9 +8448,10 @@ function checkClassInstance(workInProgress, ctor, newProps) { function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates + set(instance, workInProgress); + { instance._reactInternalInstance = fakeInternalInstance; } @@ -8612,8 +8470,7 @@ function constructClassInstance( { if ("contextType" in ctor) { - var isValid = - // Allow null for conditional declaration + var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && @@ -8621,8 +8478,8 @@ function constructClassInstance( if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + if (contextType === undefined) { addendum = " However, it is set to undefined. " + @@ -8642,6 +8499,7 @@ function constructClassInstance( Object.keys(contextType).join(", ") + "}."; } + warningWithoutStack$1( false, "%s defines an invalid contextType. " + @@ -8663,9 +8521,8 @@ function constructClassInstance( context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } + } // Instantiate twice to help detect side-effects. - // Instantiate twice to help detect side-effects. { if ( debugRenderPhaseSideEffects || @@ -8686,6 +8543,7 @@ function constructClassInstance( { if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); warningWithoutStack$1( @@ -8699,11 +8557,10 @@ function constructClassInstance( componentName ); } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. + } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. + if ( typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function" @@ -8711,6 +8568,7 @@ function constructClassInstance( var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; + if ( typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true @@ -8719,6 +8577,7 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillMount === "function") { foundWillMountName = "UNSAFE_componentWillMount"; } + if ( typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true @@ -8729,6 +8588,7 @@ function constructClassInstance( ) { foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; } + if ( typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true @@ -8737,16 +8597,19 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { foundWillUpdateName = "UNSAFE_componentWillUpdate"; } + if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { var _componentName = getComponentName(ctor) || "Component"; + var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); warningWithoutStack$1( @@ -8754,7 +8617,7 @@ function constructClassInstance( "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://fb.me/react-async-component-lifecycle-hooks", + "https://fb.me/react-unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -8766,10 +8629,9 @@ function constructClassInstance( } } } - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. + if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } @@ -8784,6 +8646,7 @@ function callComponentWillMount(workInProgress, instance) { if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } @@ -8800,6 +8663,7 @@ function callComponentWillMount(workInProgress, instance) { getComponentName(workInProgress.type) || "Component" ); } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } @@ -8812,17 +8676,21 @@ function callComponentWillReceiveProps( ) { var oldState = instance.state; startPhaseTimer(workInProgress, "componentWillReceiveProps"); + if (typeof instance.componentWillReceiveProps === "function") { instance.componentWillReceiveProps(newProps, nextContext); } + if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } + stopPhaseTimer(); if (instance.state !== oldState) { { var componentName = getComponentName(workInProgress.type) || "Component"; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); warningWithoutStack$1( @@ -8834,11 +8702,11 @@ function callComponentWillReceiveProps( ); } } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } -} +} // Invokes the mount life-cycles on a previously never rendered instance. -// Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance( workInProgress, ctor, @@ -8853,8 +8721,8 @@ function mountClassInstance( instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; - var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else if (disableLegacyContext) { @@ -8867,6 +8735,7 @@ function mountClassInstance( { if (instance.state === newProps) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); warningWithoutStack$1( @@ -8895,6 +8764,7 @@ function mountClassInstance( } var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8907,6 +8777,7 @@ function mountClassInstance( } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -8915,20 +8786,20 @@ function mountClassInstance( newProps ); instance.state = workInProgress.memoizedState; - } - - // In order to support react-lifecycles-compat polyfilled components, + } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function") ) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. + updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8953,13 +8824,12 @@ function resumeMountClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = oldProps; - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8974,14 +8844,12 @@ function resumeMountClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8998,10 +8866,10 @@ function resumeMountClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -9012,6 +8880,7 @@ function resumeMountClassInstance( ); newState = workInProgress.memoizedState; } + if ( oldProps === newProps && oldState === newState && @@ -9023,6 +8892,7 @@ function resumeMountClassInstance( if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } + return false; } @@ -9057,14 +8927,18 @@ function resumeMountClassInstance( typeof instance.componentWillMount === "function") ) { startPhaseTimer(workInProgress, "componentWillMount"); + if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } + stopPhaseTimer(); } + if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } @@ -9073,24 +8947,20 @@ function resumeMountClassInstance( // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; -} +} // Invokes the update life-cycles and returns false if it shouldn't rerender. -// Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance( current, workInProgress, @@ -9099,16 +8969,15 @@ function updateClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -9119,14 +8988,12 @@ function updateClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -9143,10 +9010,10 @@ function updateClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -9174,6 +9041,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -9182,6 +9050,7 @@ function updateClassInstance( workInProgress.effectTag |= Snapshot; } } + return false; } @@ -9216,17 +9085,22 @@ function updateClassInstance( typeof instance.componentWillUpdate === "function") ) { startPhaseTimer(workInProgress, "componentWillUpdate"); + if (typeof instance.componentWillUpdate === "function") { instance.componentWillUpdate(newProps, newState, nextContext); } + if (typeof instance.UNSAFE_componentWillUpdate === "function") { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } + stopPhaseTimer(); } + if (typeof instance.componentDidUpdate === "function") { workInProgress.effectTag |= Update; } + if (typeof instance.getSnapshotBeforeUpdate === "function") { workInProgress.effectTag |= Snapshot; } @@ -9241,6 +9115,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -9248,40 +9123,38 @@ function updateClassInstance( ) { workInProgress.effectTag |= Snapshot; } - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; } -var didWarnAboutMaps = void 0; -var didWarnAboutGenerators = void 0; -var didWarnAboutStringRefs = void 0; -var ownerHasKeyUseWarning = void 0; -var ownerHasFunctionTypeWarning = void 0; +var didWarnAboutMaps; +var didWarnAboutGenerators; +var didWarnAboutStringRefs; +var ownerHasKeyUseWarning; +var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; - /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ + ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; @@ -9289,30 +9162,29 @@ var warnForMissingKey = function(child) {}; if (child === null || typeof child !== "object") { return; } + if (!child._store || child._store.validated || child.key != null) { return; } - (function() { - if (!(typeof child._store === "object")) { - throw ReactError( - Error( - "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - child._store.validated = true; + if (!(typeof child._store === "object")) { + throw Error( + "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." + ); + } + + child._store.validated = true; var currentComponentErrorInfo = "Each child in a list should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information." + getCurrentFiberStackInDev(); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning$1( false, "Each child in a list should have a unique " + @@ -9326,6 +9198,7 @@ var isArray = Array.isArray; function coerceRef(returnFiber, current$$1, element) { var mixedRef = element.ref; + if ( mixedRef !== null && typeof mixedRef !== "function" && @@ -9336,16 +9209,16 @@ function coerceRef(returnFiber, current$$1, element) { // everyone, because the strict mode case will no longer be relevant if (returnFiber.mode & StrictMode || warnAboutStringRefs) { var componentName = getComponentName(returnFiber.type) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { if (warnAboutStringRefs) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://fb.me/react-strict-mode-string-ref%s", componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber) @@ -9355,14 +9228,14 @@ function coerceRef(returnFiber, current$$1, element) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "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) ); } + didWarnAboutStringRefs[componentName] = true; } } @@ -9370,33 +9243,30 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { var owner = element._owner; - var inst = void 0; + var inst; + if (owner) { var ownerFiber = owner; - (function() { - if (!(ownerFiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) - ); - } - })(); - inst = ownerFiber.stateNode; - } - (function() { - if (!inst) { - throw ReactError( - Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a bug in React. Please file an issue." - ) + + if (!(ownerFiber.tag === ClassComponent)) { + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); } - })(); - var stringRef = "" + mixedRef; - // Check if previous string ref matches new string ref + + inst = ownerFiber.stateNode; + } + + if (!inst) { + throw Error( + "Missing owner for string ref " + + mixedRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + } + + var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + if ( current$$1 !== null && current$$1.ref !== null && @@ -9405,69 +9275,65 @@ function coerceRef(returnFiber, current$$1, element) { ) { return current$$1.ref; } + var ref = function(value) { var refs = inst.refs; + if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = inst.refs = {}; } + if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; + ref._stringRef = stringRef; return ref; } else { - (function() { - if (!(typeof mixedRef === "string")) { - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) - ); - } - })(); - (function() { - if (!element._owner) { - throw ReactError( - Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information." - ) - ); - } - })(); + if (!(typeof mixedRef === "string")) { + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + + if (!element._owner) { + 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." + ); + } } } + return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { if (returnFiber.type !== "textarea") { var addendum = ""; + { addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentFiberStackInDev(); } - (function() { - { - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - (Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." + - addendum - ) - ); - } - })(); + + { + 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 + ); + } } } @@ -9481,38 +9347,39 @@ function warnOnFunctionType() { if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } - ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; + ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning$1( false, "Functions are not valid as a React child. This may happen if " + "you return a Component instead of from render. " + "Or maybe you meant to call this function rather than return it." ); -} - -// This wrapper function exists because I expect to clone the code in each path +} // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. + function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; - } - // Deletions are added in reversed order so we add it to the front. + } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } + childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } @@ -9521,32 +9388,36 @@ function ChildReconciler(shouldTrackSideEffects) { if (!shouldTrackSideEffects) { // Noop. return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by + } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. + var childToDelete = currentFirstChild; + while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } + return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index + // instead. var existingChildren = new Map(); - var existingChild = currentFirstChild; + while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } + existingChild = existingChild.sibling; } + return existingChildren; } @@ -9561,13 +9432,17 @@ function ChildReconciler(shouldTrackSideEffects) { function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; + if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } + var current$$1 = newFiber.alternate; + if (current$$1 !== null) { var oldIndex = current$$1.index; + if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; @@ -9589,6 +9464,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } + return newFiber; } @@ -9618,18 +9494,19 @@ function ChildReconciler(shouldTrackSideEffects) { function updateElement(returnFiber, current$$1, element, expirationTime) { if ( current$$1 !== null && - (current$$1.elementType === element.type || - // Keep this check inline so it only runs on the false path: + (current$$1.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current$$1, element)) ) { // Move based on index var existing = useFiber(current$$1, element.props, expirationTime); existing.ref = coerceRef(returnFiber, current$$1, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { // Insert @@ -9718,16 +9595,19 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } + case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal( newChild, returnFiber.mode, expirationTime ); + _created2.return = returnFiber; return _created2; } @@ -9740,6 +9620,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime, null ); + _created3.return = returnFiber; return _created3; } @@ -9758,7 +9639,6 @@ function ChildReconciler(shouldTrackSideEffects) { function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === "string" || typeof newChild === "number") { @@ -9768,6 +9648,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (key !== null) { return null; } + return updateTextNode( returnFiber, oldFiber, @@ -9789,6 +9670,7 @@ function ChildReconciler(shouldTrackSideEffects) { key ); } + return updateElement( returnFiber, oldFiber, @@ -9799,6 +9681,7 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } } + case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal( @@ -9865,6 +9748,7 @@ function ChildReconciler(shouldTrackSideEffects) { existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment( returnFiber, @@ -9874,6 +9758,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChild.key ); } + return updateElement( returnFiber, _matchedFiber, @@ -9881,11 +9766,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ); } + case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + return updatePortal( returnFiber, _matchedFiber2, @@ -9897,6 +9784,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; + return updateFragment( returnFiber, _matchedFiber3, @@ -9917,32 +9805,37 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } - /** * Warns if there is a duplicate or missing key */ + function warnOnInvalidKey(child, knownKeys) { { if (typeof child !== "object" || child === null) { return knownKeys; } + switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); var key = child.key; + if (typeof key !== "string") { break; } + if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } + if (!knownKeys.has(key)) { knownKeys.add(key); break; } + warning$1( false, "Encountered two children with the same key, `%s`. " + @@ -9953,10 +9846,12 @@ function ChildReconciler(shouldTrackSideEffects) { key ); break; + default: break; } } + return knownKeys; } @@ -9970,7 +9865,6 @@ function ChildReconciler(shouldTrackSideEffects) { // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. - // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in @@ -9978,16 +9872,14 @@ function ChildReconciler(shouldTrackSideEffects) { // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. - { // First, validate keys. var knownKeys = null; + for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9996,11 +9888,11 @@ function ChildReconciler(shouldTrackSideEffects) { var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; @@ -10008,12 +9900,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, newChildren[newIdx], expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -10022,8 +9916,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -10031,7 +9927,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -10042,6 +9940,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -10061,25 +9960,28 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber === null) { continue; } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } + previousNewFiber = _newFiber; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( existingChildren, @@ -10088,6 +9990,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { @@ -10100,12 +10003,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } + previousNewFiber = _newFiber2; } } @@ -10129,24 +10035,19 @@ function ChildReconciler(shouldTrackSideEffects) { ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - (function() { - if (!(typeof iteratorFn === "function")) { - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof iteratorFn === "function")) { + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); + } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if ( - typeof Symbol === "function" && - // $FlowFixMe Flow doesn't know about toStringTag + typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === "Generator" ) { !didWarnAboutGenerators @@ -10160,9 +10061,8 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutGenerators = true; - } + } // Warn about using Maps as children - // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { !didWarnAboutMaps ? warning$1( @@ -10173,14 +10073,16 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutMaps = true; - } - - // First, validate keys. + } // First, validate keys. // We'll get a different iterator later for the main pass. + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) { var knownKeys = null; + var _step = _newChildren.next(); + for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -10189,21 +10091,19 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - (function() { - if (!(newChildren != null)) { - throw ReactError(Error("An iterable object provided no iterator.")); - } - })(); + + if (!(newChildren != null)) { + throw Error("An iterable object provided no iterator."); + } var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; - var step = newChildren.next(); + for ( ; oldFiber !== null && !step.done; @@ -10215,12 +10115,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, step.value, expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -10229,8 +10131,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -10238,7 +10142,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -10249,6 +10155,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -10264,25 +10171,28 @@ function ChildReconciler(shouldTrackSideEffects) { // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, expirationTime); + if (_newFiber3 === null) { continue; } + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } + previousNewFiber = _newFiber3; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( existingChildren, @@ -10291,6 +10201,7 @@ function ChildReconciler(shouldTrackSideEffects) { step.value, expirationTime ); + if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { @@ -10303,12 +10214,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } + previousNewFiber = _newFiber4; } } @@ -10339,9 +10253,9 @@ function ChildReconciler(shouldTrackSideEffects) { var existing = useFiber(currentFirstChild, textContent, expirationTime); existing.return = returnFiber; return existing; - } - // The existing first child is not a text node so we need to create one + } // The existing first child is not a text node so we need to create one // and delete the existing ones. + deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText( textContent, @@ -10360,6 +10274,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = element.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10367,8 +10282,7 @@ function ChildReconciler(shouldTrackSideEffects) { 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: + : child.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) { deleteRemainingChildren(returnFiber, child.sibling); @@ -10381,10 +10295,12 @@ function ChildReconciler(shouldTrackSideEffects) { ); existing.ref = coerceRef(returnFiber, child, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { deleteRemainingChildren(returnFiber, child); @@ -10393,6 +10309,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10411,6 +10328,7 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; @@ -10425,6 +10343,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = portal.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10445,6 +10364,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10455,11 +10375,10 @@ function ChildReconciler(shouldTrackSideEffects) { ); created.return = returnFiber; return created; - } - - // This API will tag the children with the side-effect of the reconciliation + } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. + function reconcileChildFibers( returnFiber, currentFirstChild, @@ -10470,7 +10389,6 @@ function ChildReconciler(shouldTrackSideEffects) { // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]} and <>.... // We treat the ambiguous cases above the same. @@ -10479,11 +10397,11 @@ function ChildReconciler(shouldTrackSideEffects) { newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; - } + } // Handle object types - // Handle object types var isObject = typeof newChild === "object" && newChild !== null; if (isObject) { @@ -10497,6 +10415,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) ); + case REACT_PORTAL_TYPE: return placeSingleChild( reconcileSinglePortal( @@ -10547,6 +10466,7 @@ function ChildReconciler(shouldTrackSideEffects) { warnOnFunctionType(); } } + if (typeof newChild === "undefined" && !isUnkeyedTopLevelFragment) { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, @@ -10555,6 +10475,7 @@ function ChildReconciler(shouldTrackSideEffects) { case ClassComponent: { { var instance = returnFiber.stateNode; + if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; @@ -10564,23 +10485,20 @@ function ChildReconciler(shouldTrackSideEffects) { // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough + case FunctionComponent: { var Component = returnFiber.type; - (function() { - { - throw ReactError( - Error( - (Component.displayName || Component.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) - ); - } - })(); + + { + 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." + ); + } } } - } + } // Remaining cases are all treated as empty. - // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } @@ -10589,13 +10507,10 @@ function ChildReconciler(shouldTrackSideEffects) { var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current$$1, workInProgress) { - (function() { - if (!(current$$1 === null || workInProgress.child === current$$1.child)) { - throw ReactError(Error("Resuming work not yet implemented.")); - } - })(); + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw Error("Resuming work not yet implemented."); + } if (workInProgress.child === null) { return; @@ -10608,8 +10523,8 @@ function cloneChildFibers(current$$1, workInProgress) { currentChild.expirationTime ); workInProgress.child = newChild; - newChild.return = workInProgress; + while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress( @@ -10619,12 +10534,13 @@ function cloneChildFibers(current$$1, workInProgress) { ); newChild.return = workInProgress; } + newChild.sibling = null; -} +} // Reset a workInProgress child set to prepare it for a second pass. -// Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, renderExpirationTime) { var child = workInProgress.child; + while (child !== null) { resetWorkInProgress(child, renderExpirationTime); child = child.sibling; @@ -10632,21 +10548,17 @@ function resetChildFibers(workInProgress, renderExpirationTime) { } var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - (function() { - if (!(c !== NO_CONTEXT)) { - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(c !== NO_CONTEXT)) { + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + return c; } @@ -10658,19 +10570,18 @@ function getRootHostContainer() { function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - // Finally, we need to push the host context to the stack. + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. + push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. + pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } @@ -10689,15 +10600,13 @@ function getHostContext() { function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; - } - - // Track the context and the Fiber that provided it. + } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. + push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } @@ -10713,98 +10622,100 @@ function popHostContext(fiber) { pop(contextFiberStackCursor, fiber); } -var DefaultSuspenseContext = 0; - -// The Suspense Context is split into two parts. The lower bits is +var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. -var SubtreeSuspenseContextMask = 1; - -// Subtree Flags: +var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. -var InvisibleParentSuspenseContext = 1; - -// Shallow Flags: +var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. -var ForceSuspenseFallback = 2; +var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } - function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } - function setShallowSuspenseContext(parentContext, shallowContext) { return (parentContext & SubtreeSuspenseContextMask) | shallowContext; } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } - function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } - function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } -// TODO: This is now an empty object. Should we switch this to a boolean? -// Alternatively we can make this use an effect tag similar to SuspenseList. - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } + return false; } - var props = workInProgress.memoizedProps; - // In order to capture, the Suspense component must have a fallback prop. + + var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop. + if (props.fallback === undefined) { return false; - } - // Regular boundaries always capture. + } // Regular boundaries always capture. + if (props.unstable_avoidThisFallback !== true) { return true; - } - // If it's a boundary we should avoid, then we prefer to bubble up to the + } // If it's a boundary we should avoid, then we prefer to bubble up to the // parent boundary if it is currently invisible. + if (hasInvisibleParent) { return false; - } - // If the parent is not able to handle it, we must handle it. + } // If the parent is not able to handle it, we must handle it. + return true; } - function findFirstSuspended(row) { var node = row; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - return node; + var dehydrated = state.dehydrated; + + if ( + dehydrated === null || + isSuspenseInstancePending(dehydrated) || + isSuspenseInstanceFallback(dehydrated) + ) { + return node; + } } } else if ( - node.tag === SuspenseListComponent && - // revealOrder undefined can't be trusted because it don't + node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { var didSuspend = (node.effectTag & DidCapture) !== NoEffect; + if (didSuspend) { return node; } @@ -10813,37 +10724,32 @@ function findFirstSuspended(row) { node = node.child; continue; } + if (node === row) { return null; } + while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - return null; -} -function createResponderListener(responder, props) { - var eventResponderListener = { - responder: responder, - props: props - }; - { - Object.freeze(eventResponderListener); - } - return eventResponderListener; + return null; } +var emptyObject$1 = {}; +var isArray$2 = Array.isArray; function createResponderInstance( responder, responderProps, responderState, - target, fiber ) { return { @@ -10851,95 +10757,284 @@ function createResponderInstance( props: responderProps, responder: responder, rootEventTypes: null, - state: responderState, - target: target + state: responderState }; } -var NoEffect$1 = /* */ 0; -var UnmountSnapshot = /* */ 2; -var UnmountMutation = /* */ 4; -var MountMutation = /* */ 8; -var UnmountLayout = /* */ 16; -var MountLayout = /* */ 32; -var MountPassive = /* */ 64; -var UnmountPassive = /* */ 128; - -var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - -var didWarnAboutMismatchedHooksForComponent = void 0; -{ - didWarnAboutMismatchedHooksForComponent = new Set(); -} - -// These are set right before calling the component. -var renderExpirationTime$1 = NoWork; -// The work-in-progress fiber. I've named it differently to distinguish it from -// the work-in-progress hook. -var currentlyRenderingFiber$1 = null; - -// Hooks are stored as a linked list on the fiber's memoizedState field. The -// current hook list is the list that belongs to the current fiber. The -// work-in-progress hook list is a new list that will be added to the -// work-in-progress fiber. -var currentHook = null; -var nextCurrentHook = null; -var firstWorkInProgressHook = null; -var workInProgressHook = null; -var nextWorkInProgressHook = null; - -var remainingExpirationTime = NoWork; -var componentUpdateQueue = null; -var sideEffectTag = 0; - -// Updates scheduled during render will trigger an immediate re-render at the -// end of the current pass. We can't store these updates on the normal queue, -// because if the work is aborted, they should be discarded. Because this is -// a relatively rare case, we also don't want to add an additional field to -// either the hook or queue object types. So we store them in a lazily create -// map of queue -> render-phase updates, which are discarded once the component -// completes without re-rendering. +function mountEventResponder$1( + responder, + responderProps, + fiber, + respondersMap, + rootContainerInstance +) { + var responderState = emptyObject$1; + var getInitialState = responder.getInitialState; -// Whether an update was scheduled during the currently executing render pass. -var didScheduleRenderPhaseUpdate = false; -// Lazily created map of render-phase updates -var renderPhaseUpdates = null; -// Counter to prevent infinite loops. -var numberOfReRenders = 0; -var RE_RENDER_LIMIT = 25; + if (getInitialState !== null) { + responderState = getInitialState(responderProps); + } -// In DEV, this is the name of the currently executing primitive hook -var currentHookNameInDev = null; + var responderInstance = createResponderInstance( + responder, + responderProps, + responderState, + fiber + ); -// In DEV, this list ensures that hooks are called in the same order between renders. -// The list stores the order of hooks used during the initial render (mount). -// Subsequent renders (updates) reference this list. -var hookTypesDev = null; -var hookTypesUpdateIndexDev = -1; + if (!rootContainerInstance) { + var node = fiber; -// In DEV, this tracks whether currently rendering component needs to ignore -// the dependencies for Hooks that need them (e.g. useEffect or useMemo). -// When true, such Hooks will always be "remounted". Only used during hot reload. -var ignorePreviousDependencies = false; + while (node !== null) { + var tag = node.tag; -function mountHookTypesDev() { - { - var hookName = currentHookNameInDev; + if (tag === HostComponent) { + rootContainerInstance = node.stateNode; + break; + } else if (tag === HostRoot) { + rootContainerInstance = node.stateNode.containerInfo; + break; + } - if (hookTypesDev === null) { - hookTypesDev = [hookName]; - } else { - hookTypesDev.push(hookName); + node = node.return; } } -} - -function updateHookTypesDev() { - { - var hookName = currentHookNameInDev; + + mountResponderInstance( + responder, + responderInstance, + responderProps, + responderState, + rootContainerInstance + ); + respondersMap.set(responder, responderInstance); +} + +function updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance +) { + var responder; + var props; + + if (listener) { + responder = listener.responder; + props = listener.props; + } + + if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { + throw Error( + "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()." + ); + } + + var listenerProps = props; + + if (visistedResponders.has(responder)) { + // show warning + { + 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 + ); + } + + return; + } + + visistedResponders.add(responder); + var responderInstance = respondersMap.get(responder); + + if (responderInstance === undefined) { + // Mount (happens in either complete or commit phase) + mountEventResponder$1( + responder, + listenerProps, + fiber, + respondersMap, + rootContainerInstance + ); + } else { + // Update (happens during commit phase only) + responderInstance.props = listenerProps; + responderInstance.fiber = fiber; + } +} + +function updateEventListeners(listeners, fiber, rootContainerInstance) { + var visistedResponders = new Set(); + var dependencies = fiber.dependencies; + + if (listeners != null) { + if (dependencies === null) { + dependencies = fiber.dependencies = { + expirationTime: NoWork, + firstContext: null, + responders: new Map() + }; + } + + var respondersMap = dependencies.responders; + + if (respondersMap === null) { + respondersMap = new Map(); + } + + if (isArray$2(listeners)) { + for (var i = 0, length = listeners.length; i < length; i++) { + var listener = listeners[i]; + updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } else { + updateEventListener( + listeners, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } + + if (dependencies !== null) { + var _respondersMap = dependencies.responders; + + if (_respondersMap !== null) { + // Unmount + var mountedResponders = Array.from(_respondersMap.keys()); + + for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { + var mountedResponder = mountedResponders[_i]; + + if (!visistedResponders.has(mountedResponder)) { + var responderInstance = _respondersMap.get(mountedResponder); + + unmountResponderInstance(responderInstance); + + _respondersMap.delete(mountedResponder); + } + } + } + } +} +function createResponderListener(responder, props) { + var eventResponderListener = { + responder: responder, + props: props + }; + + { + Object.freeze(eventResponderListener); + } + + return eventResponderListener; +} + +var NoEffect$1 = + /* */ + 0; +var UnmountSnapshot = + /* */ + 2; +var UnmountMutation = + /* */ + 4; +var MountMutation = + /* */ + 8; +var UnmountLayout = + /* */ + 16; +var MountLayout = + /* */ + 32; +var MountPassive = + /* */ + 64; +var UnmountPassive = + /* */ + 128; + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var didWarnAboutMismatchedHooksForComponent; + +{ + didWarnAboutMismatchedHooksForComponent = new Set(); +} + +// These are set right before calling the component. +var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from +// the work-in-progress hook. + +var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The +// current hook list is the list that belongs to the current fiber. The +// work-in-progress hook list is a new list that will be added to the +// work-in-progress fiber. + +var currentHook = null; +var nextCurrentHook = null; +var firstWorkInProgressHook = null; +var workInProgressHook = null; +var nextWorkInProgressHook = null; +var remainingExpirationTime = NoWork; +var componentUpdateQueue = null; +var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the +// end of the current pass. We can't store these updates on the normal queue, +// because if the work is aborted, they should be discarded. Because this is +// a relatively rare case, we also don't want to add an additional field to +// either the hook or queue object types. So we store them in a lazily create +// map of queue -> render-phase updates, which are discarded once the component +// completes without re-rendering. +// Whether an update was scheduled during the currently executing render pass. + +var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook + +var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. +// The list stores the order of hooks used during the initial render (mount). +// Subsequent renders (updates) reference this list. + +var hookTypesDev = null; +var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore +// the dependencies for Hooks that need them (e.g. useEffect or useMemo). +// When true, such Hooks will always be "remounted". Only used during hot reload. + +var ignorePreviousDependencies = false; + +function mountHookTypesDev() { + { + var hookName = currentHookNameInDev; + + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } +} + +function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } @@ -10966,29 +11061,26 @@ function checkDepsAreArrayDev(deps) { function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentName(currentlyRenderingFiber$1.type); + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ""; - var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - - var row = i + 1 + ". " + oldHookName; - - // Extra space so second column lines up + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { row += " "; } row += newHookName + "\n"; - table += row; } @@ -11010,15 +11102,11 @@ function warnOnHookMismatchInDev(currentHookName) { } function throwInvalidHookError() { - (function() { - { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) - ); - } - })(); + { + 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." + ); + } } function areHookInputsEqual(nextDeps, prevDeps) { @@ -11039,6 +11127,7 @@ function areHookInputsEqual(nextDeps, prevDeps) { currentHookNameInDev ); } + return false; } @@ -11058,12 +11147,15 @@ function areHookInputsEqual(nextDeps, prevDeps) { ); } } + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (is(nextDeps[i], prevDeps[i])) { + if (is$1(nextDeps[i], prevDeps[i])) { continue; } + return false; } + return true; } @@ -11081,31 +11173,26 @@ function renderWithHooks( { hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: + hookTypesUpdateIndexDev = -1; // Used for hot reloading: + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - // The following should have already been reset + } // The following should have already been reset // currentHook = null; // workInProgressHook = null; - // remainingExpirationTime = NoWork; // componentUpdateQueue = null; - // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; // sideEffectTag = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because nextCurrentHook === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so nextCurrentHook would be null during updates and mounts. + { if (nextCurrentHook !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; @@ -11127,16 +11214,15 @@ function renderWithHooks( do { didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; + { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; - } + } // Start over from the beginning of the list - // Start over from the beginning of the list nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; - currentHook = null; workInProgressHook = null; componentUpdateQueue = null; @@ -11147,20 +11233,16 @@ function renderWithHooks( } ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - children = Component(props, refOrContext); } while (didScheduleRenderPhaseUpdate); renderPhaseUpdates = null; numberOfReRenders = 0; - } - - // We can assume the previous dispatcher is always this one, since we set it + } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; var renderedWork = currentlyRenderingFiber$1; - renderedWork.memoizedState = firstWorkInProgressHook; renderedWork.expirationTime = remainingExpirationTime; renderedWork.updateQueue = componentUpdateQueue; @@ -11168,15 +11250,12 @@ function renderWithHooks( { renderedWork._debugHookTypes = hookTypesDev; - } - - // This check uses currentHook so that it works the same in DEV and prod bundles. + } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -11191,45 +11270,36 @@ function renderWithHooks( remainingExpirationTime = NoWork; componentUpdateQueue = null; - sideEffectTag = 0; - - // These were reset above + sideEffectTag = 0; // These were reset above // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; - (function() { - if (!!didRenderTooFewHooks) { - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) - ); - } - })(); + if (!!didRenderTooFewHooks) { + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } return children; } - function bailoutHooks(current, workInProgress, expirationTime) { workInProgress.updateQueue = current.updateQueue; workInProgress.effectTag &= ~(Passive | Update); + if (current.expirationTime <= expirationTime) { current.expirationTime = NoWork; } } - function resetHooks() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - // This is used to reset the state of this module when a component throws. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws. // It's also called inside mountIndeterminateComponent if we determine the // component is a module-style component. + renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -11239,14 +11309,12 @@ function resetHooks() { { hookTypesDev = null; hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -11255,11 +11323,9 @@ function resetHooks() { function mountWorkInProgressHook() { var hook = { memoizedState: null, - baseState: null, queue: null, baseUpdate: null, - next: null }; @@ -11270,6 +11336,7 @@ function mountWorkInProgressHook() { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } + return workInProgressHook; } @@ -11283,27 +11350,20 @@ function updateWorkInProgressHook() { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - (function() { - if (!(nextCurrentHook !== null)) { - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); - } - })(); - currentHook = nextCurrentHook; + if (!(nextCurrentHook !== null)) { + throw Error("Rendered more hooks than during the previous render."); + } + currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, queue: currentHook.queue, baseUpdate: currentHook.baseUpdate, - next: null }; @@ -11314,8 +11374,10 @@ function updateWorkInProgressHook() { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } + nextCurrentHook = currentHook.next; } + return workInProgressHook; } @@ -11331,12 +11393,14 @@ function basicStateReducer(state, action) { function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); - var initialState = void 0; + var initialState; + if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11345,8 +11409,7 @@ function mountReducer(reducer, initialArg, init) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11356,68 +11419,67 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - (function() { - if (!(queue !== null)) { - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(queue !== null)) { + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + } queue.lastRenderedReducer = reducer; if (numberOfReRenders > 0) { // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. var _dispatch = queue.dispatch; + if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = hook.memoizedState; var update = firstRenderPhaseUpdate; + do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. - var _action = update.action; - newState = reducer(newState, _action); + var action = update.action; + newState = reducer(newState, action); update = update.next; - } while (update !== null); - - // Mark that the fiber performed work, but only if the new state is + } while (update !== null); // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(newState, hook.memoizedState)) { + + if (!is$1(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } - hook.memoizedState = newState; - // Don't persist the state accumulated from the render phase updates to + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. + if (hook.baseUpdate === queue.last) { hook.baseState = newState; } queue.lastRenderedState = newState; - return [newState, _dispatch]; } } + return [hook.memoizedState, _dispatch]; - } + } // The last update in the entire queue + + var last = queue.last; // The last update that is part of the base state. - // The last update in the entire queue - var last = queue.last; - // The last update that is part of the base state. var baseUpdate = hook.baseUpdate; - var baseState = hook.baseState; + var baseState = hook.baseState; // Find the first unprocessed update. + + var first; - // Find the first unprocessed update. - var first = void 0; if (baseUpdate !== null) { if (last !== null) { // For the first update, the queue is a circular linked list where @@ -11425,10 +11487,12 @@ function updateReducer(reducer, initialArg, init) { // the `baseUpdate` is no longer empty, we can unravel the list. last.next = null; } + first = baseUpdate.next; } else { first = last !== null ? last.next : null; } + if (first !== null) { var _newState = baseState; var newBaseState = null; @@ -11436,8 +11500,10 @@ function updateReducer(reducer, initialArg, init) { var prevUpdate = baseUpdate; var _update = first; var didSkip = false; + do { var updateExpirationTime = _update.expirationTime; + if (updateExpirationTime < renderExpirationTime$1) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base @@ -11446,14 +11512,14 @@ function updateReducer(reducer, initialArg, init) { didSkip = true; newBaseUpdate = prevUpdate; newBaseState = _newState; - } - // Update the remaining priority in the queue. + } // Update the remaining priority in the queue. + if (updateExpirationTime > remainingExpirationTime) { remainingExpirationTime = updateExpirationTime; + markUnprocessedUpdateTime(remainingExpirationTime); } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. @@ -11463,18 +11529,18 @@ function updateReducer(reducer, initialArg, init) { markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig - ); + ); // Process this update. - // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the // current reducer, we can use the eagerly computed state. _newState = _update.eagerState; } else { - var _action2 = _update.action; - _newState = reducer(_newState, _action2); + var _action = _update.action; + _newState = reducer(_newState, _action); } } + prevUpdate = _update; _update = _update.next; } while (_update !== null && _update !== first); @@ -11482,18 +11548,16 @@ function updateReducer(reducer, initialArg, init) { if (!didSkip) { newBaseUpdate = prevUpdate; newBaseState = _newState; - } - - // Mark that the fiber performed work, but only if the new state is + } // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(_newState, hook.memoizedState)) { + + if (!is$1(_newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = _newState; hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.lastRenderedState = _newState; } @@ -11503,9 +11567,11 @@ function updateReducer(reducer, initialArg, init) { function mountState(initialState) { var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { initialState = initialState(); } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11514,8 +11580,7 @@ function mountState(initialState) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11535,29 +11600,36 @@ function pushEffect(tag, create, destroy, deps) { // Circular next: null }; + if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); componentUpdateQueue.lastEffect = effect.next = effect; } else { - var _lastEffect = componentUpdateQueue.lastEffect; - if (_lastEffect === null) { + var lastEffect = componentUpdateQueue.lastEffect; + + if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { - var firstEffect = _lastEffect.next; - _lastEffect.next = effect; + var firstEffect = lastEffect.next; + lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } + return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); - var ref = { current: initialValue }; + var ref = { + current: initialValue + }; + { Object.seal(ref); } + hook.memoizedState = ref; return ref; } @@ -11582,8 +11654,10 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; + if (nextDeps !== null) { var prevDeps = prevEffect.deps; + if (areHookInputsEqual(nextDeps, prevDeps)) { pushEffect(NoEffect$1, create, destroy, nextDeps); return; @@ -11602,6 +11676,7 @@ function mountEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return mountEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11617,6 +11692,7 @@ function updateEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return updateEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11636,13 +11712,16 @@ function updateLayoutEffect(create, deps) { function imperativeHandleEffect(create, ref) { if (typeof ref === "function") { var refCallback = ref; + var _inst = create(); + refCallback(_inst); return function() { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; + { !refObject.hasOwnProperty("current") ? warning$1( @@ -11653,7 +11732,9 @@ function imperativeHandleEffect(create, ref) { ) : void 0; } + var _inst2 = create(); + refObject.current = _inst2; return function() { refObject.current = null; @@ -11671,12 +11752,10 @@ function mountImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return mountEffectImpl( Update, UnmountMutation | MountLayout, @@ -11695,12 +11774,10 @@ function updateImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl( Update, UnmountMutation | MountLayout, @@ -11728,14 +11805,17 @@ function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + hook.memoizedState = [callback, nextDeps]; return callback; } @@ -11752,33 +11832,32 @@ function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function dispatchAction(fiber, queue, action) { - (function() { - if (!(numberOfReRenders < RE_RENDER_LIMIT)) { - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) - ); - } - })(); + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } { - !(arguments.length <= 3) + !(typeof arguments[3] !== "function") ? warning$1( false, "State updates from the useState() and useReducer() Hooks don't support the " + @@ -11789,6 +11868,7 @@ function dispatchAction(fiber, queue, action) { } var alternate = fiber.alternate; + if ( fiber === currentlyRenderingFiber$1 || (alternate !== null && alternate === currentlyRenderingFiber$1) @@ -11805,39 +11885,40 @@ function dispatchAction(fiber, queue, action) { eagerState: null, next: null }; + { update.priority = getCurrentPriorityLevel(); } + if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } + lastRenderPhaseUpdate.next = update; } } else { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } - var currentTime = requestCurrentTime(); - var _suspenseConfig = requestCurrentSuspenseConfig(); - var _expirationTime = computeExpirationForFiber( + var suspenseConfig = requestCurrentSuspenseConfig(); + var expirationTime = computeExpirationForFiber( currentTime, fiber, - _suspenseConfig + suspenseConfig ); - var _update2 = { - expirationTime: _expirationTime, - suspenseConfig: _suspenseConfig, + expirationTime: expirationTime, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, @@ -11846,21 +11927,24 @@ function dispatchAction(fiber, queue, action) { { _update2.priority = getCurrentPriorityLevel(); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. - var _last = queue.last; - if (_last === null) { + var last = queue.last; + + if (last === null) { // This is the first update. Create a circular list. _update2.next = _update2; } else { - var first = _last.next; + var first = last.next; + if (first !== null) { // Still circular. _update2.next = first; } - _last.next = _update2; + + last.next = _update2; } + queue.last = _update2; if ( @@ -11870,23 +11954,27 @@ function dispatchAction(fiber, queue, action) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. - var _lastRenderedReducer = queue.lastRenderedReducer; - if (_lastRenderedReducer !== null) { - var prevDispatcher = void 0; + var lastRenderedReducer = queue.lastRenderedReducer; + + if (lastRenderedReducer !== null) { + var prevDispatcher; + { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } + try { var currentState = queue.lastRenderedState; - var _eagerState = _lastRenderedReducer(currentState, action); - // Stash the eagerly computed state, and the reducer used to compute + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. - _update2.eagerReducer = _lastRenderedReducer; - _update2.eagerState = _eagerState; - if (is(_eagerState, currentState)) { + + _update2.eagerReducer = lastRenderedReducer; + _update2.eagerState = eagerState; + + if (is$1(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that @@ -11902,6 +11990,7 @@ function dispatchAction(fiber, queue, action) { } } } + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -11909,13 +11998,13 @@ function dispatchAction(fiber, queue, action) { warnIfNotCurrentlyActingUpdatesInDev(fiber); } } - scheduleWork(fiber, _expirationTime); + + scheduleWork(fiber, expirationTime); } } var ContextOnlyDispatcher = { readContext: readContext, - useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, @@ -11928,7 +12017,6 @@ var ContextOnlyDispatcher = { useDebugValue: throwInvalidHookError, useResponder: throwInvalidHookError }; - var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; @@ -11995,6 +12083,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12006,6 +12095,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12022,6 +12112,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12039,7 +12130,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -12074,6 +12164,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12085,6 +12176,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12101,6 +12193,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12118,7 +12211,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -12153,6 +12245,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -12164,6 +12257,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -12180,6 +12274,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -12197,7 +12292,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -12239,6 +12333,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12251,6 +12346,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12269,6 +12365,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12288,7 +12385,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -12330,6 +12426,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -12342,6 +12439,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -12360,6 +12458,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -12381,10 +12480,9 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }; } -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. -var now$1 = Scheduler.unstable_now; +var now$1 = Scheduler.unstable_now; var commitTime = 0; var profilerStartTime = -1; @@ -12396,6 +12494,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } + commitTime = now$1(); } @@ -12415,6 +12514,7 @@ function stopProfilerTimerIfRunning(fiber) { if (!enableProfilerTimer) { return; } + profilerStartTime = -1; } @@ -12426,15 +12526,17 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } + profilerStartTime = -1; } } -// The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. + var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; @@ -12462,12 +12564,14 @@ function enterHydrationState(fiber) { return true; } -function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) { +function reenterHydrationStateFromDehydratedSuspenseInstance( + fiber, + suspenseInstance +) { if (!supportsHydration) { return false; } - var suspenseInstance = fiber.stateNode; nextHydratableInstance = getNextHydratableSibling(suspenseInstance); popToNextHostParent(fiber); isHydrating = true; @@ -12483,6 +12587,7 @@ function deleteHydratableInstance(returnFiber, instance) { instance ); break; + case HostComponent: didNotHydrateInstance( returnFiber.type, @@ -12497,13 +12602,12 @@ function deleteHydratableInstance(returnFiber, instance) { var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; - childToDelete.effectTag = Deletion; - - // This might seem like it belongs on progressedFirstDeletion. However, + childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However, // these children are not part of the reconciliation list of children. // Even if we abort and rereconcile the children, that will try to hydrate // again and the nodes are still in the host tree so these will be // recreated. + if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; @@ -12513,31 +12617,38 @@ function deleteHydratableInstance(returnFiber, instance) { } function insertNonHydratedInstance(returnFiber, fiber) { - fiber.effectTag |= Placement; + fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement; + { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; + switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableContainerInstance(parentContainer, type, props); break; + case HostText: var text = fiber.pendingProps; didNotFindHydratableContainerTextInstance(parentContainer, text); break; + case SuspenseComponent: didNotFindHydratableContainerSuspenseInstance(parentContainer); break; } + break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; + switch (fiber.tag) { case HostComponent: var _type = fiber.type; @@ -12550,6 +12661,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _props ); break; + case HostText: var _text = fiber.pendingProps; didNotFindHydratableTextInstance( @@ -12559,6 +12671,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _text ); break; + case SuspenseComponent: didNotFindHydratableSuspenseInstance( parentType, @@ -12567,8 +12680,10 @@ function insertNonHydratedInstance(returnFiber, fiber) { ); break; } + break; } + default: return; } @@ -12581,33 +12696,53 @@ function tryHydrate(fiber, nextInstance) { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type, props); + if (instance !== null) { fiber.stateNode = instance; return true; } + return false; } + case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); + if (textInstance !== null) { fiber.stateNode = textInstance; return true; } + return false; } + case SuspenseComponent: { if (enableSuspenseServerRenderer) { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); + if (suspenseInstance !== null) { - // Downgrade the tag to a dehydrated component until we've hydrated it. - fiber.tag = DehydratedSuspenseComponent; - fiber.stateNode = suspenseInstance; + var suspenseState = { + dehydrated: suspenseInstance, + retryTime: Never + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. + + var dehydratedFragment = createFiberFromDehydratedFragment( + suspenseInstance + ); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; return true; } } + return false; } + default: return false; } @@ -12617,7 +12752,9 @@ function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } + var nextInstance = nextHydratableInstance; + if (!nextInstance) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); @@ -12625,25 +12762,29 @@ function tryToClaimNextHydratableInstance(fiber) { hydrationParentFiber = fiber; return; } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; - } - // We matched the next one, we'll now assume that the first one was + } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. + deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance); } + hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(nextInstance); } @@ -12654,15 +12795,11 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var instance = fiber.stateNode; @@ -12673,38 +12810,37 @@ function prepareToHydrateHostInstance( rootContainerInstance, hostContext, fiber - ); - // TODO: Type this specific to this type of component. - fiber.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. + if (updatePayload !== null) { return true; } + return false; } function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); + { if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { @@ -12716,6 +12852,7 @@ function prepareToHydrateHostTextInstance(fiber) { ); break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; @@ -12733,46 +12870,66 @@ function prepareToHydrateHostTextInstance(fiber) { } } } + return shouldUpdate; } -function skipPastDehydratedSuspenseInstance(fiber) { +function prepareToHydrateHostSuspenseInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } - var suspenseInstance = fiber.stateNode; - (function() { - if (!suspenseInstance) { - throw ReactError( - Error( - "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." - ) + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + hydrateSuspenseInstance(suspenseInstance, fiber); +} + +function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + { + throw Error( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." ); } - })(); - nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( - suspenseInstance - ); + } + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; + while ( parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && - parent.tag !== DehydratedSuspenseComponent + parent.tag !== SuspenseComponent ) { parent = parent.return; } + hydrationParentFiber = parent; } @@ -12780,11 +12937,13 @@ function popHydrationState(fiber) { if (!supportsHydration) { return false; } + if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } + if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our @@ -12794,13 +12953,12 @@ function popHydrationState(fiber) { return false; } - var type = fiber.type; - - // If we have any remaining hydratable nodes, we need to delete them now. + var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. // TODO: Better heuristic. + if ( fiber.tag !== HostComponent || (type !== "head" && @@ -12808,6 +12966,7 @@ function popHydrationState(fiber) { !shouldSetTextContent(type, fiber.memoizedProps)) ) { var nextInstance = nextHydratableInstance; + while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); @@ -12815,9 +12974,15 @@ function popHydrationState(fiber) { } popToNextHostParent(fiber); - nextHydratableInstance = hydrationParentFiber - ? getNextHydratableSibling(fiber.stateNode) - : null; + + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber + ? getNextHydratableSibling(fiber.stateNode) + : null; + } + return true; } @@ -12832,19 +12997,17 @@ function resetHydrationState() { } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - -var didWarnAboutBadClass = void 0; -var didWarnAboutModulePatternComponent = void 0; -var didWarnAboutContextTypeOnFunctionComponent = void 0; -var didWarnAboutGetDerivedStateOnFunctionComponent = void 0; -var didWarnAboutFunctionRefs = void 0; -var didWarnAboutReassigningProps = void 0; -var didWarnAboutMaxDuration = void 0; -var didWarnAboutRevealOrder = void 0; -var didWarnAboutTailOptions = void 0; -var didWarnAboutDefaultPropsOnFunctionComponent = void 0; +var didWarnAboutBadClass; +var didWarnAboutModulePatternComponent; +var didWarnAboutContextTypeOnFunctionComponent; +var didWarnAboutGetDerivedStateOnFunctionComponent; +var didWarnAboutFunctionRefs; +var didWarnAboutReassigningProps; +var didWarnAboutMaxDuration; +var didWarnAboutRevealOrder; +var didWarnAboutTailOptions; +var didWarnAboutDefaultPropsOnFunctionComponent; { didWarnAboutBadClass = {}; @@ -12880,7 +13043,6 @@ function reconcileChildren( // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers( @@ -12911,11 +13073,11 @@ function forceUnmountCurrentAndReconcile( current$$1.child, null, renderExpirationTime - ); - // In the second pass, we mount the new children. The trick here is that we + ); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their their // identity matches. + workInProgress.child = reconcileChildFibers( workInProgress, null, @@ -12934,12 +13096,12 @@ function updateForwardRef( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12953,11 +13115,11 @@ function updateForwardRef( } var render = Component.render; - var ref = workInProgress.ref; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - // The rest is a fork of updateFunctionComponent - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12969,6 +13131,7 @@ function updateForwardRef( ref, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12986,6 +13149,7 @@ function updateForwardRef( ); } } + setCurrentPhase(null); } @@ -12996,9 +13160,8 @@ function updateForwardRef( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -13019,24 +13182,27 @@ function updateMemoComponent( ) { if (current$$1 === null) { var type = Component.type; + if ( isSimpleFunctionComponent(type) && - Component.compare === null && - // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined ) { var resolvedType = type; + { resolvedType = resolveFunctionForHotReloading(type); - } - // If this is a plain function component without default props, + } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. + workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; + { validateFunctionComponentInDev(workInProgress, type); } + return updateSimpleMemoComponent( current$$1, workInProgress, @@ -13046,8 +13212,10 @@ function updateMemoComponent( renderExpirationTime ); } + { var innerPropTypes = type.propTypes; + if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -13060,6 +13228,7 @@ function updateMemoComponent( ); } } + var child = createFiberFromTypeAndProps( Component.type, null, @@ -13073,9 +13242,11 @@ function updateMemoComponent( workInProgress.child = child; return child; } + { var _type = Component.type; var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -13088,14 +13259,17 @@ function updateMemoComponent( ); } } + var currentChild = current$$1.child; // This is always exactly one child + if (updateExpirationTime < renderExpirationTime) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; - // Default to shallow comparison + var prevProps = currentChild.memoizedProps; // Default to shallow comparison + var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; + if ( compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref @@ -13106,8 +13280,8 @@ function updateMemoComponent( renderExpirationTime ); } - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; var newChild = createWorkInProgress( currentChild, @@ -13131,19 +13305,21 @@ function updateSimpleMemoComponent( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. outerMemoType = refineResolvedLazyComponent(outerMemoType); } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13152,19 +13328,20 @@ function updateSimpleMemoComponent( getComponentName(outerMemoType), getCurrentFiberStackInDev ); - } - // Inner propTypes will be validated in the function component path. + } // Inner propTypes will be validated in the function component path. } } + if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; + if ( shallowEqual(prevProps, nextProps) && - current$$1.ref === workInProgress.ref && - // Prevent bailout if the implementation changed due to hot reload: + current$$1.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload: workInProgress.type === current$$1.type ) { didReceiveUpdate = false; + if (updateExpirationTime < renderExpirationTime) { return bailoutOnAlreadyFinishedWork( current$$1, @@ -13174,6 +13351,7 @@ function updateSimpleMemoComponent( } } } + return updateFunctionComponent( current$$1, workInProgress, @@ -13209,6 +13387,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren( @@ -13222,6 +13401,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { function markRef(current$$1, workInProgress) { var ref = workInProgress.ref; + if ( (current$$1 === null && ref !== null) || (current$$1 !== null && current$$1.ref !== ref) @@ -13243,6 +13423,7 @@ function updateFunctionComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -13255,14 +13436,16 @@ function updateFunctionComponent( } } - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -13274,6 +13457,7 @@ function updateFunctionComponent( context, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13291,6 +13475,7 @@ function updateFunctionComponent( ); } } + setCurrentPhase(null); } @@ -13301,9 +13486,8 @@ function updateFunctionComponent( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -13326,6 +13510,7 @@ function updateClassComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -13336,22 +13521,23 @@ function updateClassComponent( ); } } - } - - // Push context providers early to prevent context stack mismatches. + } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); var instance = workInProgress.stateNode; - var shouldUpdate = void 0; + var shouldUpdate; + if (instance === null) { if (current$$1 !== null) { // An class component without an instance only mounts if it suspended @@ -13359,11 +13545,11 @@ function updateClassComponent( // tree it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current$$1.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; - } - // In the initial pass we might need to construct the instance. + } // In the initial pass we might need to construct the instance. + constructClassInstance( workInProgress, Component, @@ -13394,6 +13580,7 @@ function updateClassComponent( renderExpirationTime ); } + var nextUnitOfWork = finishClassComponent( current$$1, workInProgress, @@ -13402,8 +13589,10 @@ function updateClassComponent( hasContext, renderExpirationTime ); + { var inst = workInProgress.stateNode; + if (inst.props !== nextProps) { !didWarnAboutReassigningProps ? warning$1( @@ -13416,6 +13605,7 @@ function updateClassComponent( didWarnAboutReassigningProps = true; } } + return nextUnitOfWork; } @@ -13429,7 +13619,6 @@ function finishClassComponent( ) { // Refs should update even if shouldComponentUpdate returns false markRef(current$$1, workInProgress); - var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect; if (!shouldUpdate && !didCaptureError) { @@ -13445,11 +13634,11 @@ function finishClassComponent( ); } - var instance = workInProgress.stateNode; + var instance = workInProgress.stateNode; // Rerender - // Rerender ReactCurrentOwner$3.current = workInProgress; - var nextChildren = void 0; + var nextChildren; + if ( didCaptureError && typeof Component.getDerivedStateFromError !== "function" @@ -13468,6 +13657,7 @@ function finishClassComponent( { setCurrentPhase("render"); nextChildren = instance.render(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13475,12 +13665,13 @@ function finishClassComponent( ) { instance.render(); } + setCurrentPhase(null); } - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; + if (current$$1 !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children @@ -13499,13 +13690,11 @@ function finishClassComponent( nextChildren, renderExpirationTime ); - } - - // Memoize state using the values we just used to render. + } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. - workInProgress.memoizedState = instance.state; - // The context might have changed so we need to recalculate it. + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } @@ -13515,6 +13704,7 @@ function finishClassComponent( function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; + if (root.pendingContext) { pushTopLevelContextObject( workInProgress, @@ -13525,21 +13715,20 @@ function pushHostRootContext(workInProgress) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } + pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - (function() { - if (!(updateQueue !== null)) { - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(updateQueue !== null)) { + 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." + ); + } + var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState !== null ? prevState.element : null; @@ -13550,10 +13739,11 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { null, renderExpirationTime ); - var nextState = workInProgress.memoizedState; - // Caution: React DevTools currently depends on this property + var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property // being called "element". + var nextChildren = nextState.element; + if (nextChildren === prevChildren) { // If the state is the same as before, that's a bailout because we had // no work that expires at this time. @@ -13564,32 +13754,33 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + var root = workInProgress.stateNode; - if ( - (current$$1 === null || current$$1.child === null) && - root.hydrate && - enterHydrationState(workInProgress) - ) { + + if (root.hydrate && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. - - // This is a bit of a hack. We track the host root as a placement to - // know that we're currently in a mounting state. That way isMounted - // works as expected. We must reset this before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag |= Placement; - - // Ensure that children mount into this root without tracking - // side-effects. This ensures that we don't store Placement effects on - // nodes that will be hydrated. - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + workInProgress.child = child; + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag = (node.effectTag & ~Placement) | Hydrating; + node = node.sibling; + } } else { // Otherwise reset hydration state in case we aborted and resumed another // root. @@ -13601,6 +13792,7 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { ); resetHydrationState(); } + return workInProgress.child; } @@ -13614,7 +13806,6 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current$$1 !== null ? current$$1.memoizedProps : null; - var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); @@ -13630,9 +13821,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { workInProgress.effectTag |= ContentReset; } - markRef(current$$1, workInProgress); + markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden. - // Check the host config to see if the children are offscreen/hidden. if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -13640,8 +13830,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } @@ -13658,9 +13848,9 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { function updateHostText(current$$1, workInProgress) { if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); - } - // Nothing to do here. This is terminal. We'll do the completion step + } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. + return null; } @@ -13677,22 +13867,23 @@ function mountLazyComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } - var props = workInProgress.pendingProps; - // We can't start a User Timing measurement with correct label yet. + var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet. // Cancel and resume right after we know the tag. + cancelWorkTimer(workInProgress); - var Component = readLazyComponentType(elementType); - // Store the unwrapped component in the type. + var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type. + workInProgress.type = Component; var resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); startWorkTimer(workInProgress); var resolvedProps = resolveDefaultProps(Component, props); - var child = void 0; + var child; + switch (resolvedTag) { case FunctionComponent: { { @@ -13701,6 +13892,7 @@ function mountLazyComponent( Component ); } + child = updateFunctionComponent( null, workInProgress, @@ -13710,12 +13902,14 @@ function mountLazyComponent( ); break; } + case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading( Component ); } + child = updateClassComponent( null, workInProgress, @@ -13725,12 +13919,14 @@ function mountLazyComponent( ); break; } + case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading( Component ); } + child = updateForwardRef( null, workInProgress, @@ -13740,10 +13936,12 @@ function mountLazyComponent( ); break; } + case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13755,6 +13953,7 @@ function mountLazyComponent( } } } + child = updateMemoComponent( null, workInProgress, @@ -13765,8 +13964,10 @@ function mountLazyComponent( ); break; } + default: { var hint = ""; + { if ( Component !== null && @@ -13775,24 +13976,21 @@ function mountLazyComponent( ) { hint = " Did you wrap a component in React.lazy() more than once?"; } - } - // This message intentionally doesn't mention ForwardRef or MemoComponent + } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - (function() { - { - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." + - hint - ) - ); - } - })(); + + { + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } } } + return child; } @@ -13809,28 +14007,26 @@ function mountIncompleteClassComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect - workInProgress.effectTag |= Placement; - } - - // Promote the fiber to a class and try rendering again. - workInProgress.tag = ClassComponent; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - // The rest of this function is a fork of `updateClassComponent` + workInProgress.effectTag |= Placement; + } // Promote the fiber to a class and try rendering again. + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); constructClassInstance( workInProgress, Component, @@ -13843,7 +14039,6 @@ function mountIncompleteClassComponent( nextProps, renderExpirationTime ); - return finishClassComponent( null, workInProgress, @@ -13866,20 +14061,21 @@ function mountIndeterminateComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderExpirationTime); - var value = void 0; + var value; { if ( @@ -13913,8 +14109,8 @@ function mountIndeterminateComponent( context, renderExpirationTime ); - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; if ( @@ -13925,6 +14121,7 @@ function mountIndeterminateComponent( ) { { var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { warningWithoutStack$1( false, @@ -13939,18 +14136,16 @@ function mountIndeterminateComponent( ); didWarnAboutModulePatternComponent[_componentName] = true; } - } + } // Proceed under the assumption that this is a class instance - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - // Throw out any hooks that were used. - resetHooks(); - - // Push context providers early to prevent context stack mismatches. + resetHooks(); // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. + var hasContext = false; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); @@ -13960,8 +14155,8 @@ function mountIndeterminateComponent( workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - var getDerivedStateFromProps = Component.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -13984,6 +14179,7 @@ function mountIndeterminateComponent( } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { if (disableLegacyContext && Component.contextTypes) { warningWithoutStack$1( @@ -14012,10 +14208,13 @@ function mountIndeterminateComponent( } } } + reconcileChildren(null, workInProgress, value, renderExpirationTime); + { validateFunctionComponentInDev(workInProgress, Component); } + return workInProgress.child; } } @@ -14030,18 +14229,22 @@ function validateFunctionComponentInDev(workInProgress, Component) { ) : void 0; } + if (workInProgress.ref !== null) { var info = ""; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } var warningKey = ownerName || workInProgress._debugID || ""; var debugSource = workInProgress._debugSource; + if (debugSource) { warningKey = debugSource.fileName + ":" + debugSource.lineNumber; } + if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; warning$1( @@ -14101,8 +14304,10 @@ function validateFunctionComponentInDev(workInProgress, Component) { } } -// TODO: This is now an empty object. Should we just make it a boolean? -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { + dehydrated: null, + retryTime: NoWork +}; function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) { // If the context is telling us that we should show a fallback, and we're not @@ -14119,9 +14324,8 @@ function updateSuspenseComponent( renderExpirationTime ) { var mode = workInProgress.mode; - var nextProps = workInProgress.pendingProps; + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.effectTag |= DidCapture; @@ -14129,17 +14333,15 @@ function updateSuspenseComponent( } var suspenseContext = suspenseStackCursor.current; - - var nextState = null; var nextDidTimeout = false; + var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect; if ( - (workInProgress.effectTag & DidCapture) !== NoEffect || + didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) ) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. - nextState = SUSPENDED_MARKER; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } else { @@ -14163,7 +14365,6 @@ function updateSuspenseComponent( } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); { @@ -14177,9 +14378,7 @@ function updateSuspenseComponent( ); } } - } - - // This next part is a bit confusing. If the children timeout, we switch to + } // This next part is a bit confusing. If the children timeout, we switch to // showing the fallback children in place of the "primary" children. // However, we don't want to delete the primary children because then their // state will be lost (both the React state and the host state, e.g. @@ -14201,35 +14400,30 @@ function updateSuspenseComponent( // custom reconciliation logic to preserve the state of the primary // children. It's essentially a very basic form of re-parenting. - // `child` points to the child fiber. In the normal case, this is the first - // fiber of the primary children set. In the timed-out case, it's a - // a fragment fiber containing the primary children. - var child = void 0; - // `next` points to the next fiber React should render. In the normal case, - // it's the same as `child`: the first fiber of the primary children set. - // In the timed-out case, it's a fragment fiber containing the *fallback* - // children -- we skip over the primary children entirely. - var next = void 0; if (current$$1 === null) { - if (enableSuspenseServerRenderer) { - // If we're currently hydrating, try to hydrate this boundary. - // But only if this has a fallback. - if (nextProps.fallback !== undefined) { - tryToClaimNextHydratableInstance(workInProgress); - // This could've changed the tag if this was a dehydrated suspense component. - if (workInProgress.tag === DehydratedSuspenseComponent) { - popSuspenseContext(workInProgress); - return updateDehydratedSuspenseComponent( - null, - workInProgress, - renderExpirationTime - ); + // If we're currently hydrating, try to hydrate this boundary. + // But only if this has a fallback. + if (nextProps.fallback !== undefined) { + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. + + if (enableSuspenseServerRenderer) { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent( + workInProgress, + dehydrated, + renderExpirationTime + ); + } } } - } - - // This is the initial mount. This branch is pretty simple because there's + } // This is the initial mount. This branch is pretty simple because there's // no previous state that needs to be preserved. + if (nextDidTimeout) { // Mount separate fragments for primary and fallback children. var nextFallbackChildren = nextProps.fallback; @@ -14243,6 +14437,7 @@ function updateSuspenseComponent( if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var progressedState = workInProgress.memoizedState; var progressedPrimaryChild = progressedState !== null @@ -14250,6 +14445,7 @@ function updateSuspenseComponent( : workInProgress.child; primaryChildFragment.child = progressedPrimaryChild; var progressedChild = progressedPrimaryChild; + while (progressedChild !== null) { progressedChild.return = primaryChildFragment; progressedChild = progressedChild.sibling; @@ -14263,85 +14459,192 @@ function updateSuspenseComponent( null ); fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - child = primaryChildFragment; - // Skip the primary children, and continue working on the + primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the // fallback children. - next = fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; } else { // Mount the primary children without an intermediate fragment fiber. var nextPrimaryChildren = nextProps.children; - child = next = mountChildFibers( + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( workInProgress, null, nextPrimaryChildren, renderExpirationTime - ); + )); } } else { // This is an update. This branch is more complicated because we need to // ensure the state of the primary children is preserved. var prevState = current$$1.memoizedState; - var prevDidTimeout = prevState !== null; - if (prevDidTimeout) { - // The current tree already timed out. That means each child set is + + if (prevState !== null) { + if (enableSuspenseServerRenderer) { + var _dehydrated = prevState.dehydrated; + + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent( + current$$1, + workInProgress, + _dehydrated, + prevState, + renderExpirationTime + ); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. + + workInProgress.effectTag |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. Wrap the children + // in a fragment fiber to keep them separate from the fallback + // children. + var _nextFallbackChildren = nextProps.fallback; + + var _primaryChildFragment = createFiberFromFragment( + // It shouldn't matter what the pending props are because we aren't + // going to render this fragment. + null, + mode, + NoWork, + null + ); + + _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child + // that we're not going to hydrate. + + _primaryChildFragment.child = null; + + if ((workInProgress.mode & BatchedMode) === NoMode) { + // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. + var _progressedChild = (_primaryChildFragment.child = + workInProgress.child); + + while (_progressedChild !== null) { + _progressedChild.return = _primaryChildFragment; + _progressedChild = _progressedChild.sibling; + } + } else { + // We will have dropped the effect list which contains the deletion. + // We need to reconcile to delete the current child. + reconcileChildFibers( + workInProgress, + current$$1.child, + null, + renderExpirationTime + ); + } // Because primaryChildFragment is a new fiber that we're inserting as the + // parent of a new tree, we need to set its treeBaseDuration. + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // treeBaseDuration is the sum of all the child tree base durations. + var treeBaseDuration = 0; + var hiddenChild = _primaryChildFragment.child; + + while (hiddenChild !== null) { + treeBaseDuration += hiddenChild.treeBaseDuration; + hiddenChild = hiddenChild.sibling; + } + + _primaryChildFragment.treeBaseDuration = treeBaseDuration; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment = createFiberFromFragment( + _nextFallbackChildren, + mode, + renderExpirationTime, + null + ); + + _fallbackChildFragment.return = workInProgress; + _primaryChildFragment.sibling = _fallbackChildFragment; + _fallbackChildFragment.effectTag |= Placement; + _primaryChildFragment.childExpirationTime = NoWork; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the + // fallback children. + + return _fallbackChildFragment; + } + } + } // The current tree already timed out. That means each child set is + // wrapped in a fragment fiber. + var currentPrimaryChildFragment = current$$1.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + if (nextDidTimeout) { // Still timed out. Reuse the current primary children by cloning // its fragment. We're going to skip over these entirely. - var _nextFallbackChildren = nextProps.fallback; - var _primaryChildFragment = createWorkInProgress( + var _nextFallbackChildren2 = nextProps.fallback; + + var _primaryChildFragment2 = createWorkInProgress( currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork ); - _primaryChildFragment.return = workInProgress; + + _primaryChildFragment2.return = workInProgress; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState = workInProgress.memoizedState; + var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child; + if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) { - _primaryChildFragment.child = _progressedPrimaryChild; - var _progressedChild = _progressedPrimaryChild; - while (_progressedChild !== null) { - _progressedChild.return = _primaryChildFragment; - _progressedChild = _progressedChild.sibling; + _primaryChildFragment2.child = _progressedPrimaryChild; + var _progressedChild2 = _progressedPrimaryChild; + + while (_progressedChild2 !== null) { + _progressedChild2.return = _primaryChildFragment2; + _progressedChild2 = _progressedChild2.sibling; } } - } - - // Because primaryChildFragment is a new fiber that we're inserting as the + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var treeBaseDuration = 0; - var hiddenChild = _primaryChildFragment.child; - while (hiddenChild !== null) { - treeBaseDuration += hiddenChild.treeBaseDuration; - hiddenChild = hiddenChild.sibling; + var _treeBaseDuration = 0; + var _hiddenChild = _primaryChildFragment2.child; + + while (_hiddenChild !== null) { + _treeBaseDuration += _hiddenChild.treeBaseDuration; + _hiddenChild = _hiddenChild.sibling; } - _primaryChildFragment.treeBaseDuration = treeBaseDuration; - } - // Clone the fallback child fragment, too. These we'll continue + _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; + } // Clone the fallback child fragment, too. These we'll continue // working on. - var _fallbackChildFragment = createWorkInProgress( + + var _fallbackChildFragment2 = createWorkInProgress( currentFallbackChildFragment, - _nextFallbackChildren, + _nextFallbackChildren2, currentFallbackChildFragment.expirationTime ); - _fallbackChildFragment.return = workInProgress; - _primaryChildFragment.sibling = _fallbackChildFragment; - child = _primaryChildFragment; - _primaryChildFragment.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment2.return = workInProgress; + _primaryChildFragment2.sibling = _fallbackChildFragment2; + _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment2; + return _fallbackChildFragment2; } else { // No longer suspended. Switch back to showing the primary children, // and remove the intermediate fragment fiber. @@ -14352,26 +14655,27 @@ function updateSuspenseComponent( currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime - ); - - // If this render doesn't suspend, we need to delete the fallback + ); // If this render doesn't suspend, we need to delete the fallback // children. Wait until the complete phase, after we've confirmed the // fallback is no longer needed. // TODO: Would it be better to store the fallback fragment on // the stateNode? - // Continue rendering the children, like we normally do. - child = next = primaryChild; + + workInProgress.memoizedState = null; + return (workInProgress.child = primaryChild); } } else { // The current tree has not already timed out. That means the primary // children are not wrapped in a fragment fiber. var _currentPrimaryChild = current$$1.child; + if (nextDidTimeout) { // Timed out. Wrap the children in a fragment fiber to keep them // separate from the fallback children. - var _nextFallbackChildren2 = nextProps.fallback; - var _primaryChildFragment2 = createFiberFromFragment( + var _nextFallbackChildren3 = nextProps.fallback; + + var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't // going to render this fragment. null, @@ -14379,78 +14683,80 @@ function updateSuspenseComponent( NoWork, null ); - _primaryChildFragment2.return = workInProgress; - _primaryChildFragment2.child = _currentPrimaryChild; - if (_currentPrimaryChild !== null) { - _currentPrimaryChild.return = _primaryChildFragment2; - } - // Even though we're creating a new fiber, there are no new children, + _primaryChildFragment3.return = workInProgress; + _primaryChildFragment3.child = _currentPrimaryChild; + + if (_currentPrimaryChild !== null) { + _currentPrimaryChild.return = _primaryChildFragment3; + } // Even though we're creating a new fiber, there are no new children, // because we're reusing an already mounted tree. So we don't need to // schedule a placement. // primaryChildFragment.effectTag |= Placement; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState2 = workInProgress.memoizedState; + var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child; - _primaryChildFragment2.child = _progressedPrimaryChild2; - var _progressedChild2 = _progressedPrimaryChild2; - while (_progressedChild2 !== null) { - _progressedChild2.return = _primaryChildFragment2; - _progressedChild2 = _progressedChild2.sibling; - } - } - // Because primaryChildFragment is a new fiber that we're inserting as the + _primaryChildFragment3.child = _progressedPrimaryChild2; + var _progressedChild3 = _progressedPrimaryChild2; + + while (_progressedChild3 !== null) { + _progressedChild3.return = _primaryChildFragment3; + _progressedChild3 = _progressedChild3.sibling; + } + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var _treeBaseDuration = 0; - var _hiddenChild = _primaryChildFragment2.child; - while (_hiddenChild !== null) { - _treeBaseDuration += _hiddenChild.treeBaseDuration; - _hiddenChild = _hiddenChild.sibling; + var _treeBaseDuration2 = 0; + var _hiddenChild2 = _primaryChildFragment3.child; + + while (_hiddenChild2 !== null) { + _treeBaseDuration2 += _hiddenChild2.treeBaseDuration; + _hiddenChild2 = _hiddenChild2.sibling; } - _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; - } - // Create a fragment from the fallback children, too. - var _fallbackChildFragment2 = createFiberFromFragment( - _nextFallbackChildren2, + _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment3 = createFiberFromFragment( + _nextFallbackChildren3, mode, renderExpirationTime, null ); - _fallbackChildFragment2.return = workInProgress; - _primaryChildFragment2.sibling = _fallbackChildFragment2; - _fallbackChildFragment2.effectTag |= Placement; - child = _primaryChildFragment2; - _primaryChildFragment2.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment3.return = workInProgress; + _primaryChildFragment3.sibling = _fallbackChildFragment3; + _fallbackChildFragment3.effectTag |= Placement; + _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment2; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment3; + return _fallbackChildFragment3; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. + workInProgress.memoizedState = null; var _nextPrimaryChildren2 = nextProps.children; - next = child = reconcileChildFibers( + return (workInProgress.child = reconcileChildFibers( workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime - ); + )); } } - workInProgress.stateNode = current$$1.stateNode; } - - workInProgress.memoizedState = nextState; - workInProgress.child = child; - return next; } function retrySuspenseComponentWithoutHydrating( @@ -14458,90 +14764,95 @@ function retrySuspenseComponentWithoutHydrating( workInProgress, renderExpirationTime ) { - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; + // We're now not suspended nor dehydrated. + workInProgress.memoizedState = null; // Retry with the full children. - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - (function() { - if (!(returnFiber !== null)) { - throw ReactError( - Error( - "Suspense boundaries are never on the root. This is probably a bug in React." - ) - ); - } - })(); - var last = returnFiber.lastEffect; - if (last !== null) { - last.nextEffect = current$$1; - returnFiber.lastEffect = current$$1; - } else { - returnFiber.firstEffect = returnFiber.lastEffect = current$$1; - } - current$$1.nextEffect = null; - current$$1.effectTag = Deletion; - - popSuspenseContext(workInProgress); + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and + // that the old child gets a Deletion effect. + // We could also call forceUnmountCurrentAndReconcile. - // Upgrade this work in progress to a real Suspense component. - workInProgress.tag = SuspenseComponent; - workInProgress.stateNode = null; - workInProgress.memoizedState = null; - // This is now an insertion. - workInProgress.effectTag |= Placement; - // Retry as a real Suspense component. - return updateSuspenseComponent(null, workInProgress, renderExpirationTime); + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; } -function updateDehydratedSuspenseComponent( - current$$1, +function mountDehydratedSuspenseComponent( workInProgress, + suspenseInstance, renderExpirationTime ) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - var suspenseInstance = workInProgress.stateNode; - if (current$$1 === null) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - var serverDisplayTime = requestCurrentTime(); - // Schedule a normal pri update to render this content. - workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.expirationTime = Never; + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & BatchedMode) === NoMode) { + { + warning$1( + false, + "Cannot hydrate Suspense in legacy mode. Switch from " + + "ReactDOM.hydrate(element, container) to " + + "ReactDOM.unstable_createSyncRoot(container, { hydrate: true })" + + ".render(element) or remove the Suspense components from " + + "the server rendered components." + ); } - return null; - } - if ((workInProgress.effectTag & DidCapture) !== NoEffect) { - // Something suspended. Leave the existing children in place. - // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far? - workInProgress.child = null; - return null; + workInProgress.expirationTime = Sync; + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content. + + var newExpirationTime = computeAsyncExpiration(serverDisplayTime); + + if (enableSchedulerTracing) { + markSpawnedWork(newExpirationTime); + } + + workInProgress.expirationTime = newExpirationTime; + } else { + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.expirationTime = Never; + + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } } + return null; +} + +function updateDehydratedSuspenseComponent( + current$$1, + workInProgress, + suspenseInstance, + suspenseState, + renderExpirationTime +) { // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); + if ((workInProgress.mode & BatchedMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime + ); + } + if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the @@ -14551,18 +14862,38 @@ function updateDehydratedSuspenseComponent( workInProgress, renderExpirationTime ); - } - // We use childExpirationTime to indicate that a child might depend on context, so if + } // We use childExpirationTime to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. + var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime; + if (didReceiveUpdate || hasContextChanged$$1) { // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using an earlier expiration time but - // during this render we can't. Instead, we're going to delete the whole subtree and - // instead inject a new real Suspense boundary to take its place, which may render content - // or fallback. The real Suspense boundary will suspend for a while so we have some time - // to ensure it can produce real content, but all state and pending events will be lost. + // hydrate it. We might still be able to hydrate it using an earlier expiration time, if + // we are rendering at lower expiration than sync. + if (renderExpirationTime < Sync) { + if (suspenseState.retryTime <= renderExpirationTime) { + // This render is even higher pri than we've seen before, let's try again + // at even higher pri. + var attemptHydrationAtExpirationTime = renderExpirationTime + 1; + suspenseState.retryTime = attemptHydrationAtExpirationTime; + scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render. + } else { + // We have already tried to ping at a higher priority than we're rendering with + // so if we got here, we must have failed to hydrate at those levels. We must + // now give up. Instead, we're going to delete the whole subtree and instead inject + // a new real Suspense boundary to take its place, which may render content + // or fallback. This might suspend for a while and if it does we might still have + // an opportunity to hydrate before this pass commits. + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. + + renderDidSuspendDelayIfPossible(); return retrySuspenseComponentWithoutHydrating( current$$1, workInProgress, @@ -14578,30 +14909,61 @@ function updateDehydratedSuspenseComponent( // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). - workInProgress.effectTag |= DidCapture; - // Leave the children in place. I.e. empty. - workInProgress.child = null; - // Register a callback to retry this boundary once the server has sent the result. + workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. + + workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result. + registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryDehydratedSuspenseBoundary.bind(null, current$$1) ); return null; } else { // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress); + reenterHydrationStateFromDehydratedSuspenseInstance( + workInProgress, + suspenseInstance + ); var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag |= Hydrating; + node = node.sibling; + } + + workInProgress.child = child; return workInProgress.child; } } +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + if (fiber.expirationTime < renderExpirationTime) { + fiber.expirationTime = renderExpirationTime; + } + + var alternate = fiber.alternate; + + if (alternate !== null && alternate.expirationTime < renderExpirationTime) { + alternate.expirationTime = renderExpirationTime; + } + + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); +} + function propagateSuspenseContextChange( workInProgress, firstChild, @@ -14611,36 +14973,39 @@ function propagateSuspenseContextChange( // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - if (node.expirationTime < renderExpirationTime) { - node.expirationTime = renderExpirationTime; - } - var alternate = node.alternate; - if ( - alternate !== null && - alternate.expirationTime < renderExpirationTime - ) { - alternate.expirationTime = renderExpirationTime; - } - scheduleWorkOnParentPath(node.return, renderExpirationTime); - } + scheduleWorkOnFiber(node, renderExpirationTime); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleWorkOnFiber(node, renderExpirationTime); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -14656,14 +15021,17 @@ function findLastContentRow(firstChild) { // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } + row = row.sibling; } + return lastContentRow; } @@ -14677,6 +15045,7 @@ function validateRevealOrder(revealOrder) { !didWarnAboutRevealOrder[revealOrder] ) { didWarnAboutRevealOrder[revealOrder] = true; + if (typeof revealOrder === "string") { switch (revealOrder.toLowerCase()) { case "together": @@ -14691,6 +15060,7 @@ function validateRevealOrder(revealOrder) { ); break; } + case "forward": case "backward": { warning$1( @@ -14702,6 +15072,7 @@ function validateRevealOrder(revealOrder) { ); break; } + default: warning$1( false, @@ -14752,6 +15123,7 @@ function validateSuspenseListNestedChild(childSlot, index) { { var isArray = Array.isArray(childSlot); var isIterable = !isArray && typeof getIteratorFn(childSlot) === "function"; + if (isArray || isIterable) { var type = isArray ? "array" : "iterable"; warning$1( @@ -14768,6 +15140,7 @@ function validateSuspenseListNestedChild(childSlot, index) { return false; } } + return true; } @@ -14787,15 +15160,19 @@ function validateSuspenseListChildren(children, revealOrder) { } } else { var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { var childrenIterator = iteratorFn.call(children); + if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; + for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } + _i++; } } @@ -14818,9 +15195,11 @@ function initSuspenseListRenderState( isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; + if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, @@ -14828,7 +15207,8 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }; } else { // We can reuse the existing object from previous renders. @@ -14838,16 +15218,16 @@ function initSuspenseListRenderState( renderState.tail = tail; renderState.tailExpiration = 0; renderState.tailMode = tailMode; + renderState.lastEffect = lastEffectBeforeRendering; } -} - -// This can end up rendering this component multiple passes. +} // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. + function updateSuspenseListComponent( current$$1, workInProgress, @@ -14857,24 +15237,21 @@ function updateSuspenseListComponent( var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; - validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren( current$$1, workInProgress, newChildren, renderExpirationTime ); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext( suspenseContext, ForceSuspenseFallback ); + if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -14884,6 +15261,7 @@ function updateSuspenseListComponent( } else { var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect; + if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render @@ -14894,8 +15272,10 @@ function updateSuspenseListComponent( renderExpirationTime ); } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } + pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & BatchedMode) === NoMode) { @@ -14906,7 +15286,8 @@ function updateSuspenseListComponent( switch (revealOrder) { case "forwards": { var lastContentRow = findLastContentRow(workInProgress.child); - var tail = void 0; + var tail; + if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. @@ -14918,15 +15299,18 @@ function updateSuspenseListComponent( tail = lastContentRow.sibling; lastContentRow.sibling = null; } + initSuspenseListRenderState( workInProgress, false, // isBackwards tail, lastContentRow, - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "backwards": { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything @@ -14935,39 +15319,45 @@ function updateSuspenseListComponent( var _tail = null; var row = workInProgress.child; workInProgress.child = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } + var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; - } - // TODO: If workInProgress.child is null, we can continue on the tail immediately. + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. + initSuspenseListRenderState( workInProgress, true, // isBackwards _tail, null, // last - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "together": { initSuspenseListRenderState( workInProgress, false, // isBackwards null, // tail null, // last - undefined + undefined, + workInProgress.lastEffect ); break; } + default: { // The default reveal order is the same as not having // a boundary. @@ -14975,6 +15365,7 @@ function updateSuspenseListComponent( } } } + return workInProgress.child; } @@ -14985,6 +15376,7 @@ function updatePortalComponent( ) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; + if (current$$1 === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal @@ -15005,6 +15397,7 @@ function updatePortalComponent( renderExpirationTime ); } + return workInProgress.child; } @@ -15015,10 +15408,8 @@ function updateContextProvider( ) { var providerType = workInProgress.type; var context = providerType._context; - var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; { @@ -15040,6 +15431,7 @@ function updateContextProvider( if (oldProps !== null) { var oldValue = oldProps.value; var changedBits = calculateChangedBits(context, newValue, oldValue); + if (changedBits === 0) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { @@ -15078,14 +15470,14 @@ function updateContextConsumer( workInProgress, renderExpirationTime ) { - var context = workInProgress.type; - // The logic below for Context differs depending on PROD or DEV mode. In + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. + { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). @@ -15105,6 +15497,7 @@ function updateContextConsumer( context = context._context; } } + var newProps = workInProgress.pendingProps; var render = newProps.children; @@ -15122,15 +15515,15 @@ function updateContextConsumer( prepareToReadContext(workInProgress, renderExpirationTime); var newValue = readContext(context, newProps.unstable_observedBits); - var newChildren = void 0; + var newChildren; + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); newChildren = render(newValue); setCurrentPhase(null); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -15147,12 +15540,29 @@ function updateFundamentalComponent$1( renderExpirationTime ) { var fundamentalImpl = workInProgress.type.impl; + if (fundamentalImpl.reconcileChildren === false) { return null; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} +function updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; reconcileChildren( current$$1, workInProgress, @@ -15183,8 +15593,14 @@ function bailoutOnAlreadyFinishedWork( stopProfilerTimerIfRunning(workInProgress); } - // Check if the children have any pending work. + var updateExpirationTime = workInProgress.expirationTime; + + if (updateExpirationTime !== NoWork) { + markUnprocessedUpdateTime(updateExpirationTime); + } // Check if the children have any pending work. + var childExpirationTime = workInProgress.childExpirationTime; + if (childExpirationTime < renderExpirationTime) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are @@ -15201,53 +15617,54 @@ function bailoutOnAlreadyFinishedWork( function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { throw new Error("Cannot swap the root fiber."); - } - - // Disconnect from the old current. + } // Disconnect from the old current. // It will get deleted. + current$$1.alternate = null; - oldWorkInProgress.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; + if (prevSibling === null) { throw new Error("Expected parent to have a child."); } + while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; + if (prevSibling === null) { throw new Error("Expected to find the previous sibling."); } } - prevSibling.sibling = newWorkInProgress; - } - // Delete the old fiber and place the new one. + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = current$$1; returnFiber.lastEffect = current$$1; } else { returnFiber.firstEffect = returnFiber.lastEffect = current$$1; } + current$$1.nextEffect = null; current$$1.effectTag = Deletion; + newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber. - newWorkInProgress.effectTag |= Placement; - - // Restart work from the new fiber. return newWorkInProgress; } } @@ -15279,25 +15696,26 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { if ( oldProps !== newProps || - hasContextChanged() || - // Force a re-render if the implementation changed due to hot reload: + hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current$$1.type ) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else if (updateExpirationTime < renderExpirationTime) { - didReceiveUpdate = false; - // This fiber does not have any pending work. Bailout without entering + didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); resetHydrationState(); break; + case HostComponent: pushHostContext(workInProgress); + if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -15305,45 +15723,69 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } + break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { pushContextProvider(workInProgress); } + break; } + case HostPortal: pushHostContainer( workInProgress, workInProgress.stateNode.containerInfo ); break; + case ContextProvider: { var newValue = workInProgress.memoizedProps.value; pushProvider(workInProgress, newValue); break; } + case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + break; + case SuspenseComponent: { var state = workInProgress.memoizedState; - var didTimeout = state !== null; - if (didTimeout) { - // If this boundary is currently timed out, we need to decide + + if (state !== null) { + if (enableSuspenseServerRenderer) { + if (state.dehydrated !== null) { + pushSuspenseContext( + workInProgress, + setDefaultShallowSuspenseContext(suspenseStackCursor.current) + ); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. + + workInProgress.effectTag |= DidCapture; + break; + } + } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary + // child fragment. + var primaryChildFragment = workInProgress.child; var primaryChildExpirationTime = primaryChildFragment.childExpirationTime; + if ( primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime @@ -15359,14 +15801,15 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // The primary children do not have pending work with sufficient + ); // The primary children do not have pending work with sufficient // priority. Bailout. + var child = bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. @@ -15381,25 +15824,13 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { setDefaultShallowSuspenseContext(suspenseStackCursor.current) ); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // We know that this component will suspend again because if it has - // been unsuspended it has committed as a regular Suspense component. - // If it needs to be retried, it should have work scheduled on it. - workInProgress.effectTag |= DidCapture; - } - break; - } + case SuspenseListComponent: { var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect; - var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime; @@ -15415,23 +15846,24 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { workInProgress, renderExpirationTime ); - } - // If none of the children had any work, that means that none of + } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. - workInProgress.effectTag |= DidCapture; - } - // If nothing suspended before and we're rendering the same children, + workInProgress.effectTag |= DidCapture; + } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. + var renderState = workInProgress.memoizedState; + if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (hasChildWork) { @@ -15444,17 +15876,23 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + return bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; } } else { didReceiveUpdate = false; - } + } // Before entering the begin phase, clear the expiration time. - // Before entering the begin phase, clear the expiration time. workInProgress.expirationTime = NoWork; switch (workInProgress.tag) { @@ -15466,6 +15904,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent( @@ -15476,6 +15915,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FunctionComponent: { var _Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; @@ -15491,13 +15931,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case ClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; + var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps); + return updateClassComponent( current$$1, workInProgress, @@ -15506,35 +15949,43 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case HostRoot: return updateHostRoot(current$$1, workInProgress, renderExpirationTime); + case HostComponent: return updateHostComponent( current$$1, workInProgress, renderExpirationTime ); + case HostText: return updateHostText(current$$1, workInProgress); + case SuspenseComponent: return updateSuspenseComponent( current$$1, workInProgress, renderExpirationTime ); + case HostPortal: return updatePortalComponent( current$$1, workInProgress, renderExpirationTime ); + case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef( current$$1, workInProgress, @@ -15543,32 +15994,40 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case Fragment: return updateFragment(current$$1, workInProgress, renderExpirationTime); + case Mode: return updateMode(current$$1, workInProgress, renderExpirationTime); + case Profiler: return updateProfiler(current$$1, workInProgress, renderExpirationTime); + case ContextProvider: return updateContextProvider( current$$1, workInProgress, renderExpirationTime ); + case ContextConsumer: return updateContextConsumer( current$$1, workInProgress, renderExpirationTime ); + case MemoComponent: { var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; - // Resolve outer props first, then resolve inner props. + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -15580,6 +16039,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent( current$$1, @@ -15590,6 +16050,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case SimpleMemoComponent: { return updateSimpleMemoComponent( current$$1, @@ -15600,13 +16061,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case IncompleteClassComponent: { var _Component3 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; + var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4); + return mountIncompleteClassComponent( current$$1, workInProgress, @@ -15615,16 +16079,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - return updateDehydratedSuspenseComponent( - current$$1, - workInProgress, - renderExpirationTime - ); - } - break; - } + case SuspenseListComponent: { return updateSuspenseListComponent( current$$1, @@ -15632,6 +16087,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FundamentalComponent: { if (enableFundamentalAPI) { return updateFundamentalComponent$1( @@ -15640,18 +16096,30 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + break; } - } - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + return updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime + ); + } + + break; } - })(); + } + + { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); + } } function createFundamentalStateInstance(currentFiber, props, impl, state) { @@ -15665,8 +16133,212 @@ function createFundamentalStateInstance(currentFiber, props, impl, state) { }; } -var emptyObject$1 = {}; -var isArray$2 = Array.isArray; +function isFiberSuspenseAndTimedOut(fiber) { + return fiber.tag === SuspenseComponent && fiber.memoizedState !== null; +} + +function getSuspenseFallbackChild(fiber) { + return fiber.child.sibling.child; +} + +function collectScopedNodes(node, fn, scopedNodes) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type, memoizedProps) === true) { + scopedNodes.push(getPublicInstance(node.stateNode)); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + } +} + +function collectFirstScopedNode(node, fn) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type2 = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type2, memoizedProps) === true) { + return getPublicInstance(node.stateNode); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + } + + return null; +} + +function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) { + var child = startingChild; + + while (child !== null) { + collectScopedNodes(child, fn, scopedNodes); + child = child.sibling; + } +} + +function collectFirstScopedNodeFromChildren(startingChild, fn) { + var child = startingChild; + + while (child !== null) { + var scopedNode = collectFirstScopedNode(child, fn); + + if (scopedNode !== null) { + return scopedNode; + } + + child = child.sibling; + } + + return null; +} + +function collectNearestScopeMethods(node, scope, childrenScopes) { + if (isValidScopeNode(node, scope)) { + childrenScopes.push(node.stateNode.methods); + } else { + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + } +} + +function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) { + var child = startingChild; + + while (child !== null) { + collectNearestScopeMethods(child, scope, childrenScopes); + child = child.sibling; + } +} + +function isValidScopeNode(node, scope) { + return ( + node.tag === ScopeComponent && + node.type === scope && + node.stateNode !== null + ); +} + +function createScopeMethods(scope, instance) { + return { + getChildren: function() { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var childrenScopes = []; + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getChildrenFromRoot: function() { + var currentFiber = instance.fiber; + var node = currentFiber; + + while (node !== null) { + var parent = node.return; + + if (parent === null) { + break; + } + + node = parent; + + if (node.tag === ScopeComponent && node.type === scope) { + break; + } + } + + var childrenScopes = []; + collectNearestChildScopeMethods(node.child, scope, childrenScopes); + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getParent: function() { + var node = instance.fiber.return; + + while (node !== null) { + if (node.tag === ScopeComponent && node.type === scope) { + return node.stateNode.methods; + } + + node = node.return; + } + + return null; + }, + getProps: function() { + var currentFiber = instance.fiber; + return currentFiber.memoizedProps; + }, + queryAllNodes: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var scopedNodes = []; + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + + return scopedNodes.length === 0 ? null : scopedNodes; + }, + queryFirstNode: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + + return null; + }, + containsNode: function(node) { + var fiber = getInstanceFromNode$1(node); + + while (fiber !== null) { + if ( + fiber.tag === ScopeComponent && + fiber.type === scope && + fiber.stateNode === instance + ) { + return true; + } + + fiber = fiber.return; + } + + return false; + } + }; +} function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into @@ -15678,13 +16350,13 @@ function markRef$1(workInProgress) { workInProgress.effectTag |= Ref; } -var appendAllChildren = void 0; -var updateHostContainer = void 0; -var updateHostComponent$1 = void 0; -var updateHostText$1 = void 0; +var appendAllChildren; +var updateHostContainer; +var updateHostComponent$1; +var updateHostText$1; + if (supportsMutation) { // Mutation mode - appendAllChildren = function( parent, workInProgress, @@ -15694,6 +16366,7 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); @@ -15708,15 +16381,19 @@ if (supportsMutation) { node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -15725,6 +16402,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15735,21 +16413,21 @@ if (supportsMutation) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; + if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; - } - - // If we get updated because one of our children updated, we don't + } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. + var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. + var updatePayload = prepareUpdate( instance, type, @@ -15757,15 +16435,16 @@ if (supportsMutation) { newProps, rootContainerInstance, currentHostContext - ); - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. + if (updatePayload) { markUpdate(workInProgress); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { @@ -15774,7 +16453,6 @@ if (supportsMutation) { }; } else if (supportsPersistence) { // Persistent host tree mode - appendAllChildren = function( parent, workInProgress, @@ -15784,33 +16462,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance = cloneHiddenTextInstance(_instance, text, node); } + appendInitialChild(parent, _instance); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance2 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props = node.memoizedProps; var _type = node.type; _instance2 = cloneHiddenInstance(_instance2, _type, _props, node); } + appendInitialChild(parent, _instance2); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15820,8 +16505,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15832,7 +16519,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15841,6 +16530,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15851,24 +16541,27 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - }; + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - // An unfortunate fork of appendAllChildren because we have two different parent types. var appendAllChildrenToContainer = function( containerChildSet, workInProgress, @@ -15878,33 +16571,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance3 = cloneHiddenTextInstance(_instance3, text, node); } + appendChildToContainerChildSet(containerChildSet, _instance3); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance4 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props2 = node.memoizedProps; var _type2 = node.type; _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node); } + appendChildToContainerChildSet(containerChildSet, _instance4); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15914,8 +16614,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15926,7 +16628,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15935,6 +16639,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15945,38 +16650,45 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } }; + updateHostContainer = function(workInProgress) { var portalOrRoot = workInProgress.stateNode; var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged) { // No changes, just reuse the existing instance. } else { var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. + markUpdate(workInProgress); finalizeContainerChildren(container, newChildSet); } }; + updateHostComponent$1 = function( current, workInProgress, @@ -15985,19 +16697,22 @@ if (supportsMutation) { rootContainerInstance ) { var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; - // If there are no effects associated with this node, then none of our children had any updates. + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. // This guarantees that we can reuse all of them. + var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged && oldProps === newProps) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var recyclableInstance = workInProgress.stateNode; var currentHostContext = getHostContext(); var updatePayload = null; + if (oldProps !== newProps) { updatePayload = prepareUpdate( recyclableInstance, @@ -16008,12 +16723,14 @@ if (supportsMutation) { currentHostContext ); } + if (childrenUnchanged && updatePayload === null) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var newInstance = cloneInstance( currentInstance, updatePayload, @@ -16024,6 +16741,7 @@ if (supportsMutation) { childrenUnchanged, recyclableInstance ); + if ( finalizeInitialChildren( newInstance, @@ -16035,7 +16753,9 @@ if (supportsMutation) { ) { markUpdate(workInProgress); } + workInProgress.stateNode = newInstance; + if (childrenUnchanged) { // If there are no other effects in this tree, we need to flag this node as having one. // Even though we're not going to use it for anything. @@ -16046,6 +16766,7 @@ if (supportsMutation) { appendAllChildren(newInstance, workInProgress, false, false); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { if (oldText !== newText) { // If the text content differs, we'll create a new text instance for it. @@ -16056,9 +16777,9 @@ if (supportsMutation) { rootContainerInstance, currentHostContext, workInProgress - ); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. + ); // We'll have to mark it as having an effect, even though we won't use the effect for anything. // This lets the parents know that at least one of their children has changed. + markUpdate(workInProgress); } }; @@ -16067,6 +16788,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -16076,6 +16798,7 @@ if (supportsMutation) { ) { // Noop }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // Noop }; @@ -16091,14 +16814,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var tailNode = renderState.tail; var lastTailNode = null; + while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } + tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; @@ -16107,8 +16832,10 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. lastTailNode.sibling = null; } + break; } + case "collapsed": { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries @@ -16117,14 +16844,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; + while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } + _tailNode = _tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { @@ -16139,6 +16868,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. _lastTailNode.sibling = null; } + break; } } @@ -16150,41 +16880,55 @@ function completeWork(current, workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case IndeterminateComponent: break; + case LazyComponent: break; + case SimpleMemoComponent: case FunctionComponent: break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + break; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var fiberRoot = workInProgress.stateNode; + if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } + if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. - popHydrationState(workInProgress); - // This resets the hacky state to fix isMounted before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag &= ~Placement; + var wasHydrated = popHydrationState(workInProgress); + + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } } + updateHostContainer(workInProgress); break; } + case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; + if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1( current, @@ -16197,14 +16941,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableFlareAPI) { var prevListeners = current.memoizedProps.listeners; var nextListeners = newProps.listeners; - var instance = workInProgress.stateNode; + if (prevListeners !== nextListeners) { - updateEventListeners( - nextListeners, - instance, - rootContainerInstance, - workInProgress - ); + markUpdate(workInProgress); } } @@ -16213,26 +16952,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. + break; } - var currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on we want to add then top->down or // bottom->up. Top->down is faster in IE11. - var wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { + + var _wasHydrated = popHydrationState(workInProgress); + + if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if ( @@ -16246,47 +16982,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { // commit-phase we mark this as such. markUpdate(workInProgress); } + if (enableFlareAPI) { - var _instance5 = workInProgress.stateNode; var listeners = newProps.listeners; + if (listeners != null) { updateEventListeners( listeners, - _instance5, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } } } else { - var _instance6 = createInstance( + var instance = createInstance( type, newProps, rootContainerInstance, currentHostContext, workInProgress ); + appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners - appendAllChildren(_instance6, workInProgress, false, false); + workInProgress.stateNode = instance; if (enableFlareAPI) { var _listeners = newProps.listeners; + if (_listeners != null) { updateEventListeners( _listeners, - _instance6, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } - } - - // Certain renderers require commit-time effects for initial mount. + } // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. + if ( finalizeInitialChildren( - _instance6, + instance, type, newProps, rootContainerInstance, @@ -16295,7 +17031,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { ) { markUpdate(workInProgress); } - workInProgress.stateNode = _instance6; } if (workInProgress.ref !== null) { @@ -16303,32 +17038,34 @@ function completeWork(current, workInProgress, renderExpirationTime) { markRef$1(workInProgress); } } + break; } + case HostText: { var newText = newProps; + if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. + updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress); - if (_wasHydrated) { + + var _wasHydrated2 = popHydrationState(workInProgress); + + if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } @@ -16341,38 +17078,86 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); } } + break; } + case ForwardRef: break; + case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; + + if (enableSuspenseServerRenderer) { + if (nextState !== null && nextState.dehydrated !== null) { + if (current === null) { + var _wasHydrated3 = popHydrationState(workInProgress); + + if (!_wasHydrated3) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + + prepareToHydrateHostSuspenseInstance(workInProgress); + + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + + return null; + } else { + // We should never have been in a hydration state if we didn't have a current. + // However, in some of those paths, we might have reentered a hydration state + // and then we might be inside a hydration state. In that case, we'll need to + // exit out of it. + resetHydrationState(); + + if ((workInProgress.effectTag & DidCapture) === NoEffect) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. + + workInProgress.effectTag |= Update; + return null; + } + } + } + if ((workInProgress.effectTag & DidCapture) !== NoEffect) { // Something suspended. Re-render with the fallback children. - workInProgress.expirationTime = renderExpirationTime; - // Do not reset the effect list. + workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list. + return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = false; + if (current === null) { - // In cases where we didn't find a suitable hydration boundary we never - // downgraded this to a DehydratedSuspenseComponent, but we still need to - // pop the hydration state since we might be inside the insertion tree. - popHydrationState(workInProgress); + if (workInProgress.memoizedProps.fallback !== undefined) { + popHydrationState(workInProgress); + } } else { var prevState = current.memoizedState; prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { // We just switched from the fallback to the normal children. // Delete the fallback. // TODO: Would it be better to store the fallback fragment on + // the stateNode during the begin phase? var currentFallbackChild = current.child.sibling; + if (currentFallbackChild !== null) { // Deletions go at the beginning of the return fiber's effect list var first = workInProgress.firstEffect; + if (first !== null) { workInProgress.firstEffect = currentFallbackChild; currentFallbackChild.nextEffect = first; @@ -16380,6 +17165,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; currentFallbackChild.nextEffect = null; } + currentFallbackChild.effectTag = Deletion; } } @@ -16402,6 +17188,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true; + if ( hasInvisibleChildContext || hasSuspenseContext( @@ -16429,6 +17216,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if (supportsMutation) { // TODO: Only schedule updates if these values are non equal, i.e. it changed. if (nextDidTimeout || prevDidTimeout) { @@ -16440,6 +17228,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if ( enableSuspenseCallback && workInProgress.updateQueue !== null && @@ -16448,76 +17237,49 @@ function completeWork(current, workInProgress, renderExpirationTime) { // Always notify the callback workInProgress.effectTag |= Update; } + break; } + case Fragment: break; + case Mode: break; + case Profiler: break; + case HostPortal: popHostContainer(workInProgress); updateHostContainer(workInProgress); break; + case ContextProvider: // Pop provider fiber popProvider(workInProgress); break; + case ContextConsumer: break; + case MemoComponent: break; + case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; + if (isContextProvider(_Component)) { popContext(workInProgress); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (current === null) { - var _wasHydrated2 = popHydrationState(workInProgress); - (function() { - if (!_wasHydrated2) { - throw ReactError( - Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ) - ); - } - })(); - if (enableSchedulerTracing) { - markSpawnedWork(Never); - } - skipPastDehydratedSuspenseInstance(workInProgress); - } else { - // We should never have been in a hydration state if we didn't have a current. - // However, in some of those paths, we might have reentered a hydration state - // and then we might be inside a hydration state. In that case, we'll need to - // exit out of it. - resetHydrationState(); - if ((workInProgress.effectTag & DidCapture) === NoEffect) { - // This boundary did not suspend so it's now hydrated. - // To handle any future suspense cases, we're going to now upgrade it - // to a Suspense component. We detach it from the existing current fiber. - current.alternate = null; - workInProgress.alternate = null; - workInProgress.tag = SuspenseComponent; - workInProgress.memoizedState = null; - workInProgress.stateNode = null; - } - } - } - break; - } + case SuspenseListComponent: { popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; if (renderState === null) { @@ -16528,18 +17290,16 @@ function completeWork(current, workInProgress, renderExpirationTime) { var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect; - var renderedTail = renderState.rendering; + if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. - // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to @@ -16547,16 +17307,17 @@ function completeWork(current, workInProgress, renderExpirationTime) { var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect); + if (!cannotBeSuspended) { var row = workInProgress.child; + while (row !== null) { var suspended = findFirstSuspended(row); + if (suspended !== null) { didSuspendAlready = true; workInProgress.effectTag |= DidCapture; - cutOffTailIfNeeded(renderState, false); - - // If this is a newly suspended tree, it might not get committed as + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thennables. Instead, we'll transfer its thennables to the // SuspenseList so that it can retry if they resolve. @@ -16568,21 +17329,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. + var newThennables = suspended.updateQueue; + if (newThennables !== null) { workInProgress.updateQueue = newThennables; workInProgress.effectTag |= Update; - } - - // Rerender the whole list, but this time, we'll force fallbacks + } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect list before doing the second pass since that's now invalid. - workInProgress.firstEffect = workInProgress.lastEffect = null; - // Reset the child fibers to their original state. - resetChildFibers(workInProgress, renderExpirationTime); - // Set up the Suspense Context to force suspense and immediately + if (renderState.lastEffect === null) { + workInProgress.firstEffect = null; + } + + workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state. + + resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately // rerender the children. + pushSuspenseContext( workInProgress, setShallowSuspenseContext( @@ -16592,42 +17357,46 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); return workInProgress.child; } + row = row.sibling; } } } else { cutOffTailIfNeeded(renderState, false); - } - // Next we're going to render the tail. + } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { workInProgress.effectTag |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, true); - // This might have been modified. + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. + + var _newThennables = _suspended.updateQueue; + + if (_newThennables !== null) { + workInProgress.updateQueue = _newThennables; + workInProgress.effectTag |= Update; + } + + cutOffTailIfNeeded(renderState, true); // This might have been modified. + if ( renderState.tail === null && renderState.tailMode === "hidden" ) { // We need to delete the row we just rendered. - // Ensure we transfer the update queue to the parent. - var _newThennables = _suspended.updateQueue; - if (_newThennables !== null) { - workInProgress.updateQueue = _newThennables; - workInProgress.effectTag |= Update; - } // Reset the effect list to what it w as before we rendered this // child. The nested children have already appended themselves. var lastEffect = (workInProgress.lastEffect = - renderState.lastEffect); - // Remove any effects that were appended after this point. + renderState.lastEffect); // Remove any effects that were appended after this point. + if (lastEffect !== null) { lastEffect.nextEffect = null; - } - // We're done. + } // We're done. + return null; } } else if ( @@ -16639,10 +17408,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { // The assumption is that this is usually faster. workInProgress.effectTag |= DidCapture; didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. If we can show // them, then they really have the same priority as this render. // So we'll pick it back up the very next render pass once we've had @@ -16650,11 +17416,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { var nextPriority = renderExpirationTime - 1; workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority; + if (enableSchedulerTracing) { markSpawnedWork(nextPriority); } } } + if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in @@ -16665,11 +17433,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; + if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } + renderState.last = renderedTail; } } @@ -16681,18 +17451,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { // until we just give up and show what we have so far. var TAIL_EXPIRATION_TIMEOUT_MS = 500; renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; - } - // Pop a row. + } // Pop a row. + var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.lastEffect = workInProgress.lastEffect; - next.sibling = null; - - // Restore the context. + next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -16701,12 +17471,15 @@ function completeWork(current, workInProgress, renderExpirationTime) { } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } - pushSuspenseContext(workInProgress, suspenseContext); - // Do a pass over the next row. + + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + return next; } + break; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalImpl = workInProgress.type.impl; @@ -16714,22 +17487,28 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (fundamentalInstance === null) { var getInitialState = fundamentalImpl.getInitialState; - var fundamentalState = void 0; + var fundamentalState; + if (getInitialState !== undefined) { fundamentalState = getInitialState(newProps); } + fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( workInProgress, newProps, fundamentalImpl, fundamentalState || {} ); - var _instance7 = getFundamentalComponentInstance(fundamentalInstance); - fundamentalInstance.instance = _instance7; + + var _instance5 = getFundamentalComponentInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance5; + if (fundamentalImpl.reconcileChildren === false) { return null; } - appendAllChildren(_instance7, workInProgress, false, false); + + appendAllChildren(_instance5, workInProgress, false, false); mountFundamentalComponent(fundamentalInstance); } else { // We fire update in commit phase @@ -16737,259 +17516,177 @@ function completeWork(current, workInProgress, renderExpirationTime) { fundamentalInstance.prevProps = prevProps; fundamentalInstance.props = newProps; fundamentalInstance.currentFiber = workInProgress; + if (supportsPersistence) { - var _instance8 = cloneFundamentalInstance(fundamentalInstance); - fundamentalInstance.instance = _instance8; - appendAllChildren(_instance8, workInProgress, false, false); + var _instance6 = cloneFundamentalInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance6; + appendAllChildren(_instance6, workInProgress, false, false); } + var shouldUpdate = shouldUpdateFundamentalComponent( fundamentalInstance ); + if (shouldUpdate) { markUpdate(workInProgress); } } } + break; } - default: - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - return null; -} + case ScopeComponent: { + if (enableScopeAPI) { + if (current === null) { + var _type3 = workInProgress.type; + var scopeInstance = { + fiber: workInProgress, + methods: null + }; + workInProgress.stateNode = scopeInstance; + scopeInstance.methods = createScopeMethods(_type3, scopeInstance); -function mountEventResponder$1( - responder, - responderProps, - instance, - rootContainerInstance, - fiber, - respondersMap -) { - var responderState = emptyObject$1; - var getInitialState = responder.getInitialState; - if (getInitialState !== null) { - responderState = getInitialState(responderProps); - } - var responderInstance = createResponderInstance( - responder, - responderProps, - responderState, - instance, - fiber - ); - mountResponderInstance( - responder, - responderInstance, - responderProps, - responderState, - instance, - rootContainerInstance - ); - respondersMap.set(responder, responderInstance); -} + if (enableFlareAPI) { + var _listeners2 = newProps.listeners; -function updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance -) { - var responder = void 0; - var props = void 0; + if (_listeners2 != null) { + var _rootContainerInstance2 = getRootHostContainer(); - if (listener) { - responder = listener.responder; - props = listener.props; - } - (function() { - if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { - throw ReactError( - Error( - "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponer()." - ) - ); + updateEventListeners( + _listeners2, + workInProgress, + _rootContainerInstance2 + ); + } + } + + if (workInProgress.ref !== null) { + markRef$1(workInProgress); + markUpdate(workInProgress); + } + } else { + if (enableFlareAPI) { + var _prevListeners = current.memoizedProps.listeners; + var _nextListeners = newProps.listeners; + + if ( + _prevListeners !== _nextListeners || + workInProgress.ref !== null + ) { + markUpdate(workInProgress); + } + } else { + if (workInProgress.ref !== null) { + markUpdate(workInProgress); + } + } + + if (current.ref !== workInProgress.ref) { + markRef$1(workInProgress); + } + } + } + + break; } - })(); - var listenerProps = props; - if (visistedResponders.has(responder)) { - // show warning - { - 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 + + default: { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } - return; } - visistedResponders.add(responder); - var responderInstance = respondersMap.get(responder); - if (responderInstance === undefined) { - // Mount - mountEventResponder$1( - responder, - listenerProps, - instance, - rootContainerInstance, - fiber, - respondersMap - ); - } else { - // Update - responderInstance.props = listenerProps; - responderInstance.fiber = fiber; - } -} - -function updateEventListeners( - listeners, - instance, - rootContainerInstance, - fiber -) { - var visistedResponders = new Set(); - var dependencies = fiber.dependencies; - if (listeners != null) { - if (dependencies === null) { - dependencies = fiber.dependencies = { - expirationTime: NoWork, - firstContext: null, - responders: new Map() - }; - } - var respondersMap = dependencies.responders; - if (respondersMap === null) { - respondersMap = new Map(); - } - if (isArray$2(listeners)) { - for (var i = 0, length = listeners.length; i < length; i++) { - var listener = listeners[i]; - updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } else { - updateEventListener( - listeners, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } - if (dependencies !== null) { - var _respondersMap = dependencies.responders; - if (_respondersMap !== null) { - // Unmount - var mountedResponders = Array.from(_respondersMap.keys()); - for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { - var mountedResponder = mountedResponders[_i]; - if (!visistedResponders.has(mountedResponder)) { - var responderInstance = _respondersMap.get(mountedResponder); - unmountResponderInstance(responderInstance); - _respondersMap.delete(mountedResponder); - } - } - } - } + return null; } function unwindWork(workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + var effectTag = workInProgress.effectTag; + if (effectTag & ShouldCapture) { workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + return null; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - (function() { - if (!((_effectTag & DidCapture) === NoEffect)) { - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!((_effectTag & DidCapture) === NoEffect)) { + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." + ); + } + workInProgress.effectTag = (_effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } + case SuspenseComponent: { popSuspenseContext(workInProgress); - var _effectTag2 = workInProgress.effectTag; - if (_effectTag2 & ShouldCapture) { - workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } - return null; - } - case DehydratedSuspenseComponent: { + if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (workInProgress.alternate === null) { - // TODO: popHydrationState - } else { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (!(workInProgress.alternate !== null)) { + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + } + resetHydrationState(); } - var _effectTag3 = workInProgress.effectTag; - if (_effectTag3 & ShouldCapture) { - workInProgress.effectTag = - (_effectTag3 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } } + + var _effectTag2 = workInProgress.effectTag; + + if (_effectTag2 & ShouldCapture) { + workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; // Captured a suspense effect. Re-render the boundary. + + return workInProgress; + } + return null; } + case SuspenseListComponent: { - popSuspenseContext(workInProgress); - // SuspenseList doesn't actually catch anything. It should've been + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. + return null; } + case HostPortal: popHostContainer(workInProgress); return null; + case ContextProvider: popProvider(workInProgress); return null; + default: return null; } @@ -16999,37 +17696,41 @@ function unwindInterruptedWork(interruptedWork) { switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } + break; } + case HostRoot: { popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); break; } + case HostComponent: { popHostContext(interruptedWork); break; } + case HostPortal: popHostContainer(interruptedWork); break; + case SuspenseComponent: popSuspenseContext(interruptedWork); break; - case DehydratedSuspenseComponent: - if (enableSuspenseServerRenderer) { - popSuspenseContext(interruptedWork); - } - break; + case SuspenseListComponent: popSuspenseContext(interruptedWork); break; + case ContextProvider: popProvider(interruptedWork); break; + default: break; } @@ -17046,18 +17747,16 @@ function createCapturedValue(value, source) { } // Module provided by RN: -(function() { - if ( - !( - typeof ReactNativePrivateInterface.ReactFiberErrorDialog - .showErrorDialog === "function" - ) - ) { - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") - ); - } -})(); +if ( + !( + typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog === + "function" + ) +) { + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." + ); +} function showErrorDialog(capturedError) { return ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog( @@ -17066,23 +17765,21 @@ function showErrorDialog(capturedError) { } function logCapturedError(capturedError) { - var logError = showErrorDialog(capturedError); - - // Allow injected showErrorDialog() to prevent default console.error logging. + var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. + if (logError === false) { return; } var error = capturedError.error; + { var componentName = capturedError.componentName, componentStack = capturedError.componentStack, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, - willRetry = capturedError.willRetry; - - // Browsers support silencing uncaught errors by calling + willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. @@ -17092,22 +17789,20 @@ function logCapturedError(capturedError) { // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; - } - // The error is fatal. Since the silencing might have + } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. - console.error(error); - // For a more detailed description of this block, see: + + console.error(error); // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; + var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - var errorBoundaryMessage = void 0; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. if (errorBoundaryFound && errorBoundaryName) { if (willRetry) { errorBoundaryMessage = @@ -17125,31 +17820,32 @@ function logCapturedError(capturedError) { "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."; } + var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + - ("" + errorBoundaryMessage); - - // In development, we provide our own message with just the component stack. + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. + console.error(combinedMessage); } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } -var PossiblyWeakSet$1 = typeof WeakSet === "function" ? WeakSet : Set; - +var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source; var stack = errorInfo.stack; + if (stack === null && source !== null) { stack = getStackByFiberInDevAndProd(source); } @@ -17190,9 +17886,8 @@ var callComponentWillUnmountWithTimer = function(current$$1, instance) { instance.state = current$$1.memoizedState; instance.componentWillUnmount(); stopPhaseTimer(); -}; +}; // Capture errors so they don't interrupt unmounting. -// Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback( @@ -17202,6 +17897,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { current$$1, instance ); + if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); @@ -17211,10 +17907,12 @@ function safelyCallComponentWillUnmount(current$$1, instance) { function safelyDetachRef(current$$1) { var ref = current$$1.ref; + if (ref !== null) { if (typeof ref === "function") { { invokeGuardedCallback(null, ref, null, null); + if (hasCaughtError()) { var refError = clearCaughtError(); captureCommitPhaseError(current$$1, refError); @@ -17229,6 +17927,7 @@ function safelyDetachRef(current$$1) { function safelyCallDestroy(current$$1, destroy) { { invokeGuardedCallback(null, destroy, null); + if (hasCaughtError()) { var error = clearCaughtError(); captureCommitPhaseError(current$$1, error); @@ -17244,16 +17943,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); return; } + case ClassComponent: { if (finishedWork.effectTag & Snapshot) { if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, "getSnapshotBeforeUpdate"); - var instance = finishedWork.stateNode; - // We could update instance props and state here, + var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17283,14 +17983,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { : void 0; } } + var snapshot = instance.getSnapshotBeforeUpdate( finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState ); + { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); warningWithoutStack$1( @@ -17301,12 +18004,15 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { ); } } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; stopPhaseTimer(); } } + return; } + case HostRoot: case HostComponent: case HostText: @@ -17314,16 +18020,13 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case IncompleteClassComponent: // Nothing to do for these component types return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17331,18 +18034,22 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { function commitHookEffectList(unmountTag, mountTag, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; + do { if ((effect.tag & unmountTag) !== NoEffect$1) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; + if (destroy !== undefined) { destroy(); } } + if ((effect.tag & mountTag) !== NoEffect$1) { // Mount var create = effect.create; @@ -17350,8 +18057,10 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { { var _destroy = effect.destroy; + if (_destroy !== undefined && typeof _destroy !== "function") { var addendum = void 0; + if (_destroy === null) { addendum = " You returned null. If your effect does not require clean " + @@ -17373,6 +18082,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else { addendum = " You returned: " + _destroy; } + warningWithoutStack$1( false, "An effect function must not return anything besides a function, " + @@ -17383,6 +18093,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } } } + effect = effect.next; } while (effect !== firstEffect); } @@ -17398,6 +18109,7 @@ function commitPassiveHookEffects(finishedWork) { commitHookEffectList(NoEffect$1, MountPassive, finishedWork); break; } + default: break; } @@ -17417,14 +18129,16 @@ function commitLifeCycles( commitHookEffectList(UnmountLayout, MountLayout, finishedWork); break; } + case ClassComponent: { var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update) { if (current$$1 === null) { - startPhaseTimer(finishedWork, "componentDidMount"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidMount"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17454,6 +18168,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidMount(); stopPhaseTimer(); } else { @@ -17465,10 +18180,10 @@ function commitLifeCycles( current$$1.memoizedProps ); var prevState = current$$1.memoizedState; - startPhaseTimer(finishedWork, "componentDidUpdate"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidUpdate"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17498,6 +18213,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidUpdate( prevProps, prevState, @@ -17506,7 +18222,9 @@ function commitLifeCycles( stopPhaseTimer(); } } + var updateQueue = finishedWork.updateQueue; + if (updateQueue !== null) { { if ( @@ -17536,10 +18254,10 @@ function commitLifeCycles( ) : void 0; } - } - // We could update instance props and state here, + } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + commitUpdateQueue( finishedWork, updateQueue, @@ -17547,22 +18265,28 @@ function commitLifeCycles( committedExpirationTime ); } + return; } + case HostRoot: { var _updateQueue = finishedWork.updateQueue; + if (_updateQueue !== null) { var _instance = null; + if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; + case ClassComponent: _instance = finishedWork.child.stateNode; break; } } + commitUpdateQueue( finishedWork, _updateQueue, @@ -17570,15 +18294,16 @@ function commitLifeCycles( committedExpirationTime ); } + return; } - case HostComponent: { - var _instance2 = finishedWork.stateNode; - // Renderers may schedule work to be done after host components are mounted + case HostComponent: { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. + if (current$$1 === null && finishedWork.effectTag & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; @@ -17587,14 +18312,17 @@ function commitLifeCycles( return; } + case HostText: { // We have no life-cycles associated with text. return; } + case HostPortal: { // We have no life-cycles associated with portals. return; } + case Profiler: { if (enableProfilerTimer) { var onRender = finishedWork.memoizedProps.onRender; @@ -17622,23 +18350,27 @@ function commitLifeCycles( } } } + return; } - case SuspenseComponent: + + case SuspenseComponent: { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + return; + } + case SuspenseListComponent: case IncompleteClassComponent: case FundamentalComponent: + case ScopeComponent: return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17646,10 +18378,13 @@ function commitLifeCycles( function hideOrUnhideAllChildren(finishedWork, isHidden) { if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. var node = finishedWork; + while (true) { if (node.tag === HostComponent) { var instance = node.stateNode; + if (isHidden) { hideInstance(instance); } else { @@ -17657,6 +18392,7 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (isHidden) { hideTextInstance(_instance3); } else { @@ -17664,9 +18400,11 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if ( node.tag === SuspenseComponent && - node.memoizedState !== null + node.memoizedState !== null && + node.memoizedState.dehydrated === null ) { // Found a nested Suspense component that timed out. Skip over the + // primary child fragment, which should remain hidden. var fallbackChildFragment = node.child.sibling; fallbackChildFragment.return = node; node = fallbackChildFragment; @@ -17676,15 +18414,19 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -17693,16 +18435,24 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { function commitAttachRef(finishedWork) { var ref = finishedWork.ref; + if (ref !== null) { var instance = finishedWork.stateNode; - var instanceToUse = void 0; + var instanceToUse; + switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; + default: instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag + + if (enableScopeAPI && finishedWork.tag === ScopeComponent) { + instanceToUse = instance.methods; } + if (typeof ref === "function") { ref(instanceToUse); } else { @@ -17725,6 +18475,7 @@ function commitAttachRef(finishedWork) { function commitDetachRef(current$$1) { var currentRef = current$$1.ref; + if (currentRef !== null) { if (typeof currentRef === "function") { currentRef(null); @@ -17732,12 +18483,11 @@ function commitDetachRef(current$$1) { currentRef.current = null; } } -} - -// User-originating errors (lifecycles and refs) should not interrupt +} // User-originating errors (lifecycles and refs) should not interrupt // deletion, so don't let them throw. Host-originating errors should // interrupt deletion, so it's okay -function commitUnmount(current$$1, renderPriorityLevel) { + +function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) { onCommitUnmount(current$$1); switch (current$$1.tag) { @@ -17746,12 +18496,12 @@ function commitUnmount(current$$1, renderPriorityLevel) { case MemoComponent: case SimpleMemoComponent: { var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - // When the owner fiber is deleted, the destroy function of a passive + if (lastEffect !== null) { + var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive // effect hook is called during the synchronous commit phase. This is // a concession to implementation complexity. Calling it in the // passive effect phase (like they usually are, when dependencies @@ -17763,40 +18513,51 @@ function commitUnmount(current$$1, renderPriorityLevel) { // the priority. // // TODO: Reconsider this implementation trade off. + var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; runWithPriority$1(priorityLevel, function() { var effect = firstEffect; + do { var destroy = effect.destroy; + if (destroy !== undefined) { safelyCallDestroy(current$$1, destroy); } + effect = effect.next; } while (effect !== firstEffect); }); } } + break; } + case ClassComponent: { safelyDetachRef(current$$1); var instance = current$$1.stateNode; + if (typeof instance.componentWillUnmount === "function") { safelyCallComponentWillUnmount(current$$1, instance); } + return; } + case HostComponent: { if (enableFlareAPI) { var dependencies = current$$1.dependencies; if (dependencies !== null) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for ( var i = 0, length = responderInstances.length; i < length; @@ -17805,49 +18566,80 @@ function commitUnmount(current$$1, renderPriorityLevel) { var responderInstance = responderInstances[i]; unmountResponderInstance(responderInstance); } + dependencies.responders = null; } } } + safelyDetachRef(current$$1); return; } + case HostPortal: { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if (supportsMutation) { - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else if (supportsPersistence) { emptyPortalContainer(current$$1); } + return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = current$$1.stateNode; + if (fundamentalInstance !== null) { unmountFundamentalComponent(fundamentalInstance); current$$1.stateNode = null; } } + + return; + } + + case DehydratedFragment: { + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(current$$1.stateNode); + } + } + } + + return; + } + + case ScopeComponent: { + if (enableScopeAPI) { + safelyDetachRef(current$$1); + } } } } -function commitNestedUnmounts(root, renderPriorityLevel) { +function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) { // While we're inside a removed host node we don't want to call // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. var node = root; + while (true) { - commitUnmount(node, renderPriorityLevel); - // Visit children because they may contain more composite or host nodes. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes. // Skip portals because commitUnmount() currently visits them recursively. + if ( - node.child !== null && - // If we use mutation we drill down into portals using commitUnmount above. + node.child !== null && // If we use mutation we drill down into portals using commitUnmount above. // If we don't use mutation we drill down into portals here instead. (!supportsMutation || node.tag !== HostPortal) ) { @@ -17855,27 +18647,31 @@ function commitNestedUnmounts(root, renderPriorityLevel) { node = node.child; continue; } + if (node === root) { return; } + while (node.sibling === null) { if (node.return === null || node.return === root) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } function detachFiber(current$$1) { - var alternate = current$$1.alternate; - // Cut off the return pointers to disconnect it from the tree. Ideally, we + var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. This child // itself will be GC:ed when the parent updates the next time. + current$$1.return = null; current$$1.child = null; current$$1.memoizedState = null; @@ -17886,6 +18682,7 @@ function detachFiber(current$$1) { current$$1.lastEffect = null; current$$1.pendingProps = null; current$$1.memoizedProps = null; + if (alternate !== null) { detachFiber(alternate); } @@ -17898,7 +18695,6 @@ function emptyPortalContainer(current$$1) { var portal = current$$1.stateNode; var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); } @@ -17914,45 +18710,41 @@ function commitContainer(finishedWork) { case FundamentalComponent: { return; } + case HostRoot: case HostPortal: { var portalOrRoot = finishedWork.stateNode; var containerInfo = portalOrRoot.containerInfo, - _pendingChildren = portalOrRoot.pendingChildren; - + pendingChildren = portalOrRoot.pendingChildren; return; } + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } function getHostParentFiber(fiber) { var parent = fiber.return; + while (parent !== null) { if (isHostParent(parent)) { return parent; } + parent = parent.return; } - (function() { - { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } function isHostParent(fiber) { @@ -17967,7 +18759,9 @@ function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. var node = fiber; + siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { @@ -17976,31 +18770,34 @@ function getHostSibling(fiber) { // last sibling. return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; + while ( node.tag !== HostComponent && node.tag !== HostText && - node.tag !== DehydratedSuspenseComponent + node.tag !== DehydratedFragment ) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.effectTag & Placement) { // If we don't have a child, try the siblings instead. continue siblings; - } - // If we don't have a child, try the siblings instead. + } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. + if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } - } - // Check if this host node is stable or about to be placed. + } // Check if this host node is stable or about to be placed. + if (!(node.effectTag & Placement)) { // Found it! return node.stateNode; @@ -18011,60 +18808,63 @@ function getHostSibling(fiber) { function commitPlacement(finishedWork) { if (!supportsMutation) { return; - } + } // Recursively insert all host nodes into the parent. - // Recursively insert all host nodes into the parent. - var parentFiber = getHostParentFiber(finishedWork); + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - // Note: these two variables *must* always be updated together. - var parent = void 0; - var isContainer = void 0; + var parent; + var isContainer; var parentStateNode = parentFiber.stateNode; + switch (parentFiber.tag) { case HostComponent: parent = parentStateNode; isContainer = false; break; + case HostRoot: parent = parentStateNode.containerInfo; isContainer = true; break; + case HostPortal: parent = parentStateNode.containerInfo; isContainer = true; break; + case FundamentalComponent: if (enableFundamentalAPI) { parent = parentStateNode.instance; isContainer = false; } + // eslint-disable-next-line-no-fallthrough - default: - (function() { - { - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + default: { + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } } + if (parentFiber.effectTag & ContentReset) { // Reset the text content of the parent before doing any insertions - resetTextContent(parent); - // Clear ContentReset from the effect tag + resetTextContent(parent); // Clear ContentReset from the effect tag + parentFiber.effectTag &= ~ContentReset; } - var before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. + var node = finishedWork; + while (true) { var isHost = node.tag === HostComponent || node.tag === HostText; + if (isHost || (enableFundamentalAPI && node.tag === FundamentalComponent)) { var stateNode = isHost ? node.stateNode : node.stateNode.instance; + if (before) { if (isContainer) { insertInContainerBefore(parent, stateNode, before); @@ -18087,85 +18887,91 @@ function commitPlacement(finishedWork) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel) { +function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) { // We only have the top Fiber that was deleted but we need to recurse down its - var node = current$$1; - - // Each iteration, currentParent is populated with node's host parent if not + // children to find all the terminal nodes. + var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not // currentParentIsValid. - var currentParentIsValid = false; - // Note: these two variables *must* always be updated together. - var currentParent = void 0; - var currentParentIsContainer = void 0; + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. + + var currentParent; + var currentParentIsContainer; while (true) { if (!currentParentIsValid) { var parent = node.return; + findParent: while (true) { - (function() { - if (!(parent !== null)) { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(parent !== null)) { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + var parentStateNode = parent.stateNode; + switch (parent.tag) { case HostComponent: currentParent = parentStateNode; currentParentIsContainer = false; break findParent; + case HostRoot: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case HostPortal: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case FundamentalComponent: if (enableFundamentalAPI) { currentParent = parentStateNode.instance; currentParentIsContainer = false; } } + parent = parent.return; } + currentParentIsValid = true; } if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, node.stateNode); } else { removeChild(currentParent, node.stateNode); - } - // Don't visit children because we already visited them. + } // Don't visit children because we already visited them. } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var fundamentalNode = node.stateNode.instance; - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, fundamentalNode); } else { @@ -18173,9 +18979,20 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { } } else if ( enableSuspenseServerRenderer && - node.tag === DehydratedSuspenseComponent + node.tag === DehydratedFragment ) { - // Delete the dehydrated suspense boundary and all of its content. + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(node.stateNode); + } + } + } // Delete the dehydrated suspense boundary and all of its content. + if (currentParentIsContainer) { clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); } else { @@ -18186,49 +19003,55 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { // When we go into a portal, it becomes the parent to remove from. // We will reassign it back when we pop the portal on the way up. currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; - // Visit children because portals might contain host components. + currentParentIsContainer = true; // Visit children because portals might contain host components. + node.child.return = node; node = node.child; continue; } } else { - commitUnmount(node, renderPriorityLevel); - // Visit children because we may find more host components below. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below. + if (node.child !== null) { node.child.return = node; node = node.child; continue; } } + if (node === current$$1) { return; } + while (node.sibling === null) { if (node.return === null || node.return === current$$1) { return; } + node = node.return; + if (node.tag === HostPortal) { // When we go out of the portal, we need to restore the parent. // Since we don't keep a stack of them, we will search for it. currentParentIsValid = false; } } + node.sibling.return = node.return; node = node.sibling; } } -function commitDeletion(current$$1, renderPriorityLevel) { +function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) { if (supportsMutation) { // Recursively delete all host nodes from the parent. // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else { // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(current$$1, renderPriorityLevel); + commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel); } + detachFiber(current$$1); } @@ -18244,18 +19067,35 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + + case HostRoot: { + if (supportsHydration) { + var root = finishedWork.stateNode; + + if (root.hydrate) { + // We've just hydrated. No need to hydrate again. + root.hydrate = false; + commitHydratedContainer(root.containerInfo); + } + } + + break; + } } commitContainer(finishedWork); @@ -18272,23 +19112,27 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case ClassComponent: { return; } + case HostComponent: { var instance = finishedWork.stateNode; + if (instance != null) { // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps; - var type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; + if (updatePayload !== null) { commitUpdate( instance, @@ -18299,72 +19143,117 @@ function commitWork(current$$1, finishedWork) { finishedWork ); } + + if (enableFlareAPI) { + var prevListeners = oldProps.listeners; + var nextListeners = newProps.listeners; + + if (prevListeners !== nextListeners) { + updateEventListeners(nextListeners, finishedWork, null); + } + } } + return; } + case HostText: { - (function() { - if (!(finishedWork.stateNode !== null)) { - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(finishedWork.stateNode !== null)) { + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldText = current$$1 !== null ? current$$1.memoizedProps : newText; commitTextUpdate(textInstance, oldText, newText); return; } + case HostRoot: { + if (supportsHydration) { + var _root = finishedWork.stateNode; + + if (_root.hydrate) { + // We've just hydrated. No need to hydrate again. + _root.hydrate = false; + commitHydratedContainer(_root.containerInfo); + } + } + return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + case IncompleteClassComponent: { return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = finishedWork.stateNode; updateFundamentalComponent(fundamentalInstance); } + return; } - default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + var scopeInstance = finishedWork.stateNode; + scopeInstance.fiber = finishedWork; + + if (enableFlareAPI) { + var _newProps = finishedWork.memoizedProps; + + var _oldProps = + current$$1 !== null ? current$$1.memoizedProps : _newProps; + + var _prevListeners = _oldProps.listeners; + var _nextListeners = _newProps.listeners; + + if (_prevListeners !== _nextListeners) { + updateEventListeners(_nextListeners, finishedWork, null); + } } - })(); + } + + return; + } + + default: { + { + 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." + ); + } } } } function commitSuspenseComponent(finishedWork) { var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; + var newDidTimeout; var primaryChildParent = finishedWork; + if (newState === null) { newDidTimeout = false; } else { @@ -18379,8 +19268,10 @@ function commitSuspenseComponent(finishedWork) { if (enableSuspenseCallback && newState !== null) { var suspenseCallback = finishedWork.memoizedProps.suspenseCallback; + if (typeof suspenseCallback === "function") { var thenables = finishedWork.updateQueue; + if (thenables !== null) { suspenseCallback(new Set(thenables)); } @@ -18392,23 +19283,67 @@ function commitSuspenseComponent(finishedWork) { } } +function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } + + var newState = finishedWork.memoizedState; + + if (newState === null) { + var current$$1 = finishedWork.alternate; + + if (current$$1 !== null) { + var prevState = current$$1.memoizedState; + + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onHydrated = hydrationCallbacks.onHydrated; + + if (onHydrated) { + onHydrated(suspenseInstance); + } + } + } + } + } + } + } +} + function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of thenables. // For each thenable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. var thenables = finishedWork.updateQueue; + if (thenables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; + if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet$1(); + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } + thenables.forEach(function(thenable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryThenable.bind(null, finishedWork, thenable); + if (!retryCache.has(thenable)) { if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); + if (thenable.__reactDoNotTraceInteractions !== true) { + retry = tracing.unstable_wrap(retry); + } } + retryCache.add(thenable); thenable.then(retry, retry); } @@ -18420,24 +19355,28 @@ function commitResetTextContent(current$$1) { if (!supportsMutation) { return; } + resetTextContent(current$$1.stateNode); } -var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { - var update = createUpdate(expirationTime, null); - // Unmount the root by rendering null. - update.tag = CaptureUpdate; - // Caution: React DevTools currently depends on this property + var update = createUpdate(expirationTime, null); // Unmount the root by rendering null. + + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". - update.payload = { element: null }; + + update.payload = { + element: null + }; var error = errorInfo.value; + update.callback = function() { onUncaughtError(error); logError(fiber, errorInfo); }; + return update; } @@ -18445,8 +19384,10 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime, null); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; + if (typeof getDerivedStateFromError === "function") { var error = errorInfo.value; + update.payload = function() { logError(fiber, errorInfo); return getDerivedStateFromError(error); @@ -18454,27 +19395,30 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { } var inst = fiber.stateNode; + if (inst !== null && typeof inst.componentDidCatch === "function") { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } + if (typeof getDerivedStateFromError !== "function") { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined - // Only log here if componentDidCatch is the only error boundary method defined logError(fiber, errorInfo); } + var error = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error, { componentStack: stack !== null ? stack : "" }); + { if (typeof getDerivedStateFromError !== "function") { // If componentDidCatch is the only error boundary method defined, @@ -18496,6 +19440,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { markFailedErrorBoundaryForHotReloading(fiber); }; } + return update; } @@ -18504,18 +19449,21 @@ function attachPingListener(root, renderExpirationTime, thenable) { // only if one does not already exist for the current render expiration // time (which acts like a "thread ID" here). var pingCache = root.pingCache; - var threadIDs = void 0; + var threadIDs; + if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); threadIDs = new Set(); pingCache.set(thenable, threadIDs); } else { threadIDs = pingCache.get(thenable); + if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(thenable, threadIDs); } } + if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); @@ -18525,9 +19473,6 @@ function attachPingListener(root, renderExpirationTime, thenable) { thenable, renderExpirationTime ); - if (enableSchedulerTracing) { - ping = tracing.unstable_wrap(ping); - } thenable.then(ping, ping); } } @@ -18540,8 +19485,8 @@ function throwException( renderExpirationTime ) { // The source fiber did not complete. - sourceFiber.effectTag |= Incomplete; - // Its effect list is no longer valid. + sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid. + sourceFiber.firstEffect = sourceFiber.lastEffect = null; if ( @@ -18551,34 +19496,31 @@ function throwException( ) { // This is a thenable. var thenable = value; - checkForWrongSuspensePriorityInDEV(sourceFiber); - var hasInvisibleParentBoundary = hasSuspenseContext( suspenseStackCursor.current, InvisibleParentSuspenseContext - ); + ); // Schedule the nearest Suspense to re-render the timed out view. - // Schedule the nearest Suspense to re-render the timed out view. var _workInProgress = returnFiber; + do { if ( _workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary) ) { // Found the nearest boundary. - // Stash the promise on the boundary fiber. If the boundary times out, we'll + // attach another listener to flip the boundary back to its normal state. var thenables = _workInProgress.updateQueue; + if (thenables === null) { var updateQueue = new Set(); updateQueue.add(thenable); _workInProgress.updateQueue = updateQueue; } else { thenables.add(thenable); - } - - // If the boundary is outside of batched mode, we should *not* + } // If the boundary is outside of batched mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. In the commit phase, we'll schedule a // subsequent synchronous update to re-render the Suspense. @@ -18586,16 +19528,17 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a batched mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & BatchedMode) === NoMode) { - _workInProgress.effectTag |= DidCapture; - // We're going to commit this fiber even though it didn't complete. + if ((_workInProgress.mode & BatchedMode) === NoMode) { + _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. + sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call @@ -18609,17 +19552,13 @@ function throwException( update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update); } - } - - // The source fiber did not complete. Mark it with Sync priority to + } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. - sourceFiber.expirationTime = Sync; - // Exit without suspending. - return; - } + sourceFiber.expirationTime = Sync; // Exit without suspending. - // Confirmed that the boundary is in a concurrent mode tree. Continue + return; + } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this @@ -18634,7 +19573,6 @@ function throwException( // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, @@ -18662,56 +19600,16 @@ function throwException( // ensure that new initial loading states can commit as soon as possible. attachPingListener(root, renderExpirationTime, thenable); - - _workInProgress.effectTag |= ShouldCapture; - _workInProgress.expirationTime = renderExpirationTime; - - return; - } else if ( - enableSuspenseServerRenderer && - _workInProgress.tag === DehydratedSuspenseComponent - ) { - attachPingListener(root, renderExpirationTime, thenable); - - // Since we already have a current fiber, we can eagerly add a retry listener. - var retryCache = _workInProgress.memoizedState; - if (retryCache === null) { - retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var current$$1 = _workInProgress.alternate; - (function() { - if (!current$$1) { - throw ReactError( - Error( - "A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React." - ) - ); - } - })(); - current$$1.memoizedState = retryCache; - } - // Memoize using the boundary fiber to prevent redundant listeners. - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - var retry = resolveRetryThenable.bind( - null, - _workInProgress, - thenable - ); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - thenable.then(retry, retry); - } _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; - } - // This boundary already captured during this render. Continue to the next + } // This boundary already captured during this render. Continue to the next // boundary. + _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // No boundary was found. Fallthrough to error mode. + } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode. // TODO: Use invariant so the message is stripped in prod? + value = new Error( (getComponentName(sourceFiber.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n" + @@ -18720,33 +19618,37 @@ function throwException( "provide a loading indicator or placeholder to display." + getStackByFiberInDevAndProd(sourceFiber) ); - } - - // We didn't find a boundary that could handle this type of exception. Start + } // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. + renderDidError(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; + do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; + var _update = createRootErrorUpdate( workInProgress, _errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update); return; } + case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; + if ( (workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === "function" || @@ -18755,142 +19657,153 @@ function throwException( !isAlreadyFailedLegacyErrorBoundary(instance))) ) { workInProgress.effectTag |= ShouldCapture; - workInProgress.expirationTime = renderExpirationTime; - // Schedule the error boundary to re-render using updated state + workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state + var _update2 = createClassErrorUpdate( workInProgress, errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update2); return; } + break; + default: break; } + workInProgress = workInProgress.return; } while (workInProgress !== null); } -// The scheduler is imported here *only* to detect whether it's been mocked -// DEV stuff var ceil = Math.ceil; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; +var NoContext = + /* */ + 0; +var BatchedContext = + /* */ + 1; +var EventContext = + /* */ + 2; +var DiscreteEventContext = + /* */ + 4; +var LegacyUnbatchedContext = + /* */ + 8; +var RenderContext = + /* */ + 16; +var CommitContext = + /* */ + 32; +var RootIncomplete = 0; +var RootFatalErrored = 1; +var RootErrored = 2; +var RootSuspended = 3; +var RootSuspendedWithDelay = 4; +var RootCompleted = 5; +// Describes where we are in the React execution stack +var executionContext = NoContext; // The root we're working on -var NoContext = /* */ 0; -var BatchedContext = /* */ 1; -var EventContext = /* */ 2; -var DiscreteEventContext = /* */ 4; -var LegacyUnbatchedContext = /* */ 8; -var RenderContext = /* */ 16; -var CommitContext = /* */ 32; +var workInProgressRoot = null; // The fiber we're working on -var RootIncomplete = 0; -var RootErrored = 1; -var RootSuspended = 2; -var RootSuspendedWithDelay = 3; -var RootCompleted = 4; +var workInProgress = null; // The expiration time we're rendering -// Describes where we are in the React execution stack -var executionContext = NoContext; -// The root we're working on -var workInProgressRoot = null; -// The fiber we're working on -var workInProgress = null; -// The expiration time we're rendering -var renderExpirationTime = NoWork; -// Whether to root completed, errored, suspended, etc. -var workInProgressRootExitStatus = RootIncomplete; -// Most recent event time among processed updates during this render. +var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc. + +var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown + +var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render. // This is conceptually a time stamp but expressed in terms of an ExpirationTime // because we deal mostly with expiration times in the hot path, so this avoids // the conversion happening in the hot path. + var workInProgressRootLatestProcessedExpirationTime = Sync; var workInProgressRootLatestSuspenseTimeout = Sync; -var workInProgressRootCanSuspendUsingConfig = null; -// If we're pinged while rendering we don't always restart immediately. +var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only +// includes unprocessed updates, not work in bailed out children. + +var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately. // This flag determines if it might be worthwhile to restart if an opportunity // happens latere. -var workInProgressRootHasPendingPing = false; -// The most recent time we committed a fallback. This lets us ensure a train + +var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. + var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; - var nextEffect = null; var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; - var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsRenderPriority = NoPriority; var pendingPassiveEffectsExpirationTime = NoWork; +var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates -var rootsWithPendingDiscreteUpdates = null; - -// Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; - -var interruptedBy = null; - -// Marks the need to reschedule pending interactions at these expiration times +var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times // during the commit phase. This enables them to be traced across components // that spawn new work during render. E.g. hidden boundaries, suspended SSR // hydration or SuspenseList. -var spawnedWorkDuringRender = null; -// Expiration times are computed by adding to the current time (the start +var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start // time). However, if two updates are scheduled within the same event, we // should treat their start times as simultaneous, even if the actual clock // time has advanced between the first and second call. - // In other words, because expiration times determine how updates are batched, // we want all updates of like priority that occur within the same event to // receive the same expiration time. Otherwise we get tearing. -var currentEventTime = NoWork; +var currentEventTime = NoWork; function requestCurrentTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return msToExpirationTime(now()); - } - // We're not inside React, so we may be in the middle of a browser event. + } // We're not inside React, so we may be in the middle of a browser event. + if (currentEventTime !== NoWork) { // Use the same start time for all updates until we enter React again. return currentEventTime; - } - // This is the first update since React yielded. Compute a new start time. + } // This is the first update since React yielded. Compute a new start time. + currentEventTime = msToExpirationTime(now()); return currentEventTime; } - function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { var mode = fiber.mode; + if ((mode & BatchedMode) === NoMode) { return Sync; } var priorityLevel = getCurrentPriorityLevel(); + if ((mode & ConcurrentMode) === NoMode) { return priorityLevel === ImmediatePriority ? Sync : Batched; } if ((executionContext & RenderContext) !== NoContext) { // Use whatever time we're already rendering + // TODO: Should there be a way to opt out, like with `runWithPriority`? return renderExpirationTime; } - var expirationTime = void 0; + var expirationTime; + if (suspenseConfig !== null) { // Compute an expiration time based on the Suspense timeout. expirationTime = computeSuspenseExpiration( @@ -18903,33 +19816,33 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { case ImmediatePriority: expirationTime = Sync; break; + case UserBlockingPriority$1: // TODO: Rename this to computeUserBlockingExpiration expirationTime = computeInteractiveExpiration(currentTime); break; + case NormalPriority: case LowPriority: // TODO: Handle LowPriority // TODO: Rename this to... something better. expirationTime = computeAsyncExpiration(currentTime); break; + case IdlePriority: - expirationTime = Never; + expirationTime = Idle; break; - default: - (function() { - { - throw ReactError(Error("Expected a valid priority level")); - } - })(); - } - } - // If we're in the middle of rendering a tree, do not update at the same + default: { + throw Error("Expected a valid priority level"); + } + } + } // If we're in the middle of rendering a tree, do not update at the same // expiration time that is already rendering. // TODO: We shouldn't have to do this if the update is on a different root. // Refactor computeExpirationForFiber + scheduleUpdate so we have access to // the root when we check for this condition. + if (workInProgressRoot !== null && expirationTime === renderExpirationTime) { // This is a trick to move this update into a separate batch expirationTime -= 1; @@ -18937,47 +19850,40 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { return expirationTime; } - function scheduleUpdateOnFiber(fiber, expirationTime) { checkForNestedUpdates(); warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber); - var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime); + if (root === null) { warnAboutUpdateOnUnmountedFiberInDEV(fiber); return; } - root.pingTime = NoWork; - checkForInterruption(fiber, expirationTime); - recordScheduleUpdate(); - - // TODO: computeExpirationForFiber also reads the priority. Pass the + recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); if (expirationTime === Sync) { if ( // Check if we're inside unbatchedUpdates - (executionContext & LegacyUnbatchedContext) !== NoContext && - // Check if we're not already rendering + (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering (executionContext & (RenderContext | CommitContext)) === NoContext ) { // Register pending interactions on the root to avoid losing traced interaction data. - schedulePendingInteractions(root, expirationTime); - - // This is a legacy edge case. The initial mount of a ReactDOM.render-ed + schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed // root inside of batchedUpdates should be synchronous, but layout updates // should be deferred until the end of the batch. - var callback = renderRoot(root, Sync, true); - while (callback !== null) { - callback = callback(true); - } + + performSyncWorkOnRoot(root); } else { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); + if (executionContext === NoContext) { - // Flush the synchronous work now, wnless we're already working or inside + // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated @@ -18986,12 +19892,12 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { } } } else { - scheduleCallbackForRoot(root, priorityLevel, expirationTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); } if ( - (executionContext & DiscreteEventContext) !== NoContext && - // Only updates at user-blocking priority or greater are considered + (executionContext & DiscreteEventContext) !== NoContext && // Only updates at user-blocking priority or greater are considered // discrete, even inside a discrete event. (priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority) @@ -19002,37 +19908,42 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); } else { var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) { rootsWithPendingDiscreteUpdates.set(root, expirationTime); } } } } -var scheduleWork = scheduleUpdateOnFiber; - -// This is split into a separate function so we can mark a fiber with pending +var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending // work without treating it as a typical update that originates from an event; // e.g. retrying a Suspense boundary isn't an update, but it does schedule work // on a fiber. + function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { // Update the source fiber's expiration time if (fiber.expirationTime < expirationTime) { fiber.expirationTime = expirationTime; } + var alternate = fiber.alternate; + if (alternate !== null && alternate.expirationTime < expirationTime) { alternate.expirationTime = expirationTime; - } - // Walk the parent path to the root and update the child expiration time. + } // Walk the parent path to the root and update the child expiration time. + var node = fiber.return; var root = null; + if (node === null && fiber.tag === HostRoot) { root = fiber.stateNode; } else { while (node !== null) { alternate = node.alternate; + if (node.childExpirationTime < expirationTime) { node.childExpirationTime = expirationTime; + if ( alternate !== null && alternate.childExpirationTime < expirationTime @@ -19045,580 +19956,430 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { ) { alternate.childExpirationTime = expirationTime; } + if (node.return === null && node.tag === HostRoot) { root = node.stateNode; break; } + node = node.return; } } if (root !== null) { - // Update the first and last pending expiration times in this root - var firstPendingTime = root.firstPendingTime; - if (expirationTime > firstPendingTime) { - root.firstPendingTime = expirationTime; - } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime === NoWork || expirationTime < lastPendingTime) { - root.lastPendingTime = expirationTime; - } + if (workInProgressRoot === root) { + // Received an update to a tree that's in the middle of rendering. Mark + // that's unprocessed work on this root. + markUnprocessedUpdateTime(expirationTime); + + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: This happens to work when receiving an update during the render + // phase, because of the trick inside computeExpirationForFiber to + // subtract 1 from `renderExpirationTime` to move it into a + // separate bucket. But we should probably model it with an exception, + // using the same mechanism we use to force hydration of a subtree. + // TODO: This does not account for low pri updates that were already + // scheduled before the root started rendering. Need to track the next + // pending expiration time (perhaps by backtracking the return path) and + // then trigger a restart in the `renderDidSuspendDelayIfPossible` path. + markRootSuspendedAtTime(root, renderExpirationTime); + } + } // Mark that the root has a pending update. + + markRootUpdatedAtTime(root, expirationTime); } return root; } -// Use this function, along with runRootCallback, to ensure that only a single -// callback per root is scheduled. It's still possible to call renderRoot -// directly, but scheduling via this function helps avoid excessive callbacks. -// It works by storing the callback node and expiration time on the root. When a -// new callback comes in, it compares the expiration time to determine if it -// should cancel the previous one. It also relies on commitRoot scheduling a -// callback to render the next level, because that means we don't need a -// separate callback per expiration time. -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - var existingCallbackExpirationTime = root.callbackExpirationTime; - if (existingCallbackExpirationTime < expirationTime) { - // New callback has higher priority than the existing one. - var existingCallbackNode = root.callbackNode; - if (existingCallbackNode !== null) { - cancelCallback(existingCallbackNode); - } - root.callbackExpirationTime = expirationTime; - - if (expirationTime === Sync) { - // Sync React callbacks are scheduled on a special internal queue - root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - ); - } else { - var options = null; - if ( - !disableSchedulerTimeoutBasedOnReactExpirationTime && - expirationTime !== Never - ) { - var timeout = expirationTimeToMs(expirationTime) - now(); - options = { timeout: timeout }; - } - - root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - options - ); - if ( - enableUserTimingAPI && - expirationTime !== Sync && - (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - // Scheduled an async callback, and we're not already working. Add an - // entry to the flamegraph that shows we're waiting for a callback - // to fire. - startRequestCallbackTimer(); - } - } +function getNextRootExpirationTimeToWorkOn(root) { + // Determines the next expiration time that the root should render, taking + // into account levels that may be suspended, or levels that may have + // received a ping. + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + return lastExpiredTime; + } // "Pending" refers to any update that hasn't committed yet, including if it + // suspended. The "suspended" range is therefore a subset. + + var firstPendingTime = root.firstPendingTime; + + if (!isRootSuspendedAtTime(root, firstPendingTime)) { + // The highest priority pending time is not suspended. Let's work on that. + return firstPendingTime; + } // If the first pending time is suspended, check if there's a lower priority + // pending level that we know about. Or check if we received a ping. Work + // on whichever is higher priority. + + var lastPingedTime = root.lastPingedTime; + var nextKnownPendingLevel = root.nextKnownPendingLevel; + return lastPingedTime > nextKnownPendingLevel + ? lastPingedTime + : nextKnownPendingLevel; +} // Use this function to schedule a task for a root. There's only one task per +// root; if a task was already scheduled, we'll check to make sure the +// expiration time of the existing task is the same as the expiration time of +// the next level that the root has work on. This function is called on every +// update, and right before exiting a task. + +function ensureRootIsScheduled(root) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + // Special case: Expired work should flush synchronously. + root.callbackExpirationTime = Sync; + root.callbackPriority = ImmediatePriority; + root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + ); + return; } - // Associate the current interactions with this new root+priority. - schedulePendingInteractions(root, expirationTime); -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + var existingCallbackNode = root.callbackNode; -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode; - var continuation = null; - try { - continuation = callback(isSync); - if (continuation !== null) { - return runRootCallback.bind(null, root, continuation); - } else { - return null; - } - } finally { - // If the callback exits without returning a continuation, remove the - // corresponding callback node from the root. Unless the callback node - // has changed, which implies that it was already cancelled by a high - // priority update. - if (continuation === null && prevCallbackNode === root.callbackNode) { + if (expirationTime === NoWork) { + // There's nothing to work on. + if (existingCallbackNode !== null) { root.callbackNode = null; root.callbackExpirationTime = NoWork; + root.callbackPriority = NoPriority; } - } -} -function flushDiscreteUpdates() { - // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. - // However, `act` uses `batchedUpdates`, so there's no way to distinguish - // those two cases. Need to fix this before exposing flushDiscreteUpdates - // as a public API. - if ( - (executionContext & (BatchedContext | RenderContext | CommitContext)) !== - NoContext - ) { - if (true && (executionContext & RenderContext) !== NoContext) { - warning$1( - false, - "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + - "already rendering." - ); - } - // We're already rendering, so we can't synchronously flush pending work. - // This is probably a nested event dispatch triggered by a lifecycle/effect, - // like `el.focus()`. Exit. return; - } - flushPendingDiscreteUpdates(); - if (!revertPassiveEffectsChange) { - // If the discrete updates scheduled passive effects, flush them now so that - // they fire before the next serial event. - flushPassiveEffects(); - } -} + } // TODO: If this is an update, we already read the current time. Pass the + // time as an argument. -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - if ( - firstBatch !== null && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ) { - scheduleCallback(NormalPriority, function() { - firstBatch._onComplete(); - return null; - }); - return true; - } else { - return false; - } -} + var currentTime = requestCurrentTime(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); // If there's an existing render task, confirm it has the correct priority and + // expiration time. Otherwise, we'll cancel it and schedule a new one. -function flushPendingDiscreteUpdates() { - if (rootsWithPendingDiscreteUpdates !== null) { - // For each root with pending discrete updates, schedule a callback to - // immediately flush them. - var roots = rootsWithPendingDiscreteUpdates; - rootsWithPendingDiscreteUpdates = null; - roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - }); - // Now flush the immediate queue. - flushSyncCallbackQueue(); - } -} + if (existingCallbackNode !== null) { + var existingCallbackPriority = root.callbackPriority; + var existingCallbackExpirationTime = root.callbackExpirationTime; -function batchedUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + if ( + // Callback must have the exact same expiration time. + existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority. + existingCallbackPriority >= priorityLevel + ) { + // Existing callback is sufficient. + return; + } // Need to schedule a new task. + // TODO: Instead of scheduling a new task, we should be able to change the + // priority of the existing one. -function batchedEventUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= EventContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } + cancelCallback(existingCallbackNode); } -} -function discreteUpdates$1(fn, a, b, c) { - var prevExecutionContext = executionContext; - executionContext |= DiscreteEventContext; - try { - // Should this - return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c)); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + var callbackNode; -function flushSync(fn, a) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - (function() { + if (expirationTime === Sync) { + // Sync React callbacks are scheduled on a special internal queue + callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root) + ); + } else { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects + // ordering because tasks are processed in timeout order. { - throw ReactError( - Error( - "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." - ) - ); + timeout: expirationTimeToMs(expirationTime) - now() } - })(); - } - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return runWithPriority$1(ImmediatePriority, fn.bind(null, a)); - } finally { - executionContext = prevExecutionContext; - // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - flushSyncCallbackQueue(); + ); } -} -function prepareFreshStack(root, expirationTime) { - root.finishedWork = null; - root.finishedExpirationTime = NoWork; + root.callbackNode = callbackNode; +} // This is the entry point for every concurrent task, i.e. anything that +// goes through Scheduler. - var timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; - // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - cancelTimeout(timeoutHandle); - } +function performConcurrentWorkOnRoot(root, didTimeout) { + // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. + currentEventTime = NoWork; - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - while (interruptedWork !== null) { - unwindInterruptedWork(interruptedWork); - interruptedWork = interruptedWork.return; - } - } - workInProgressRoot = root; - workInProgress = createWorkInProgress(root.current, null, expirationTime); - renderExpirationTime = expirationTime; - workInProgressRootExitStatus = RootIncomplete; - workInProgressRootLatestProcessedExpirationTime = Sync; - workInProgressRootLatestSuspenseTimeout = Sync; - workInProgressRootCanSuspendUsingConfig = null; - workInProgressRootHasPendingPing = false; + if (didTimeout) { + // The render task took too long to complete. Mark the current time as + // expired to synchronously render all expired work in a single batch. + var currentTime = requestCurrentTime(); + markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback. - if (enableSchedulerTracing) { - spawnedWorkDuringRender = null; - } + ensureRootIsScheduled(root); + return null; + } // Determine the next expiration time to work on, using the fields stored + // on the root. - { - ReactStrictModeWarnings.discardPendingWarnings(); - componentsThatTriggeredHighPriSuspend = null; - } -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + + if (expirationTime !== NoWork) { + var originalCallbackNode = root.callbackNode; -function renderRoot(root, expirationTime, isSync) { - (function() { if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); + throw Error("Should not already be working."); } - })(); - if (enableUserTimingAPI && expirationTime !== Sync) { - var didExpire = isSync; - stopRequestCallbackTimer(didExpire); - } + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root.firstPendingTime < expirationTime) { - // If there's no work left at this expiration time, exit immediately. This - // happens when multiple callbacks are scheduled for a single root, but an - // earlier callback flushes the work of a later one. - return null; - } + if ( + root !== workInProgressRoot || + expirationTime !== renderExpirationTime + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. - if (isSync && root.finishedExpirationTime === expirationTime) { - // There's already a pending commit at this expiration time. - // TODO: This is poorly factored. This case only exists for the - // batch.commit() API. - return commitRoot.bind(null, root); - } + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); - flushPassiveEffects(); + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - // If the root or expiration time have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) { - prepareFreshStack(root, expirationTime); - startWorkOnPendingInteractions(root, expirationTime); - } else if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // We could've received an update at a lower priority while we yielded. - // We're suspended in a delayed state. Once we complete this render we're - // just going to try to recover at the last pending time anyway so we might - // as well start doing that eagerly. - // Ideally we should be able to do this even for retries but we don't yet - // know if we're going to process an update which wants to commit earlier, - // and this path happens very early so it would happen too often. Instead, - // for that case, we'll wait until we complete. - if (workInProgressRootHasPendingPing) { - // We have a ping at this expiration. Let's restart to see if we get unblocked. - prepareFreshStack(root, expirationTime); - } else { - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately, while preserving the position in the queue. - return renderRoot.bind(null, root, lastPendingTime); + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (enableSchedulerTracing) { + popInteractions(prevInteractions); } - } - } - // If we have a work-in-progress fiber, it means there's still work to do - // in this root. - if (workInProgress !== null) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - prevDispatcher = ContextOnlyDispatcher; - } - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - startWorkLoopTimer(workInProgress); - - // TODO: Fork renderRoot into renderRootSync and renderRootAsync - if (isSync) { - if (expirationTime !== Sync) { - // An async update expired. There may be other expired updates on - // this root. We should render all the expired work in a - // single batch. - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) { - // Restart at the current time. - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } - return renderRoot.bind(null, root, currentTime); - } + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; } - } else { - // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - currentEventTime = NoWork; - } - - do { - try { - if (isSync) { - workLoopSync(); - } else { - workLoop(); - } - break; - } catch (thrownValue) { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooks(); - - var sourceFiber = workInProgress; - if (sourceFiber === null || sourceFiber.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - prepareFreshStack(root, expirationTime); - executionContext = prevExecutionContext; - throw thrownValue; - } - - if (enableProfilerTimer && sourceFiber.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true); - } - var returnFiber = sourceFiber.return; - throwException( + if (workInProgress !== null) { + // There's still work left over. Exit without committing. + stopInterruptedWorkLoopTimer(); + } else { + // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. + stopFinishedWorkLoopTimer(); + var finishedWork = (root.finishedWork = root.current.alternate); + root.finishedExpirationTime = expirationTime; + finishConcurrentRender( root, - returnFiber, - sourceFiber, - thrownValue, - renderExpirationTime + finishedWork, + workInProgressRootExitStatus, + expirationTime ); - workInProgress = completeUnitOfWork(sourceFiber); } - } while (true); - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } + ensureRootIsScheduled(root); - if (workInProgress !== null) { - // There's still work left over. Return a continuation. - stopInterruptedWorkLoopTimer(); - if (expirationTime !== Sync) { - startRequestCallbackTimer(); + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); } - return renderRoot.bind(null, root, expirationTime); } } - // We now have a consistent tree. The next step is either to commit it, or, if - // something suspended, wait to commit it after a timeout. - stopFinishedWorkLoopTimer(); - - root.finishedWork = root.current.alternate; - root.finishedExpirationTime = expirationTime; - - var isLocked = resolveLocksOnRoot(root, expirationTime); - if (isLocked) { - // This root has a lock that prevents it from committing. Exit. If we begin - // work on the root again, without any intervening updates, it will finish - // without doing additional work. - return null; - } + return null; +} +function finishConcurrentRender( + root, + finishedWork, + exitStatus, + expirationTime +) { // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: { - (function() { - { - throw ReactError(Error("Should have a work-in-progress.")); - } - })(); + switch (exitStatus) { + case RootIncomplete: + case RootFatalErrored: { + { + throw Error("Root did not complete. This is a bug in React."); + } } - // Flow knows about invariant, so it complains if I add a break statement, - // but eslint doesn't know about invariant, so it complains if I do. - // eslint-disable-next-line no-fallthrough + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + case RootErrored: { - // An error was thrown. First check if there is lower priority work - // scheduled on this root. - var _lastPendingTime = root.lastPendingTime; - if (_lastPendingTime < expirationTime) { - // There's lower priority work. Before raising the error, try rendering - // at the lower priority to see if it fixes it. Use a continuation to - // maintain the existing priority and position in the queue. - return renderRoot.bind(null, root, _lastPendingTime); - } - if (!isSync) { - // If we're rendering asynchronously, it's possible the error was - // caused by tearing due to a mutation during an event. Try rendering - // one more time without yiedling to events. - prepareFreshStack(root, expirationTime); - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - return null; - } - // If we're already rendering synchronously, commit the root in its - // errored state. - return commitRoot.bind(null, root); + // If this was an async render, the error may have happened due to + // a mutation in a concurrent event. Try rendering one more time, + // synchronously, to see if the error goes away. If there are + // lower priority updates, let's include those, too, in case they + // fix the inconsistency. Render at Idle to include all updates. + // If it was Idle or Never or some not-yet-invented time, render + // at that time. + markRootExpiredAtTime( + root, + expirationTime > Idle ? Idle : expirationTime + ); // We assume that this second render pass will be synchronous + // and therefore not hit this path again. + + break; } + case RootSuspended: { - flushSuspensePriorityWarningInDEV(); + markRootSuspendedAtTime(root, expirationTime); + var lastSuspendedTime = root.lastSuspendedTime; - // We have an acceptable loading state. We need to figure out if we should - // immediately commit it or wait a bit. + if (expirationTime === lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } + + flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. + // If we have processed new updates during this render, we may now + // have a new loading state ready. We want to ensure that we commit + // that as soon as possible. - // If we have processed new updates during this render, we may now have a - // new loading state ready. We want to ensure that we commit that as soon as - // possible. var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync; + if ( - hasNotProcessedNewUpdates && - !isSync && - // do not delay if we're inside an act() scope + hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // If we have not processed any new updates during this pass, then this is - // either a retry of an existing fallback state or a hidden tree. - // Hidden trees shouldn't be batched with other work and after that's - // fixed it can only be a retry. - // We're going to throttle committing retries so that we don't show too - // many loading states too quickly. + // If we have not processed any new updates during this pass, then + // this is either a retry of an existing fallback state or a + // hidden tree. Hidden trees shouldn't be batched with other work + // and after that's fixed it can only be a retry. We're going to + // throttle committing retries so that we don't show too many + // loading states too quickly. var msUntilTimeout = - globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - // Don't bother with a very short suspense time. + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. + if (msUntilTimeout > 10) { if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart + // earlier so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } } - var _lastPendingTime2 = root.lastPendingTime; - if (_lastPendingTime2 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level. - return renderRoot.bind(null, root, _lastPendingTime2); + + var nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (nextTime !== NoWork && nextTime !== expirationTime) { + // There's additional work on this root. + break; } - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + + if ( + lastSuspendedTime !== NoWork && + lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = lastSuspendedTime; + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. + root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootSuspendedWithDelay: { + markRootSuspendedAtTime(root, expirationTime); + var _lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === _lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } + flushSuspensePriorityWarningInDEV(); if ( - !isSync && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // We're suspended in a state that should be avoided. We'll try to avoid committing - // it for as long as the timeouts let us. + // We're suspended in a state that should be avoided. We'll try to + // avoid committing it for as long as the timeouts let us. if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var _lastPingedTime = root.lastPingedTime; + + if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart earlier + // so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + + var _nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (_nextTime !== NoWork && _nextTime !== expirationTime) { + // There's additional work on this root. + break; } - var _lastPendingTime3 = root.lastPendingTime; - if (_lastPendingTime3 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately. - return renderRoot.bind(null, root, _lastPendingTime3); + + if ( + _lastSuspendedTime !== NoWork && + _lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = _lastSuspendedTime; + break; } - var _msUntilTimeout = void 0; + var _msUntilTimeout; + if (workInProgressRootLatestSuspenseTimeout !== Sync) { - // We have processed a suspense config whose expiration time we can use as - // the timeout. + // We have processed a suspense config whose expiration time we + // can use as the timeout. _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now(); } else if (workInProgressRootLatestProcessedExpirationTime === Sync) { - // This should never normally happen because only new updates cause - // delayed states, so we should have processed something. However, - // this could also happen in an offscreen tree. + // This should never normally happen because only new updates + // cause delayed states, so we should have processed something. + // However, this could also happen in an offscreen tree. _msUntilTimeout = 0; } else { - // If we don't have a suspense config, we're going to use a heuristic to + // If we don't have a suspense config, we're going to use a + // heuristic to determine how long we can suspend. var eventTimeMs = inferTimeFromExpirationTime( workInProgressRootLatestProcessedExpirationTime ); @@ -19626,40 +20387,40 @@ function renderRoot(root, expirationTime, isSync) { var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs; var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed < 0) { // We get this wrong some time since we estimate the time. timeElapsed = 0; } - _msUntilTimeout = jnd(timeElapsed) - timeElapsed; - - // Clamp the timeout to the expiration time. - // TODO: Once the event time is exact instead of inferred from expiration time + _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the + // event time is exact instead of inferred from expiration time // we don't need this. + if (timeUntilExpirationMs < _msUntilTimeout) { _msUntilTimeout = timeUntilExpirationMs; } - } + } // Don't bother with a very short suspense time. - // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootCompleted: { // The work completed. Ready to commit. if ( - !isSync && // do not delay if we're inside an act() scope !( true && @@ -19671,139 +20432,497 @@ function renderRoot(root, expirationTime, isSync) { ) { // If we have exceeded the minimum loading delay, which probably // means we have shown a spinner already, we might have to suspend - // a bit longer to ensure that the spinner is shown for enough time. + // a bit longer to ensure that the spinner is shown for + // enough time. var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay( workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig ); + if (_msUntilTimeout2 > 10) { + markRootSuspendedAtTime(root, expirationTime); root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout2 ); - return null; + break; } } - return commitRoot.bind(null, root); + + commitRoot(root); + break; } + default: { - (function() { - { - throw ReactError(Error("Unknown root exit status.")); - } - })(); + { + throw Error("Unknown root exit status."); + } } } -} +} // This is the entry point for synchronous tasks that don't go +// through Scheduler -function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); -} +function performSyncWorkOnRoot(root) { + // Check if there's expired work on this root. Otherwise, render at Sync. + var lastExpiredTime = root.lastExpiredTime; + var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync; + + if (root.finishedExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + // TODO: This is poorly factored. This case only exists for the + // batch.commit() API. + commitRoot(root); + } else { + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } + + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. -function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { - if ( - expirationTime < workInProgressRootLatestProcessedExpirationTime && - expirationTime > Never - ) { - workInProgressRootLatestProcessedExpirationTime = expirationTime; - } - if (suspenseConfig !== null) { if ( - expirationTime < workInProgressRootLatestSuspenseTimeout && - expirationTime > Never + root !== workInProgressRoot || + expirationTime !== renderExpirationTime ) { - workInProgressRootLatestSuspenseTimeout = expirationTime; - // Most of the time we only have one config and getting wrong is not bad. - workInProgressRootCanSuspendUsingConfig = suspenseConfig; + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. + + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); + + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (enableSchedulerTracing) { + popInteractions(prevInteractions); + } + + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; + } + + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + { + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + } else { + // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. + stopFinishedWorkLoopTimer(); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = expirationTime; + finishSyncRender(root, workInProgressRootExitStatus, expirationTime); + } // Before exiting, make sure there's a callback scheduled for the next + // pending level. + + ensureRootIsScheduled(root); } } + + return null; } -function renderDidSuspend() { - if (workInProgressRootExitStatus === RootIncomplete) { - workInProgressRootExitStatus = RootSuspended; +function finishSyncRender(root, exitStatus, expirationTime) { + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + { + if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) { + flushSuspensePriorityWarningInDEV(); + } } + + commitRoot(root); } -function renderDidSuspendDelayIfPossible() { +function flushDiscreteUpdates() { + // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. + // However, `act` uses `batchedUpdates`, so there's no way to distinguish + // those two cases. Need to fix this before exposing flushDiscreteUpdates + // as a public API. if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended + (executionContext & (BatchedContext | RenderContext | CommitContext)) !== + NoContext ) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } -} + if (true && (executionContext & RenderContext) !== NoContext) { + warning$1( + false, + "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + + "already rendering." + ); + } // We're already rendering, so we can't synchronously flush pending work. + // This is probably a nested event dispatch triggered by a lifecycle/effect, + // like `el.focus()`. Exit. -function renderDidError() { - if (workInProgressRootExitStatus !== RootCompleted) { - workInProgressRootExitStatus = RootErrored; + return; } -} -// Called during render to determine if anything has suspended. -// Returns false if we're not sure. -function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootIncomplete; -} + flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that + // they fire before the next serial event. -function inferTimeFromExpirationTime(expirationTime) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; + flushPassiveEffects(); } -function inferTimeFromExpirationTimeWithSuspenseConfig( - expirationTime, - suspenseConfig -) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time by subtracting the timeout - // that was added to the event time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return ( - earliestExpirationTimeMs - - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) - ); +function syncUpdates(fn, a, b, c) { + return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c)); } -function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. - while (workInProgress !== null) { - workInProgress = performUnitOfWork(workInProgress); - } -} +function flushPendingDiscreteUpdates() { + if (rootsWithPendingDiscreteUpdates !== null) { + // For each root with pending discrete updates, schedule a callback to + // immediately flush them. + var roots = rootsWithPendingDiscreteUpdates; + rootsWithPendingDiscreteUpdates = null; + roots.forEach(function(expirationTime, root) { + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); + }); // Now flush the immediate queue. -function workLoop() { - // Perform work until Scheduler asks us to yield - while (workInProgress !== null && !shouldYield()) { - workInProgress = performUnitOfWork(workInProgress); + flushSyncCallbackQueue(); } } -function performUnitOfWork(unitOfWork) { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current$$1 = unitOfWork.alternate; +function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; - startWorkTimer(unitOfWork); - setCurrentFiber(unitOfWork); + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; - var next = void 0; - if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function batchedEventUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= EventContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function discreteUpdates$1(fn, a, b, c) { + var prevExecutionContext = executionContext; + executionContext |= DiscreteEventContext; + + try { + // Should this + return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c)); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} + +function flushSync(fn, a) { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + { + throw Error( + "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." + ); + } + } + + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return runWithPriority$1(ImmediatePriority, fn.bind(null, a)); + } finally { + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. + + flushSyncCallbackQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.finishedWork = null; + root.finishedExpirationTime = NoWork; + var timeoutHandle = root.timeoutHandle; + + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above + + cancelTimeout(timeoutHandle); + } + + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + + while (interruptedWork !== null) { + unwindInterruptedWork(interruptedWork); + interruptedWork = interruptedWork.return; + } + } + + workInProgressRoot = root; + workInProgress = createWorkInProgress(root.current, null, expirationTime); + renderExpirationTime = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; + workInProgressRootLatestProcessedExpirationTime = Sync; + workInProgressRootLatestSuspenseTimeout = Sync; + workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = NoWork; + workInProgressRootHasPendingPing = false; + + if (enableSchedulerTracing) { + spawnedWorkDuringRender = null; + } + + { + ReactStrictModeWarnings.discardPendingWarnings(); + componentsThatTriggeredHighPriSuspend = null; + } +} + +function handleError(root, thrownValue) { + do { + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooks(); + resetCurrentFiber(); + + if (workInProgress === null || workInProgress.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + return null; + } + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true); + } + + throwException( + root, + workInProgress.return, + workInProgress, + thrownValue, + renderExpirationTime + ); + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; + continue; + } // Return to the normal work loop. + + return; + } while (true); +} + +function pushDispatcher(root) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } +} + +function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher.current = prevDispatcher; +} + +function pushInteractions(root) { + if (enableSchedulerTracing) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; + } + + return null; +} + +function popInteractions(prevInteractions) { + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } +} + +function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); +} +function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { + if ( + expirationTime < workInProgressRootLatestProcessedExpirationTime && + expirationTime > Idle + ) { + workInProgressRootLatestProcessedExpirationTime = expirationTime; + } + + if (suspenseConfig !== null) { + if ( + expirationTime < workInProgressRootLatestSuspenseTimeout && + expirationTime > Idle + ) { + workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad. + + workInProgressRootCanSuspendUsingConfig = suspenseConfig; + } + } +} +function markUnprocessedUpdateTime(expirationTime) { + if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) { + workInProgressRootNextUnprocessedUpdateTime = expirationTime; + } +} +function renderDidSuspend() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} +function renderDidSuspendDelayIfPossible() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there's a lower priority update somewhere else in the tree. + + if ( + workInProgressRootNextUnprocessedUpdateTime !== NoWork && + workInProgressRoot !== null + ) { + // Mark the current render as suspended, and then mark that there's a + // pending update. + // TODO: This should immediately interrupt the current render, instead + // of waiting until the next time we yield. + markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime); + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + ); + } +} +function renderDidError() { + if (workInProgressRootExitStatus !== RootCompleted) { + workInProgressRootExitStatus = RootErrored; + } +} // Called during render to determine if anything has suspended. +// Returns false if we're not sure. + +function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootIncomplete; +} + +function inferTimeFromExpirationTime(expirationTime) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; +} + +function inferTimeFromExpirationTimeWithSuspenseConfig( + expirationTime, + suspenseConfig +) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time by subtracting the timeout + // that was added to the event time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return ( + earliestExpirationTimeMs - + (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) + ); +} // The work loop is an extremely hot path. Tell Closure not to inline it. + +/** @noinline */ + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + workInProgress = performUnitOfWork(workInProgress); + } +} +/** @noinline */ + +function workLoopConcurrent() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + workInProgress = performUnitOfWork(workInProgress); + } +} + +function performUnitOfWork(unitOfWork) { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current$$1 = unitOfWork.alternate; + startWorkTimer(unitOfWork); + setCurrentFiber(unitOfWork); + var next; + + if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); } resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { // If this doesn't spawn new work, complete the current work. next = completeUnitOfWork(unitOfWork); @@ -19817,17 +20936,18 @@ function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. workInProgress = unitOfWork; + do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = workInProgress.alternate; - var returnFiber = workInProgress.return; + var returnFiber = workInProgress.return; // Check if the work completed or if something threw. - // Check if the work completed or if something threw. if ((workInProgress.effectTag & Incomplete) === NoEffect) { setCurrentFiber(workInProgress); var next = void 0; + if ( !enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode @@ -19835,10 +20955,11 @@ function completeUnitOfWork(unitOfWork) { next = completeWork(current$$1, workInProgress, renderExpirationTime); } else { startProfilerTimer(workInProgress); - next = completeWork(current$$1, workInProgress, renderExpirationTime); - // Update render duration assuming we didn't error. + next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); } + stopWorkTimer(workInProgress); resetCurrentFiber(); resetChildExpirationTime(workInProgress); @@ -19849,8 +20970,7 @@ function completeUnitOfWork(unitOfWork) { } if ( - returnFiber !== null && - // Do not append effects to parents if a sibling failed to complete + returnFiber !== null && // Do not append effects to parents if a sibling failed to complete (returnFiber.effectTag & Incomplete) === NoEffect ) { // Append all the effects of the subtree and this fiber onto the effect @@ -19859,30 +20979,31 @@ function completeUnitOfWork(unitOfWork) { if (returnFiber.firstEffect === null) { returnFiber.firstEffect = workInProgress.firstEffect; } + if (workInProgress.lastEffect !== null) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; } - returnFiber.lastEffect = workInProgress.lastEffect; - } - // If this fiber had side-effects, we append it AFTER the children's + returnFiber.lastEffect = workInProgress.lastEffect; + } // If this fiber had side-effects, we append it AFTER the children's // side-effects. We can perform certain side-effects earlier if needed, // by doing multiple passes over the effect list. We don't want to // schedule our own side-effect on our own list because if end up // reusing children we'll schedule this effect onto itself since we're // at the end. - var effectTag = workInProgress.effectTag; - // Skip both NoWork and PerformedWork tags when creating the effect + var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect // list. PerformedWork effect is read by React DevTools but shouldn't be // committed. + if (effectTag > PerformedWork) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress; } else { returnFiber.firstEffect = workInProgress; } + returnFiber.lastEffect = workInProgress; } } @@ -19890,24 +21011,23 @@ function completeUnitOfWork(unitOfWork) { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. - var _next = unwindWork(workInProgress, renderExpirationTime); - - // Because this fiber did not complete, don't reset its expiration time. + var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time. if ( enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode ) { // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing. - // Include the time spent working on failed children before continuing. var actualDuration = workInProgress.actualDuration; var child = workInProgress.child; + while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } + workInProgress.actualDuration = actualDuration; } @@ -19922,6 +21042,7 @@ function completeUnitOfWork(unitOfWork) { _next.effectTag &= HostEffectMask; return _next; } + stopWorkTimer(workInProgress); if (returnFiber !== null) { @@ -19932,21 +21053,30 @@ function completeUnitOfWork(unitOfWork) { } var siblingFiber = workInProgress.sibling; + if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; - } - // Otherwise, return to the parent + } // Otherwise, return to the parent + workInProgress = returnFiber; - } while (workInProgress !== null); + } while (workInProgress !== null); // We've reached the root. - // We've reached the root. if (workInProgressRootExitStatus === RootIncomplete) { workInProgressRootExitStatus = RootCompleted; } + return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + var childExpirationTime = fiber.childExpirationTime; + return updateExpirationTime > childExpirationTime + ? updateExpirationTime + : childExpirationTime; +} + function resetChildExpirationTime(completedWork) { if ( renderExpirationTime !== Never && @@ -19957,55 +21087,62 @@ function resetChildExpirationTime(completedWork) { return; } - var newChildExpirationTime = NoWork; + var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time. - // Bubble up the earliest expiration time. if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - - // When a fiber is cloned, its actualDuration is reset to 0. This value will + var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. + var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child; - var child = completedWork.child; + while (child !== null) { var childUpdateExpirationTime = child.expirationTime; var childChildExpirationTime = child.childExpirationTime; + if (childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = childUpdateExpirationTime; } + if (childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = childChildExpirationTime; } + if (shouldBubbleActualDurations) { actualDuration += child.actualDuration; } + treeBaseDuration += child.treeBaseDuration; child = child.sibling; } + completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; + while (_child !== null) { var _childUpdateExpirationTime = _child.expirationTime; var _childChildExpirationTime = _child.childExpirationTime; + if (_childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childUpdateExpirationTime; } + if (_childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childChildExpirationTime; } + _child = _child.sibling; } } @@ -20019,14 +21156,6 @@ function commitRoot(root) { ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel) ); - // If there are passive effects, schedule a callback to flush them. This goes - // outside commitRootImpl so that it inherits the priority of the render. - if (rootWithPendingPassiveEffects !== null) { - scheduleCallback(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } return null; } @@ -20034,51 +21163,42 @@ function commitRootImpl(root, renderPriorityLevel) { flushPassiveEffects(); flushRenderPhaseStrictModeWarningsInDEV(); - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } var finishedWork = root.finishedWork; var expirationTime = root.finishedExpirationTime; + if (finishedWork === null) { return null; } + root.finishedWork = null; root.finishedExpirationTime = NoWork; - (function() { - if (!(finishedWork !== root.current)) { - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - - // commitRoot never returns a continuation; it always finishes synchronously. + if (!(finishedWork !== root.current)) { + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. + root.callbackNode = null; root.callbackExpirationTime = NoWork; - - startCommitTimer(); - - // Update the first and last pending times on this root. The new first + root.callbackPriority = NoPriority; + root.nextKnownPendingLevel = NoWork; + startCommitTimer(); // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime; - var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - var firstPendingTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = firstPendingTimeBeforeCommit; - if (firstPendingTimeBeforeCommit < root.lastPendingTime) { - // This usually means we've finished all the work, but it can also happen - // when something gets downprioritized during render, like a hidden tree. - root.lastPendingTime = firstPendingTimeBeforeCommit; - } + + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + markRootFinishedAtTime( + root, + expirationTime, + remainingExpirationTimeBeforeCommit + ); if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -20086,13 +21206,13 @@ function commitRootImpl(root, renderPriorityLevel) { workInProgress = null; renderExpirationTime = NoWork; } else { - } - // This indicates that the last root we worked on is not the same one that + } // This indicates that the last root we worked on is not the same one that // we're committing now. This most commonly happens when a suspended root // times out. - // Get the list of effects. - var firstEffect = void 0; + + var firstEffect; + if (finishedWork.effectTag > PerformedWork) { // A fiber's effect list consists only of its children, not itself. So if // the root has an effect, we need to add it to the end of the list. The @@ -20112,85 +21232,82 @@ function commitRootImpl(root, renderPriorityLevel) { if (firstEffect !== null) { var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } + var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles - // Reset this to null before calling lifecycles - ReactCurrentOwner$2.current = null; - - // The commit phase is broken into several sub-phases. We do a separate pass + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. + startCommitSnapshotEffectsTimer(); prepareForCommit(root.containerInfo); nextEffect = firstEffect; + do { { invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); + stopCommitSnapshotEffectsTimer(); if (enableProfilerTimer) { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. - // The next phase is the mutation phase, where we mutate the host tree. startCommitHostEffectsTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( null, commitMutationEffects, null, + root, renderPriorityLevel ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitHostEffectsTimer(); - resetAfterCommit(root.containerInfo); - // The work-in-progress tree is now the current tree. This must come after + stopCommitHostEffectsTimer(); + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. - root.current = finishedWork; - // The next phase is the layout phase, where we call effects that read + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read // the host tree after it's been mutated. The idiomatic use case for this is // layout, but class component lifecycles also fire here for legacy reasons. + startCommitLifeCyclesTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( @@ -20200,41 +21317,44 @@ function commitRootImpl(root, renderPriorityLevel) { root, expirationTime ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error2 = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error2); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitLifeCyclesTimer(); - - nextEffect = null; - // Tell Scheduler to yield at the end of the frame, so the browser has an + stopCommitLifeCyclesTimer(); + nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an // opportunity to paint. + requestPaint(); if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); } + executionContext = prevExecutionContext; } else { // No effects. - root.current = finishedWork; - // Measure these anyway so the flamegraph explicitly shows that there were + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. + startCommitSnapshotEffectsTimer(); stopCommitSnapshotEffectsTimer(); + if (enableProfilerTimer) { recordCommitTime(); } + startCommitHostEffectsTimer(); stopCommitHostEffectsTimer(); startCommitLifeCyclesTimer(); @@ -20242,7 +21362,6 @@ function commitRootImpl(root, renderPriorityLevel) { } stopCommitTimer(); - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { @@ -20257,26 +21376,22 @@ function commitRootImpl(root, renderPriorityLevel) { // nextEffect pointers to assist with GC. If we have passive effects, we'll // clear this in flushPassiveEffects. nextEffect = firstEffect; + while (nextEffect !== null) { var nextNextEffect = nextEffect.nextEffect; nextEffect.nextEffect = null; nextEffect = nextNextEffect; } - } + } // Check if there's remaining work on this root - // Check if there's remaining work on this root var remainingExpirationTime = root.firstPendingTime; - if (remainingExpirationTime !== NoWork) { - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - remainingExpirationTime - ); + if (remainingExpirationTime !== NoWork) { if (enableSchedulerTracing) { if (spawnedWorkDuringRender !== null) { var expirationTimes = spawnedWorkDuringRender; spawnedWorkDuringRender = null; + for (var i = 0; i < expirationTimes.length; i++) { scheduleInteractions( root, @@ -20285,9 +21400,9 @@ function commitRootImpl(root, renderPriorityLevel) { ); } } - } - scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + schedulePendingInteractions(root, remainingExpirationTime); + } } else { // If there's no remaining work, we can clear the set of already failed // error boundaries. @@ -20304,8 +21419,6 @@ function commitRootImpl(root, renderPriorityLevel) { } } - onCommitRoot(finishedWork.stateNode, expirationTime); - if (remainingExpirationTime === Sync) { // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. @@ -20319,6 +21432,11 @@ function commitRootImpl(root, renderPriorityLevel) { nestedUpdateCount = 0; } + onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. + + ensureRootIsScheduled(root); + if (hasUncaughtError) { hasUncaughtError = false; var _error3 = firstUncaughtError; @@ -20332,33 +21450,44 @@ function commitRootImpl(root, renderPriorityLevel) { // synchronously, but layout updates should be deferred until the end // of the batch. return null; - } + } // If layout work was scheduled, flush it now. - // If layout work was scheduled, flush it now. flushSyncCallbackQueue(); return null; } function commitBeforeMutationEffects() { while (nextEffect !== null) { - if ((nextEffect.effectTag & Snapshot) !== NoEffect) { + var effectTag = nextEffect.effectTag; + + if ((effectTag & Snapshot) !== NoEffect) { setCurrentFiber(nextEffect); recordEffect(); - var current$$1 = nextEffect.alternate; commitBeforeMutationLifeCycles(current$$1, nextEffect); - resetCurrentFiber(); } + + if ((effectTag & Passive) !== NoEffect) { + // If there are passive effects, schedule a callback to flush at + // the earliest opportunity. + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + nextEffect = nextEffect.nextEffect; } } -function commitMutationEffects(renderPriorityLevel) { +function commitMutationEffects(root, renderPriorityLevel) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & ContentReset) { @@ -20367,52 +21496,67 @@ function commitMutationEffects(renderPriorityLevel) { if (effectTag & Ref) { var current$$1 = nextEffect.alternate; + if (current$$1 !== null) { commitDetachRef(current$$1); } - } - - // The following switch statement is only concerned about placement, + } // The following switch statement is only concerned about placement, // updates, and deletions. To avoid needing to add a case for every possible // bitmap value, we remove the secondary effects from the effect tag and // switch on that value. - var primaryEffectTag = effectTag & (Placement | Update | Deletion); + + var primaryEffectTag = + effectTag & (Placement | Update | Deletion | Hydrating); + switch (primaryEffectTag) { case Placement: { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. + nextEffect.effectTag &= ~Placement; break; } + case PlacementAndUpdate: { // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - // Update + nextEffect.effectTag &= ~Placement; // Update + var _current = nextEffect.alternate; commitWork(_current, nextEffect); break; } - case Update: { + + case Hydrating: { + nextEffect.effectTag &= ~Hydrating; + break; + } + + case HydratingAndUpdate: { + nextEffect.effectTag &= ~Hydrating; // Update + var _current2 = nextEffect.alternate; commitWork(_current2, nextEffect); break; } + + case Update: { + var _current3 = nextEffect.alternate; + commitWork(_current3, nextEffect); + break; + } + case Deletion: { - commitDeletion(nextEffect, renderPriorityLevel); + commitDeletion(root, nextEffect, renderPriorityLevel); break; } - } + } // TODO: Only record a mutation effect if primaryEffectTag is non-zero. - // TODO: Only record a mutation effect if primaryEffectTag is non-zero. recordEffect(); - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } @@ -20422,7 +21566,6 @@ function commitLayoutEffects(root, committedExpirationTime) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) { @@ -20436,88 +21579,78 @@ function commitLayoutEffects(root, committedExpirationTime) { commitAttachRef(nextEffect); } - if (effectTag & Passive) { - rootDoesHavePassiveEffects = true; - } - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } } function flushPassiveEffects() { + if (pendingPassiveEffectsRenderPriority !== NoPriority) { + var priorityLevel = + pendingPassiveEffectsRenderPriority > NormalPriority + ? NormalPriority + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = NoPriority; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} + +function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } + var root = rootWithPendingPassiveEffects; var expirationTime = pendingPassiveEffectsExpirationTime; - var renderPriorityLevel = pendingPassiveEffectsRenderPriority; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = NoWork; - pendingPassiveEffectsRenderPriority = NoPriority; - var priorityLevel = - renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; - return runWithPriority$1( - priorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Cannot flush passive effects while already rendering."); } - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); - } - })(); var prevExecutionContext = executionContext; executionContext |= CommitContext; - - // Note: This currently assumes there are no passive effects on the root + var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root // fiber, because the root is not part of its own effect list. This could // change in the future. + var effect = root.current.firstEffect; + while (effect !== null) { { setCurrentFiber(effect); invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + if (hasCaughtError()) { - (function() { - if (!(effect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(effect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(effect, error); } + resetCurrentFiber(); } - var nextNextEffect = effect.nextEffect; - // Remove nextEffect pointer to assist GC + + var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC + effect.nextEffect = null; effect = nextNextEffect; } if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); finishPendingInteractions(root, expirationTime); } executionContext = prevExecutionContext; - flushSyncCallbackQueue(); - - // If additional passive effects were scheduled, increment a counter. If this + flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; - return true; } @@ -20527,7 +21660,6 @@ function isAlreadyFailedLegacyErrorBoundary(instance) { legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } - function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); @@ -20542,6 +21674,7 @@ function prepareToThrowUncaughtError(error) { firstUncaughtError = error; } } + var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { @@ -20549,8 +21682,10 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); enqueueUpdate(rootFiber, update); var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } } @@ -20563,6 +21698,7 @@ function captureCommitPhaseError(sourceFiber, error) { } var fiber = sourceFiber.return; + while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); @@ -20570,6 +21706,7 @@ function captureCommitPhaseError(sourceFiber, error) { } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; + if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && @@ -20578,24 +21715,27 @@ function captureCommitPhaseError(sourceFiber, error) { var errorInfo = createCapturedValue(error, sourceFiber); var update = createClassErrorUpdate( fiber, - errorInfo, - // TODO: This is always sync + errorInfo, // TODO: This is always sync Sync ); enqueueUpdate(fiber, update); var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } + return; } } + fiber = fiber.return; } } - function pingSuspendedRoot(root, thenable, suspendedTime) { var pingCache = root.pingCache; + if (pingCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. @@ -20606,10 +21746,8 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. - // If we're suspended with delay, we'll always suspend so we can always // restart. If we're suspended without any updates, it might be a retry. // If it's early in the retry we can restart. We can't know for sure @@ -20630,23 +21768,23 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // opportunity later. So we mark this render as having a ping. workInProgressRootHasPendingPing = true; } + return; } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < suspendedTime) { + if (!isRootSuspendedAtTime(root, suspendedTime)) { // The root is no longer suspended at this time. return; } - var pingTime = root.pingTime; - if (pingTime !== NoWork && pingTime < suspendedTime) { + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) { // There's already a lower priority ping scheduled. return; - } + } // Mark the time at which this ping was scheduled. - // Mark the time at which this ping was scheduled. - root.pingTime = suspendedTime; + root.lastPingedTime = suspendedTime; if (root.finishedExpirationTime === suspendedTime) { // If there's a pending fallback waiting to commit, throw it away. @@ -20654,54 +21792,70 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { root.finishedWork = null; } - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - suspendedTime - ); - scheduleCallbackForRoot(root, priorityLevel, suspendedTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, suspendedTime); } -function retryTimedOutBoundary(boundaryFiber) { +function retryTimedOutBoundary(boundaryFiber, retryTime) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new expiration time. - var currentTime = requestCurrentTime(); - var suspenseConfig = null; // Retries don't carry over the already committed update. - var retryTime = computeExpirationForFiber( - currentTime, - boundaryFiber, - suspenseConfig - ); - // TODO: Special case idle priority? - var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + if (retryTime === NoWork) { + var suspenseConfig = null; // Retries don't carry over the already committed update. + + var currentTime = requestCurrentTime(); + retryTime = computeExpirationForFiber( + currentTime, + boundaryFiber, + suspenseConfig + ); + } // TODO: Special case idle priority? + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { - scheduleCallbackForRoot(root, priorityLevel, retryTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, retryTime); } } +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryTime = NoWork; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + + retryTimedOutBoundary(boundaryFiber, retryTime); +} function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = void 0; + var retryTime = NoWork; // Default + + var retryCache; + if (enableSuspenseServerRenderer) { switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + break; - case DehydratedSuspenseComponent: - retryCache = boundaryFiber.memoizedState; + + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; break; - default: - (function() { - { - throw ReactError( - Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ) - ); - } - })(); + + default: { + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } } } else { retryCache = boundaryFiber.stateNode; @@ -20713,10 +21867,8 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); -} - -// Computes the next Just Noticeable Difference (JND) boundary. + retryTimedOutBoundary(boundaryFiber, retryTime); +} // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid @@ -20725,6 +21877,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. + function jnd(timeElapsed) { return timeElapsed < 120 ? 120 @@ -20747,25 +21900,28 @@ function computeMsUntilSuspenseLoadingDelay( suspenseConfig ) { var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0; + if (busyMinDurationMs <= 0) { return 0; } - var busyDelayMs = suspenseConfig.busyDelayMs | 0; - // Compute the time until this render pass would expire. + var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire. + var currentTimeMs = now(); var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig( mostRecentEventTime, suspenseConfig ); var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed <= busyDelayMs) { // If we haven't yet waited longer than the initial delay, we don't // have to wait any additional time. return 0; } - var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; - // This is the value that is passed to `setTimeout`. + + var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`. + return msUntilTimeout; } @@ -20773,15 +21929,12 @@ function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; - (function() { - { - throw ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) - ); - } - })(); + + { + 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." + ); + } } { @@ -20832,9 +21985,11 @@ function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { } var didWarnStateUpdateForUnmountedComponent = null; + function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { { var tag = fiber.tag; + if ( tag !== HostRoot && tag !== ClassComponent && @@ -20845,18 +22000,21 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { ) { // Only warn for user-defined components, not internal ones like Suspense. return; - } - // We show the whole stack but dedupe on the top component's name because + } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent !== null) { if (didWarnStateUpdateForUnmountedComponent.has(componentName)) { return; } + didWarnStateUpdateForUnmountedComponent.add(componentName); } else { didWarnStateUpdateForUnmountedComponent = new Set([componentName]); } + warningWithoutStack$1( false, "Can't perform a React state update on an unmounted component. This " + @@ -20870,20 +22028,22 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { } } -var beginWork$$1 = void 0; +var beginWork$$1; + if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var dummyFiber = null; + beginWork$$1 = function(current$$1, unitOfWork, expirationTime) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV( dummyFiber, unitOfWork ); + try { return beginWork$1(current$$1, unitOfWork, expirationTime); } catch (originalError) { @@ -20894,25 +22054,23 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ) { // Don't replay promises. Treat everything else like an error. throw originalError; - } - - // Keep this code in sync with renderRoot; any changes here must have + } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. - resetContextDependencies(); - resetHooks(); + resetContextDependencies(); + resetHooks(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. // Unwind the failed stack frame - unwindInterruptedWork(unitOfWork); - // Restore the original properties of the fiber. + unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber. + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if (enableProfilerTimer && unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); - } + } // Run beginWork again. - // Run beginWork again. invokeGuardedCallback( null, beginWork$1, @@ -20923,9 +22081,9 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ); if (hasCaughtError()) { - var replayError = clearCaughtError(); - // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. + var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. // Rethrow this error instead of the original one. + throw replayError; } else { // This branch is reachable if the render phase is impure. @@ -20939,6 +22097,7 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInGetChildContext = false; + function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { { if (fiber.tag === ClassComponent) { @@ -20947,16 +22106,19 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { if (didWarnAboutUpdateInGetChildContext) { return; } + warningWithoutStack$1( false, "setState(...): Cannot call setState() inside getChildContext()" ); didWarnAboutUpdateInGetChildContext = true; break; + case "render": if (didWarnAboutUpdateInRender) { return; } + warningWithoutStack$1( false, "Cannot update during an existing state transition (such as " + @@ -20968,11 +22130,11 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { } } } -} - -// a 'shared' variable that changes when act() opens/closes in tests. -var IsThisRendererActing = { current: false }; +} // a 'shared' variable that changes when act() opens/closes in tests. +var IsThisRendererActing = { + current: false +}; function warnIfNotScopedWithMatchingAct(fiber) { { if ( @@ -20999,7 +22161,6 @@ function warnIfNotScopedWithMatchingAct(fiber) { } } } - function warnIfNotCurrentlyActingEffectsInDEV(fiber) { { if ( @@ -21056,11 +22217,9 @@ function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { } } -var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; +var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler. -// In tests, we want to enforce a mocked scheduler. -var didWarnAboutUnmockedScheduler = false; -// TODO Before we release concurrent mode, revisit this and decide whether a mocked +var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked // scheduler is the actual recommendation. The alternative could be a testing build, // a new lib, or whatever; we dunno just yet. This message is for early adopters // to get their tests right. @@ -21095,20 +22254,22 @@ function warnIfUnmockedScheduler(fiber) { } } } - var componentsThatTriggeredHighPriSuspend = null; function checkForWrongSuspensePriorityInDEV(sourceFiber) { { var currentPriorityLevel = getCurrentPriorityLevel(); + if ( (sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$1 || currentPriorityLevel === ImmediatePriority) ) { var workInProgressNode = sourceFiber; + while (workInProgressNode !== null) { // Add the component that triggered the suspense var current$$1 = workInProgressNode.alternate; + if (current$$1 !== null) { // TODO: warn component that triggers the high priority // suspend is the HostRoot @@ -21117,10 +22278,13 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { // Loop through the component's update queue and see whether the component // has triggered any high priority updates var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var update = updateQueue.firstUpdate; + while (update !== null) { var priorityLevel = update.priority; + if ( priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority @@ -21134,12 +22298,16 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + update = update.next; } } + break; + case FunctionComponent: case ForwardRef: case SimpleMemoComponent: @@ -21147,11 +22315,12 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null ) { - var _update = workInProgressNode.memoizedState.baseUpdate; - // Loop through the functional component's memoized state to see whether + var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether // the component has triggered any high pri updates + while (_update !== null) { var priority = _update.priority; + if ( priority === UserBlockingPriority$1 || priority === ImmediatePriority @@ -21165,21 +22334,27 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + if ( _update.next === workInProgressNode.memoizedState.baseUpdate ) { break; } + _update = _update.next; } } + break; + default: break; } } + workInProgressNode = workInProgressNode.return; } } @@ -21205,8 +22380,7 @@ function flushSuspensePriorityWarningInDEV() { "triggers the bulk of the changes." + "\n\n" + "Refer to the documentation for useSuspenseTransition to learn how " + - "to implement this pattern.", - // TODO: Add link to React docs with more information, once it exists + "to implement this pattern.", // TODO: Add link to React docs with more information, once it exists componentNames.sort().join(", ") ); } @@ -21223,6 +22397,7 @@ function markSpawnedWork(expirationTime) { if (!enableSchedulerTracing) { return; } + if (spawnedWorkDuringRender === null) { spawnedWorkDuringRender = [expirationTime]; } else { @@ -21238,6 +22413,7 @@ function scheduleInteractions(root, expirationTime, interactions) { if (interactions.size > 0) { var pendingInteractionMap = root.pendingInteractionMap; var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { interactions.forEach(function(interaction) { if (!pendingInteractions.has(interaction)) { @@ -21248,15 +22424,15 @@ function scheduleInteractions(root, expirationTime, interactions) { pendingInteractions.add(interaction); }); } else { - pendingInteractionMap.set(expirationTime, new Set(interactions)); + pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions. - // Update the pending async work count for the current interactions. interactions.forEach(function(interaction) { interaction.__count++; }); } var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); subscriber.onWorkScheduled(interactions, threadID); @@ -21279,11 +22455,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { // This is called when new work is started on a root. if (!enableSchedulerTracing) { return; - } - - // Determine which interactions this batch of work currently includes, So that + } // Determine which interactions this batch of work currently includes, So that // we can accurately attribute time spent working on it, And so that cascading // work triggered during the render phase will be associated with it. + var interactions = new Set(); root.pendingInteractionMap.forEach(function( scheduledInteractions, @@ -21294,19 +22469,20 @@ function startWorkOnPendingInteractions(root, expirationTime) { return interactions.add(interaction); }); } - }); + }); // Store the current set of interactions on the FiberRoot for a few reasons: + // We can re-use it in hot functions like performConcurrentWorkOnRoot() + // without having to recalculate it. We will also use it in commitWork() to + // pass to any Profiler onRender() hooks. This also provides DevTools with a + // way to access it when the onCommitRoot() hook is called. - // Store the current set of interactions on the FiberRoot for a few reasons: - // We can re-use it in hot functions like renderRoot() without having to - // recalculate it. We will also use it in commitWork() to pass to any Profiler - // onRender() hooks. This also provides DevTools with a way to access it when - // the onCommitRoot() hook is called. root.memoizedInteractions = interactions; if (interactions.size > 0) { var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); + try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { @@ -21325,11 +22501,11 @@ function finishPendingInteractions(root, committedExpirationTime) { } var earliestRemainingTimeAfterCommit = root.firstPendingTime; - - var subscriber = void 0; + var subscriber; try { subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { var threadID = computeThreadID(root, committedExpirationTime); subscriber.onWorkStopped(root.memoizedInteractions, threadID); @@ -21353,7 +22529,6 @@ function finishPendingInteractions(root, committedExpirationTime) { // That indicates that we are waiting for suspense data. if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { pendingInteractionMap.delete(scheduledExpirationTime); - scheduledInteractions.forEach(function(interaction) { interaction.__count--; @@ -21376,21 +22551,22 @@ function finishPendingInteractions(root, committedExpirationTime) { var onCommitFiberRoot = null; var onCommitFiberUnmount = null; var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; - function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { // No DevTools return false; } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } + if (!hook.supportsFiber) { { warningWithoutStack$1( @@ -21399,16 +22575,18 @@ function injectInternals(internals) { "with the current version of React. Please update React DevTools. " + "https://fb.me/react-devtools" ); - } - // DevTools exists, even though it doesn't support Fiber. + } // DevTools exists, even though it doesn't support Fiber. + return true; } + try { - var rendererID = hook.inject(internals); - // We have successfully injected, so now it is safe to set up hooks. + var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. + onCommitFiberRoot = function(root, expirationTime) { try { var didError = (root.current.effectTag & DidCapture) === DidCapture; + if (enableProfilerTimer) { var currentTime = requestCurrentTime(); var priorityLevel = inferPriorityFromExpirationTime( @@ -21430,6 +22608,7 @@ function injectInternals(internals) { } } }; + onCommitFiberUnmount = function(fiber) { try { hook.onCommitFiberUnmount(rendererID, fiber); @@ -21453,34 +22632,33 @@ function injectInternals(internals) { err ); } - } - // DevTools exists + } // DevTools exists + return true; } - function onCommitRoot(root, expirationTime) { if (typeof onCommitFiberRoot === "function") { onCommitFiberRoot(root, expirationTime); } } - function onCommitUnmount(fiber) { if (typeof onCommitFiberUnmount === "function") { onCommitFiberUnmount(fiber); } } -var hasBadMapPolyfill = void 0; +var hasBadMapPolyfill; { hasBadMapPolyfill = false; + try { var nonExtensibleObject = Object.preventExtensions({}); var testMap = new Map([[nonExtensibleObject, null]]); - var testSet = new Set([nonExtensibleObject]); - // This is necessary for Rollup to not consider these unused. + var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. + testMap.set(0, 0); testSet.add(0); } catch (e) { @@ -21489,14 +22667,7 @@ var hasBadMapPolyfill = void 0; } } -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. - -var debugCounter = void 0; - -{ - debugCounter = 1; -} +var debugCounter = 1; function FiberNode(tag, pendingProps, key, mode) { // Instance @@ -21504,34 +22675,26 @@ function FiberNode(tag, pendingProps, key, mode) { this.key = key; this.elementType = null; this.type = null; - this.stateNode = null; + this.stateNode = null; // Fiber - // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; + this.mode = mode; // Effects - this.mode = mode; - - // Effects this.effectTag = NoEffect; this.nextEffect = null; - this.firstEffect = null; this.lastEffect = null; - this.expirationTime = NoWork; this.childExpirationTime = NoWork; - this.alternate = null; if (enableProfilerTimer) { @@ -21550,31 +22713,33 @@ function FiberNode(tag, pendingProps, key, mode) { this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - - // It's okay to replace the initial doubles with smis after initialization. + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). + this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; + } // This is normally DEV-only except www when it adds listeners. + // TODO: remove the User Timing integration in favor of Root Events. + + if (enableUserTimingAPI) { + this._debugID = debugCounter++; + this._debugIsCurrentlyTiming = false; } { - this._debugID = debugCounter++; this._debugSource = null; this._debugOwner = null; - this._debugIsCurrentlyTiming = false; this._debugNeedsRemount = false; this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } } -} - -// This is a constructor function, rather than a POJO constructor, still +} // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost @@ -21587,6 +22752,7 @@ function FiberNode(tag, pendingProps, key, mode) { // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. + var createFiber = function(tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); @@ -21604,25 +22770,27 @@ function isSimpleFunctionComponent(type) { type.defaultProps === undefined ); } - function resolveLazyComponentTag(Component) { if (typeof Component === "function") { return shouldConstruct(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; + if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } + if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } + return IndeterminateComponent; -} +} // This is used to create an alternate fiber to do work on. -// This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps, expirationTime) { var workInProgress = current.alternate; + if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused @@ -21650,13 +22818,11 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.alternate = current; current.alternate = workInProgress; } else { - workInProgress.pendingProps = pendingProps; - - // We already have an alternate. + workInProgress.pendingProps = pendingProps; // We already have an alternate. // Reset the effect tag. - workInProgress.effectTag = NoEffect; - // The effect list is no longer valid. + workInProgress.effectTag = NoEffect; // The effect list is no longer valid. + workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; @@ -21673,14 +22839,12 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21689,9 +22853,8 @@ function createWorkInProgress(current, pendingProps, expirationTime) { expirationTime: currentDependencies.expirationTime, firstContext: currentDependencies.firstContext, responders: currentDependencies.responders - }; + }; // These will be overridden during the parent's reconciliation - // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; @@ -21703,56 +22866,54 @@ function createWorkInProgress(current, pendingProps, expirationTime) { { workInProgress._debugNeedsRemount = current._debugNeedsRemount; + switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; + case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; + case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; + default: break; } } return workInProgress; -} +} // Used to reuse a Fiber for a second pass. -// Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderExpirationTime) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. - // Reset the effect tag but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. - workInProgress.effectTag &= Placement; + workInProgress.effectTag &= Placement; // The effect list is no longer valid. - // The effect list is no longer valid. workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; - var current = workInProgress.alternate; + if (current === null) { // Reset to createFiber's initial values. workInProgress.childExpirationTime = NoWork; workInProgress.expirationTime = renderExpirationTime; - workInProgress.child = null; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; - workInProgress.dependencies = null; if (enableProfilerTimer) { @@ -21765,14 +22926,12 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21793,9 +22952,9 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { return workInProgress; } - function createHostRootFiber(tag) { - var mode = void 0; + var mode; + if (tag === ConcurrentRoot) { mode = ConcurrentMode | BatchedMode | StrictMode; } else if (tag === BatchedRoot) { @@ -21813,7 +22972,6 @@ function createHostRootFiber(tag) { return createFiber(HostRoot, null, null, mode); } - function createFiberFromTypeAndProps( type, // React$ElementType key, @@ -21822,14 +22980,15 @@ function createFiberFromTypeAndProps( mode, expirationTime ) { - var fiber = void 0; + var fiber; + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - var fiberTag = IndeterminateComponent; - // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; + if (typeof type === "function") { if (shouldConstruct(type)) { fiberTag = ClassComponent; + { resolvedType = resolveClassForHotReloading(resolvedType); } @@ -21849,18 +23008,23 @@ function createFiberFromTypeAndProps( expirationTime, key ); + case REACT_CONCURRENT_MODE_TYPE: fiberTag = Mode; mode |= ConcurrentMode | BatchedMode | StrictMode; break; + case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictMode; break; + case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList( pendingProps, @@ -21868,29 +23032,37 @@ function createFiberFromTypeAndProps( expirationTime, key ); + default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; + case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; + case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; + { resolvedType = resolveForwardRefForHotReloading(resolvedType); } + break getTag; + case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; + case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_FUNDAMENTAL_TYPE: if (enableFundamentalAPI) { return createFiberFromFundamental( @@ -21901,10 +23073,24 @@ function createFiberFromTypeAndProps( key ); } + break; + + case REACT_SCOPE_TYPE: + if (enableScopeAPI) { + return createFiberFromScope( + type, + pendingProps, + mode, + expirationTime, + key + ); + } } } + var info = ""; + { if ( type === undefined || @@ -21917,23 +23103,22 @@ function createFiberFromTypeAndProps( "it's defined in, or you might have mixed up default and " + "named imports."; } + var ownerName = owner ? getComponentName(owner.type) : null; + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } } - (function() { - { - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (type == null ? type : typeof type) + - "." + - info - ) - ); - } - })(); + + { + 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 + ); + } } } } @@ -21942,15 +23127,15 @@ function createFiberFromTypeAndProps( fiber.elementType = type; fiber.type = resolvedType; fiber.expirationTime = expirationTime; - return fiber; } - function createFiberFromElement(element, mode, expirationTime) { var owner = null; + { owner = element._owner; } + var type = element.type; var key = element.key; var pendingProps = element.props; @@ -21962,19 +23147,19 @@ function createFiberFromElement(element, mode, expirationTime) { mode, expirationTime ); + { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } + return fiber; } - function createFiberFromFragment(elements, mode, expirationTime, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromFundamental( fundamentalComponent, pendingProps, @@ -21989,6 +23174,14 @@ function createFiberFromFundamental( return fiber; } +function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) { + var fiber = createFiber(ScopeComponent, pendingProps, key, mode); + fiber.type = scope; + fiber.elementType = scope; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -22002,76 +23195,74 @@ function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { } } - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - // TODO: The Profiler fiber shouldn't have a type. It has a tag. + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag. + fiber.elementType = REACT_PROFILER_TYPE; fiber.type = REACT_PROFILER_TYPE; fiber.expirationTime = expirationTime; - return fiber; } function createFiberFromSuspense(pendingProps, mode, expirationTime, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - - // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. + fiber.type = REACT_SUSPENSE_TYPE; fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + { // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. fiber.type = REACT_SUSPENSE_LIST_TYPE; } + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromText(content, mode, expirationTime) { var fiber = createFiber(HostText, content, null, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - // TODO: These should not need a type. + var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type. + fiber.elementType = "DELETED"; fiber.type = "DELETED"; return fiber; } - +function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; +} function createFiberFromPortal(portal, mode, expirationTime) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.expirationTime = expirationTime; fiber.stateNode = { containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates + pendingChildren: null, + // Used by persistent updates implementation: portal.implementation }; return fiber; -} +} // Used for stashing WIP properties to replay failed work in DEV. -// Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); - } - - // This is intentionally written as a list of all properties. + } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 @@ -22100,12 +23291,14 @@ function assignFiberPropertiesInDEV(target, source) { target.expirationTime = source.expirationTime; target.childExpirationTime = source.childExpirationTime; target.alternate = source.alternate; + if (enableProfilerTimer) { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } + target._debugID = source._debugID; target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; @@ -22115,19 +23308,6 @@ function assignFiberPropertiesInDEV(target, source) { return target; } -// TODO: This should be lifted into the renderer. - -// The following attributes are only used by interaction tracing builds. -// They enable interactions to be associated with their async work, -// And expose interaction metadata to the React DevTools Profiler plugin. -// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. - -// Exported FiberRoot type includes all properties, -// To avoid requiring potentially error-prone :any casts throughout the project. -// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true). -// The types are defined separately within this file to ensure they stay in sync. -// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.) - function FiberRootNode(containerInfo, tag, hydrate) { this.tag = tag; this.current = null; @@ -22140,31 +23320,129 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.context = null; this.pendingContext = null; this.hydrate = hydrate; - this.firstBatch = null; this.callbackNode = null; - this.callbackExpirationTime = NoWork; + this.callbackPriority = NoPriority; this.firstPendingTime = NoWork; - this.lastPendingTime = NoWork; - this.pingTime = NoWork; + this.firstSuspendedTime = NoWork; + this.lastSuspendedTime = NoWork; + this.nextKnownPendingLevel = NoWork; + this.lastPingedTime = NoWork; + this.lastExpiredTime = NoWork; if (enableSchedulerTracing) { this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } + + if (enableSuspenseCallback) { + this.hydrationCallbacks = null; + } } -function createFiberRoot(containerInfo, tag, hydrate) { +function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate); - // Cyclic construction. This cheats the type system right now because + if (enableSuspenseCallback) { + root.hydrationCallbacks = hydrationCallbacks; + } // Cyclic construction. This cheats the type system right now because // stateNode is any. + var uninitializedFiber = createHostRootFiber(tag); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - return root; } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + return ( + firstSuspendedTime !== NoWork && + firstSuspendedTime >= expirationTime && + lastSuspendedTime <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + + if (firstSuspendedTime < expirationTime) { + root.firstSuspendedTime = expirationTime; + } + + if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) { + root.lastSuspendedTime = expirationTime; + } + + if (expirationTime <= root.lastPingedTime) { + root.lastPingedTime = NoWork; + } + + if (expirationTime <= root.lastExpiredTime) { + root.lastExpiredTime = NoWork; + } +} +function markRootUpdatedAtTime(root, expirationTime) { + // Update the range of pending times + var firstPendingTime = root.firstPendingTime; + + if (expirationTime > firstPendingTime) { + root.firstPendingTime = expirationTime; + } // Update the range of suspended times. Treat everything lower priority or + // equal to this update as unsuspended. + + var firstSuspendedTime = root.firstSuspendedTime; + + if (firstSuspendedTime !== NoWork) { + if (expirationTime >= firstSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (expirationTime >= root.lastSuspendedTime) { + root.lastSuspendedTime = expirationTime + 1; + } // This is a pending level. Check if it's higher priority than the next + // known pending level. + + if (expirationTime > root.nextKnownPendingLevel) { + root.nextKnownPendingLevel = expirationTime; + } + } +} +function markRootFinishedAtTime( + root, + finishedExpirationTime, + remainingExpirationTime +) { + // Update the range of pending times + root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or + // equal to this update as unsuspended. + + if (finishedExpirationTime <= root.lastSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (finishedExpirationTime <= root.firstSuspendedTime) { + // Part of the suspended range is now unsuspended. Narrow the range to + // include everything between the unsuspended time (non-inclusive) and the + // last suspended time. + root.firstSuspendedTime = finishedExpirationTime - 1; + } + + if (finishedExpirationTime <= root.lastPingedTime) { + // Clear the pinged time + root.lastPingedTime = NoWork; + } + + if (finishedExpirationTime <= root.lastExpiredTime) { + // Clear the expired time + root.lastExpiredTime = NoWork; + } +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) { + root.lastExpiredTime = expirationTime; + } +} // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. @@ -22173,14 +23451,10 @@ function createFiberRoot(containerInfo, tag, hydrate) { var ReactFiberInstrumentation = { debugTool: null }; - var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. - -var didWarnAboutNestedUpdates = void 0; -var didWarnAboutFindNodeInStrictMode = void 0; +var didWarnAboutNestedUpdates; +var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; @@ -22197,6 +23471,7 @@ function getContextForSubtree(parentComponent) { if (fiber.tag === ClassComponent) { var Component = fiber.type; + if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } @@ -22205,166 +23480,72 @@ function getContextForSubtree(parentComponent) { return parentContext; } -function scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback -) { - { - if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - 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" - ); +function findHostInstance(component) { + var fiber = get(component); + + if (fiber === undefined) { + if (typeof component.render === "function") { + { + throw Error("Unable to find node on an unmounted component."); + } + } else { + { + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } } } - var update = createUpdate(expirationTime, suspenseConfig); - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = { element: element }; - - callback = callback === undefined ? null : callback; - if (callback !== null) { - !(typeof callback === "function") - ? warningWithoutStack$1( - false, - "render(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callback - ) - : void 0; - update.callback = callback; - } + var hostFiber = findCurrentHostFiber(fiber); - if (revertPassiveEffectsChange) { - flushPassiveEffects(); + if (hostFiber === null) { + return null; } - enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); - return expirationTime; + return hostFiber.stateNode; } -function updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback -) { - // TODO: If this is a nested container, this won't be the root. - var current$$1 = container.current; - +function findHostInstanceWithWarning(component, methodName) { { - if (ReactFiberInstrumentation_1.debugTool) { - if (current$$1.alternate === null) { - ReactFiberInstrumentation_1.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); - } - } - } - - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - return scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback - ); -} + var fiber = get(component); -function findHostInstance(component) { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { + if (fiber === undefined) { + if (typeof component.render === "function") { { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); + throw Error("Unable to find node on an unmounted component."); } - })(); - } else { - (function() { + } else { { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } - })(); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - } else { - (function() { - { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) - ); - } - })(); } } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + if (hostFiber.mode & StrictMode) { var componentName = getComponentName(fiber.type) || "Component"; + if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; + if (fiber.mode & StrictMode) { warningWithoutStack$1( false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which is inside StrictMode. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -22375,10 +23556,9 @@ function findHostInstanceWithWarning(component, methodName) { false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which renders StrictMode children. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -22387,18 +23567,20 @@ function findHostInstanceWithWarning(component, methodName) { } } } + return hostFiber.stateNode; } + return findHostInstance(component); } -function createContainer(containerInfo, tag, hydrate) { - return createFiberRoot(containerInfo, tag, hydrate); +function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) { + return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks); } - function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; var currentTime = requestCurrentTime(); + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -22406,30 +23588,83 @@ function updateContainer(element, container, parentComponent, callback) { warnIfNotScopedWithMatchingAct(current$$1); } } + var suspenseConfig = requestCurrentSuspenseConfig(); var expirationTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - return updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback - ); -} + { + if (ReactFiberInstrumentation_1.debugTool) { + if (current$$1.alternate === null) { + ReactFiberInstrumentation_1.debugTool.onMountContainer(container); + } else if (element === null) { + ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); + } else { + ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); + } + } + } + + var context = getContextForSubtree(parentComponent); + + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + + { + if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + 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" + ); + } + } + + var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property + // being called "element". + + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; + + if (callback !== null) { + !(typeof callback === "function") + ? warningWithoutStack$1( + false, + "render(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callback + ) + : void 0; + update.callback = callback; + } + + enqueueUpdate(current$$1, update); + scheduleWork(current$$1, expirationTime); + return expirationTime; +} function getPublicRootInstance(container) { var containerFiber = container.current; + if (!containerFiber.child) { return null; } + switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); + default: return containerFiber.child.stateNode; } @@ -22442,7 +23677,6 @@ var shouldSuspendImpl = function(fiber) { function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } - var overrideHookState = null; var overrideProps = null; var scheduleUpdate = null; @@ -22453,62 +23687,53 @@ var setSuspenseHandler = null; if (idx >= path.length) { return value; } + var key = path[idx]; - var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); - // $FlowFixMe number or string is fine here + var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); // $FlowFixMe number or string is fine here + updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); return updated; }; var copyWithSet = function(obj, path, value) { return copyWithSetImpl(obj, path, 0, value); - }; + }; // Support DevTools editable values for useState and useReducer. - // Support DevTools editable values for useState and useReducer. overrideHookState = function(fiber, id, path, value) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; + while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } - if (currentHook !== null) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } + if (currentHook !== null) { var newState = copyWithSet(currentHook.memoizedState, path, value); currentHook.memoizedState = newState; - currentHook.baseState = newState; - - // We aren't actually adding an update to the queue, + currentHook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); + fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); scheduleWork(fiber, Sync); } - }; + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } + scheduleWork(fiber, Sync); }; scheduleUpdate = function(fiber) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } scheduleWork(fiber, Sync); }; @@ -22520,7 +23745,6 @@ var setSuspenseHandler = null; function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals( Object.assign({}, devToolsConfig, { overrideHookState: overrideHookState, @@ -22530,9 +23754,11 @@ function injectIntoDevTools(devToolsConfig) { currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + return hostFiber.stateNode; }, findFiberByHostInstance: function(instance) { @@ -22540,9 +23766,9 @@ function injectIntoDevTools(devToolsConfig) { // Might not be implemented by the renderer. return null; } + return findFiberByHostInstance(instance); }, - // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh, scheduleRefresh: scheduleRefresh, @@ -22561,13 +23787,11 @@ function injectIntoDevTools(devToolsConfig) { function createPortal( children, - containerInfo, - // TODO: figure out the API for cross-renderer implementation. + containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation ) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, @@ -22578,404 +23802,31 @@ function createPortal( }; } -// TODO: this is special because it gets imported during build. - -var ReactVersion = "16.8.6"; - -// Modules provided by RN: -var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { - /** - * `NativeMethodsMixin` provides methods to access the underlying native - * component directly. This can be useful in cases when you want to focus - * a view or measure its on-screen dimensions, for example. - * - * The methods described here are available on most of the default components - * provided by React Native. Note, however, that they are *not* available on - * composite components that aren't directly backed by a native view. This will - * generally include most components that you define in your own app. For more - * information, see [Direct - * Manipulation](docs/direct-manipulation.html). - * - * Note the Flow $Exact<> syntax is required to support mixins. - * React createClass mixins can only be used with exact types. - */ - var NativeMethodsMixin = { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measure( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measureInWindow( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeNode`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * - * As always, to obtain a native node handle for a component, you can use - * `findNodeHandle(component)`. - */ - measureLayout: function( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: measureLayout on components using NativeMethodsMixin " + - "or ReactNative.NativeComponent is not currently supported in Fabric. " + - "measureLayout must be called on a native ref. Consider using forwardRef." - ); - return; - } else { - var relativeNode = void 0; - - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } - - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." - ); - - return; - } - - ReactNativePrivateInterface.UIManager.measureLayout( - findNodeHandle(this), - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - } - }, - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](docs/direct-manipulation.html)). - */ - setNativeProps: function(nativeProps) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than findNodeHandle() because - // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - return; - } - - var nativeTag = - maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; - var viewConfig = - maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - - { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = create(nativeProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( - nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } - }, - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus: function() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }, - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur: function() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - } - }; - - { - // hide this from Flow since we can't define these properties outside of - // true without actually implementing them (setting them to undefined - // isn't allowed by ReactClass) - var NativeMethodsMixin_DEV = NativeMethodsMixin; - (function() { - if ( - !( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps - ) - ) { - throw ReactError(Error("Do not override existing functions.")); - } - })(); - // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, - // Once these lifecycles have been remove from the reconciler. - NativeMethodsMixin_DEV.componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { - throwOnStylesProp(this, newProps); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( - newProps - ) { - throwOnStylesProp(this, newProps); - }; - - // React may warn about cWM/cWRP/cWU methods being deprecated. - // Add a flag to suppress these warnings for this special case. - // TODO (bvaughn) Remove this flag once the above methods have been removed. - NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; - NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; - } - - return NativeMethodsMixin; -}; - -function _classCallCheck$2(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn$1(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits$1(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); -} - -// Modules provided by RN: -var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { - /** - * Superclass that provides methods to access the underlying native component. - * This can be useful when you want to focus a view or measure its dimensions. - * - * Methods implemented by this class are available on most default components - * provided by React Native. However, they are *not* available on composite - * components that are not directly backed by a native view. For more - * information, see [Direct Manipulation](docs/direct-manipulation.html). - * - * @abstract - */ - var ReactNativeComponent = (function(_React$Component) { - _inherits$1(ReactNativeComponent, _React$Component); - - function ReactNativeComponent() { - _classCallCheck$2(this, ReactNativeComponent); - - return _possibleConstructorReturn$1( - this, - _React$Component.apply(this, arguments) - ); - } - - /** - * Removes focus. This is the opposite of `focus()`. - */ - - /** - * Due to bugs in Flow's handling of React.createClass, some fields already - * declared in the base class need to be redeclared below. - */ - ReactNativeComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - }; - - /** - * Requests focus. The exact behavior depends on the platform and view. - */ +// TODO: this is special because it gets imported during build. - ReactNativeComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }; +var ReactVersion = "16.10.2"; +var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { + /** + * `NativeMethodsMixin` provides methods to access the underlying native + * component directly. This can be useful in cases when you want to focus + * a view or measure its on-screen dimensions, for example. + * + * The methods described here are available on most of the default components + * provided by React Native. Note, however, that they are *not* available on + * composite components that aren't directly backed by a native view. This will + * generally include most components that you define in your own app. For more + * information, see [Direct + * Manipulation](docs/direct-manipulation.html). + * + * Note the Flow $Exact<> syntax is required to support mixins. + * React createClass mixins can only be used with exact types. + */ + var NativeMethodsMixin = { /** - * Measures the on-screen location and dimensions. If successful, the callback - * will be called asynchronously with the following arguments: + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: * * - x * - y @@ -22984,24 +23835,22 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { * - pageX * - pageY * - * These values are not available until after natives rendering completes. If - * you need the measurements as soon as possible, consider using the - * [`onLayout` prop](docs/view.html#onlayout) instead. + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. */ - - ReactNativeComponent.prototype.measure = function measure(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measure: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23020,37 +23869,34 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Measures the on-screen location and dimensions. Even if the React Native - * root view is embedded within another native view, this method will give you - * the absolute coordinates measured from the window. If successful, the - * callback will be called asynchronously with the following arguments: + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: * * - x * - y * - width * - height * - * These values are not available until after natives rendering completes. + * Note that these measurements are not available until after the rendering + * has been completed in native. */ - - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measureInWindow: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23069,32 +23915,32 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Similar to [`measure()`](#measure), but the resulting location will be - * relative to the supplied ancestor's location. + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeNode`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. * - * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + * As always, to obtain a native node handle for a component, you can use + * `findNodeHandle(component)`. */ - - ReactNativeComponent.prototype.measureLayout = function measureLayout( + measureLayout: function( relativeToNativeNode, onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + onFail + ) /* currently unused */ + { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23108,7 +23954,7 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { ); return; } else { - var relativeNode = void 0; + var relativeNode; if (typeof relativeToNativeNode === "number") { // Already a node handle @@ -23122,7 +23968,6 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { false, "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." ); - return; } @@ -23133,7 +23978,7 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); } - }; + }, /** * This function sends props straight to native. They will not participate in @@ -23141,27 +23986,22 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ - - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + setNativeProps: function(nativeProps) { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // Use findNodeHandle() rather than findNodeHandle() because // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23179,11 +24019,14 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { var viewConfig = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - var updatePayload = create(nativeProps, viewConfig.validAttributes); + { + warnForStyleProps(nativeProps, viewConfig.validAttributes); + } - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( nativeTag, @@ -23191,12 +24034,322 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { updatePayload ); } + }, + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus: function() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }, + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur: function() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + } + }; + + { + // hide this from Flow since we can't define these properties outside of + // true without actually implementing them (setting them to undefined + // isn't allowed by ReactClass) + var NativeMethodsMixin_DEV = NativeMethodsMixin; + + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw Error("Do not override existing functions."); + } // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, + // Once these lifecycles have been remove from the reconciler. + + NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp(this, this.props); }; - return ReactNativeComponent; - })(React.Component); + NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp(this, newProps); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { + throwOnStylesProp(this, this.props); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( + newProps + ) { + throwOnStylesProp(this, newProps); + }; // React may warn about cWM/cWRP/cWU methods being deprecated. + // Add a flag to suppress these warnings for this special case. + // TODO (bvaughn) Remove this flag once the above methods have been removed. + + NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; + NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; + } + + return NativeMethodsMixin; +}; + +var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { + /** + * Superclass that provides methods to access the underlying native component. + * This can be useful when you want to focus a view or measure its dimensions. + * + * Methods implemented by this class are available on most default components + * provided by React Native. However, they are *not* available on composite + * components that are not directly backed by a native view. For more + * information, see [Direct Manipulation](docs/direct-manipulation.html). + * + * @abstract + */ + var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); + + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } + + var _proto = ReactNativeComponent.prototype; + + /** + * Due to bugs in Flow's handling of React.createClass, some fields already + * declared in the base class need to be redeclared below. + */ + + /** + * Removes focus. This is the opposite of `focus()`. + */ + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + }; + /** + * Requests focus. The exact behavior depends on the platform and view. + */ + + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }; + /** + * Measures the on-screen location and dimensions. If successful, the callback + * will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * These values are not available until after natives rendering completes. If + * you need the measurements as soon as possible, consider using the + * [`onLayout` prop](docs/view.html#onlayout) instead. + */ + + _proto.measure = function measure(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Measures the on-screen location and dimensions. Even if the React Native + * root view is embedded within another native view, this method will give you + * the absolute coordinates measured from the window. If successful, the + * callback will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * + * These values are not available until after natives rendering completes. + */ + + _proto.measureInWindow = function measureInWindow(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Similar to [`measure()`](#measure), but the resulting location will be + * relative to the supplied ancestor's location. + * + * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + */ + + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: measureLayout on components using NativeMethodsMixin " + + "or ReactNative.NativeComponent is not currently supported in Fabric. " + + "measureLayout must be called on a native ref. Consider using forwardRef." + ); + return; + } else { + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } + + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } + + ReactNativePrivateInterface.UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } + }; + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](docs/direct-manipulation.html)). + */ + + _proto.setNativeProps = function setNativeProps(nativeProps) { + // Class components don't have viewConfig -> validateAttributes. + // Nor does it make sense to set native props on a non-native component. + // Instead, find the nearest host component and set props on it. + // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // We want the instance/wrapper (not the native tag). + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. - // eslint-disable-next-line no-unused-expressions + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + var nativeTag = + maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; + var viewConfig = + maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } + }; + + return ReactNativeComponent; + })(React.Component); // eslint-disable-next-line no-unused-expressions return ReactNativeComponent; }; @@ -23207,13 +24360,13 @@ function getInstanceFromTag(tag) { return instanceCache.get(tag) || null; } -// Module provided by RN: var emptyObject$2 = {}; + { Object.freeze(emptyObject$2); } -var getInspectorDataForViewTag = void 0; +var getInspectorDataForViewTag; { var traverseOwnerTreeUp = function(hierarchy, instance) { @@ -23237,30 +24390,36 @@ var getInspectorDataForViewTag = void 0; return instance; } } + return hierarchy[0]; }; var getHostProps = function(fiber) { var host = findCurrentHostFiber(fiber); + if (host) { return host.memoizedProps || emptyObject$2; } + return emptyObject$2; }; var getHostNode = function(fiber, findNodeHandle) { - var hostNode = void 0; - // look for children first for the hostNode + var hostNode; // look for children first for the hostNode // as composite fibers do not have a hostNode + while (fiber) { if (fiber.stateNode !== null && fiber.tag === HostComponent) { hostNode = findNodeHandle(fiber.stateNode); } + if (hostNode) { return hostNode; } + fiber = fiber.child; } + return null; }; @@ -23285,9 +24444,8 @@ var getInspectorDataForViewTag = void 0; }; getInspectorDataForViewTag = function(viewTag) { - var closestInstance = getInstanceFromTag(viewTag); + var closestInstance = getInstanceFromTag(viewTag); // Handle case where user clicks outside of ReactNative - // Handle case where user clicks outside of ReactNative if (!closestInstance) { return { hierarchy: [], @@ -23304,7 +24462,6 @@ var getInspectorDataForViewTag = void 0; var props = getHostProps(instance); var source = instance._debugSource; var selection = fiberHierarchy.indexOf(instance); - return { hierarchy: hierarchy, props: props, @@ -23316,12 +24473,12 @@ var getInspectorDataForViewTag = void 0; var _nativeFabricUIManage = nativeFabricUIManager; var fabricDispatchCommand = _nativeFabricUIManage.dispatchCommand; - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function findNodeHandle(componentOrHandle) { { var owner = ReactCurrentOwner.current; + if (owner !== null && owner.stateNode !== null) { !owner.stateNode._warnedAboutRefsInRender ? warningWithoutStack$1( @@ -23334,24 +24491,29 @@ function findNodeHandle(componentOrHandle) { getComponentName(owner.type) || "A component" ) : void 0; - owner.stateNode._warnedAboutRefsInRender = true; } } + if (componentOrHandle == null) { return null; } + if (typeof componentOrHandle === "number") { // Already a node handle return componentOrHandle; } + if (componentOrHandle._nativeTag) { return componentOrHandle._nativeTag; } + if (componentOrHandle.canonical && componentOrHandle.canonical._nativeTag) { return componentOrHandle.canonical._nativeTag; } - var hostInstance = void 0; + + var hostInstance; + { hostInstance = findHostInstanceWithWarning( componentOrHandle, @@ -23361,13 +24523,14 @@ function findNodeHandle(componentOrHandle) { if (hostInstance == null) { return hostInstance; - } - // TODO: the code is right but the types here are wrong. + } // TODO: the code is right but the types here are wrong. // https://github.com/facebook/react/pull/12863 + if (hostInstance.canonical) { // Fabric return hostInstance.canonical._nativeTag; } + return hostInstance._nativeTag; } @@ -23377,14 +24540,10 @@ setBatchingImplementation( flushDiscreteUpdates, batchedEventUpdates$1 ); - var roots = new Map(); - var ReactFabric = { NativeComponent: ReactNativeComponent$1(findNodeHandle, findHostInstance), - findNodeHandle: findNodeHandle, - dispatchCommand: function(handle, command, args) { var invalid = handle._nativeTag == null || handle._internalInstanceHandle == null; @@ -23412,15 +24571,16 @@ var ReactFabric = { if (!root) { // TODO (bvaughn): If we decide to keep the wrapper component, // We could create a wrapper for containerTag as well to reduce special casing. - root = createContainer(containerTag, LegacyRoot, false); + root = createContainer(containerTag, LegacyRoot, false, null); roots.set(containerTag, root); } - updateContainer(element, root, null, callback); + updateContainer(element, root, null, callback); return getPublicRootInstance(root); }, unmountComponentAtNode: function(containerTag) { var root = roots.get(containerTag); + if (root) { // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? updateContainer(null, root, null, function() { @@ -23431,16 +24591,13 @@ var ReactFabric = { createPortal: function(children, containerTag) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - return createPortal(children, containerTag, null, key); }, - __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // Used as a mixin in many createClass-based components NativeMethodsMixin: NativeMethodsMixin(findNodeHandle, findHostInstance) } }; - injectIntoDevTools({ findFiberByHostInstance: getInstanceFromInstance, getInspectorDataForViewTag: getInspectorDataForViewTag, @@ -23457,6 +24614,7 @@ var ReactFabric$3 = (ReactFabric$2 && ReactFabric) || ReactFabric$2; // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. + var fabric = ReactFabric$3.default || ReactFabric$3; module.exports = fabric; diff --git a/Libraries/Renderer/implementations/ReactFabric-dev.js b/Libraries/Renderer/implementations/ReactFabric-dev.js index 02ac7229225767..f7d77db03adaac 100644 --- a/Libraries/Renderer/implementations/ReactFabric-dev.js +++ b/Libraries/Renderer/implementations/ReactFabric-dev.js @@ -23,15 +23,6 @@ var Scheduler = require("scheduler"); var checkPropTypes = require("prop-types/checkPropTypes"); var tracing = require("scheduler/tracing"); -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. - -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} - /** * Use invariant() to assert state which your program assumes to be true. * @@ -47,76 +38,69 @@ function ReactError(error) { * Injectable ordering of event plugins. */ var eventPluginOrder = null; - /** * Injectable mapping from names to event plugin modules. */ -var namesToPlugins = {}; +var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ + function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } + for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); - (function() { - if (!(pluginIndex > -1)) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) - ); - } - })(); + + if (!(pluginIndex > -1)) { + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + if (plugins[pluginIndex]) { continue; } - (function() { - if (!pluginModule.extractEvents) { - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) - ); - } - })(); + + if (!pluginModule.extractEvents) { + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + } + plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { - (function() { - if ( - !publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ) - ) { - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) - ); - } - })(); + if ( + !publishEventForPlugin( + publishedEvents[eventName], + pluginModule, + eventName + ) + ) { + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } } } } - /** * Publishes an event so that it can be dispatched by the supplied plugin. * @@ -125,21 +109,19 @@ function recomputePluginOrdering() { * @return {boolean} True if the event was successfully published. * @private */ + function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - (function() { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName + - "`." - ) - ); - } - })(); - eventNameDispatchConfigs[eventName] = dispatchConfig; + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." + ); + } + eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { @@ -151,6 +133,7 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); } } + return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( @@ -160,9 +143,9 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); return true; } + return false; } - /** * Publishes a registration name that is used to identify dispatched events. * @@ -170,18 +153,16 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { * @param {object} PluginModule Plugin publishing the event. * @private */ + function publishRegistrationName(registrationName, pluginModule, eventName) { - (function() { - if (!!registrationNameModules[registrationName]) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) - ); - } - })(); + if (!!registrationNameModules[registrationName]) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + registrationNameModules[registrationName] = pluginModule; registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; @@ -190,7 +171,6 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { var lowerCasedName = registrationName.toLowerCase(); } } - /** * Registers plugins so that they can extract and dispatch events. * @@ -200,23 +180,23 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { /** * Ordered list of injected plugins. */ -var plugins = []; +var plugins = []; /** * Mapping from event name to dispatch config */ -var eventNameDispatchConfigs = {}; +var eventNameDispatchConfigs = {}; /** * Mapping from registration name to plugin module */ -var registrationNameModules = {}; +var registrationNameModules = {}; /** * Mapping from registration name to event name */ -var registrationNameDependencies = {}; +var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available @@ -235,21 +215,17 @@ var registrationNameDependencies = {}; * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ + function injectEventPluginOrder(injectedEventPluginOrder) { - (function() { - if (!!eventPluginOrder) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) - ); - } - })(); - // Clone the ordering so it cannot be dynamically mutated. + if (!!eventPluginOrder) { + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." + ); + } // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); } - /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. @@ -260,32 +236,34 @@ function injectEventPluginOrder(injectedEventPluginOrder) { * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ + function injectEventPluginsByName(injectedNamesToPlugins) { var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } + var pluginModule = injectedNamesToPlugins[pluginName]; + if ( !namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule ) { - (function() { - if (!!namesToPlugins[pluginName]) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) - ); - } - })(); + if (!!namesToPlugins[pluginName]) { + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } + if (isOrderingDirty) { recomputePluginOrdering(); } @@ -303,6 +281,7 @@ var invokeGuardedCallbackImpl = function( f ) { var funcArgs = Array.prototype.slice.call(arguments, 3); + try { func.apply(context, funcArgs); } catch (error) { @@ -329,7 +308,6 @@ var invokeGuardedCallbackImpl = function( // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if ( @@ -355,52 +333,45 @@ var invokeGuardedCallbackImpl = function( // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebookincubator/create-react-app/issues/3482 // So we preemptively throw with a better message instead. - (function() { - if (!(typeof document !== "undefined")) { - throw ReactError( - Error( - "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." - ) - ); - } - })(); - var evt = document.createEvent("Event"); + if (!(typeof document !== "undefined")) { + 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." + ); + } - // Keeps track of whether the user-provided callback threw an error. We + var evt = document.createEvent("Event"); // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. - var didError = true; - // Keeps track of the value of window.event so that we can reset it + var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. - var windowEvent = window.event; - // Keeps track of the descriptor of window.event to restore it after event + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 + var windowEventDescriptor = Object.getOwnPropertyDescriptor( window, "event" - ); - - // Create an event handler for our fake event. We will synchronously + ); // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - - // We check for window.hasOwnProperty('event') to prevent the + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. + if ( typeof window.event !== "undefined" && window.hasOwnProperty("event") @@ -410,9 +381,7 @@ var invokeGuardedCallbackImpl = function( func.apply(context, funcArgs); didError = false; - } - - // Create a global error event handler. We use this to capture the value + } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of @@ -423,17 +392,20 @@ var invokeGuardedCallbackImpl = function( // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. + + var error; // Use this to track whether the error event is ever called. + var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } + if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. @@ -446,17 +418,14 @@ var invokeGuardedCallbackImpl = function( } } } - } + } // Create a fake event type. - // Create a fake event type. - var evtType = "react-" + (name ? name : "invokeguardedcallback"); + var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - // Attach our event handlers window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); - - // Synchronously dispatch our fake event. If the user-provided function + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); @@ -484,10 +453,10 @@ var invokeGuardedCallbackImpl = function( "See https://fb.me/react-crossorigin-error for more information." ); } + this.onError(error); - } + } // Remove our event listeners - // Remove our event listeners window.removeEventListener("error", handleWindowError); }; @@ -497,21 +466,17 @@ var invokeGuardedCallbackImpl = function( var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// Used by Fiber to simulate a try-catch. var hasError = false; -var caughtError = null; +var caughtError = null; // Used by event system to capture/rethrow the first error. -// Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; - var reporter = { onError: function(error) { hasError = true; caughtError = error; } }; - /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. @@ -525,12 +490,12 @@ var reporter = { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } - /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. @@ -541,6 +506,7 @@ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallbackAndCatchFirstError( name, func, @@ -553,19 +519,21 @@ function invokeGuardedCallbackAndCatchFirstError( f ) { invokeGuardedCallback.apply(this, arguments); + if (hasError) { var error = clearCaughtError(); + if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } - /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ + function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; @@ -574,11 +542,9 @@ function rethrowCaughtError() { throw error; } } - function hasCaughtError() { return hasError; } - function clearCaughtError() { if (hasError) { var error = caughtError; @@ -586,15 +552,11 @@ function clearCaughtError() { caughtError = null; return error; } else { - (function() { - { - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -604,14 +566,13 @@ function clearCaughtError() { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - var warningWithoutStack = function() {}; { warningWithoutStack = function(condition, format) { for ( var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), + args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++ @@ -625,25 +586,28 @@ var warningWithoutStack = function() {}; "message argument" ); } + if (args.length > 8) { // Check before the condition to catch violations early. throw new Error( "warningWithoutStack() currently supports at most 8 arguments." ); } + if (condition) { return; } + if (typeof console !== "undefined") { var argsWithFormat = args.map(function(item) { return "" + item; }); - argsWithFormat.unshift("Warning: " + format); - - // We intentionally don't use spread (or .apply) directly because it + argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 + Function.prototype.apply.call(console.error, console, argsWithFormat); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -664,7 +628,6 @@ var warningWithoutStack$1 = warningWithoutStack; var getFiberCurrentPropsFromNode = null; var getInstanceFromNode = null; var getNodeFromInstance = null; - function setComponentTree( getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, @@ -673,6 +636,7 @@ function setComponentTree( getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode = getInstanceFromNodeImpl; getNodeFromInstance = getNodeFromInstanceImpl; + { !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1( @@ -683,70 +647,69 @@ function setComponentTree( : void 0; } } +var validateEventDispatches; -var validateEventDispatches = void 0; { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, "EventPluginUtils: Invalid `event`.") : void 0; }; } - /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ + function executeDispatch(event, listener, inst) { var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } - /** * Standard/simple iteration through an event's collected dispatches. */ + function executeDispatchesInOrder(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, dispatchListeners, dispatchInstances); } + event._dispatchListeners = null; event._dispatchInstances = null; } - /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. @@ -754,18 +717,21 @@ function executeDispatchesInOrder(event) { * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ + function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } @@ -775,19 +741,19 @@ function executeDispatchesInOrderStopAtTrueImpl(event) { return dispatchInstances; } } + return null; } - /** * @see executeDispatchesInOrderStopAtTrueImpl */ + function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } - /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make @@ -797,17 +763,19 @@ function executeDispatchesInOrderStopAtTrue(event) { * * @return {*} The return value of executing the single dispatch. */ + function executeDirectDispatch(event) { { validateEventDispatches(event); } + var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - (function() { - if (!!Array.isArray(dispatchListener)) { - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); - } - })(); + + if (!!Array.isArray(dispatchListener)) { + throw Error("executeDirectDispatch(...): Invalid `event`."); + } + event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -817,11 +785,11 @@ function executeDirectDispatch(event) { event._dispatchInstances = null; return res; } - /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ + function hasDispatches(event) { return !!event._dispatchListeners; } @@ -840,27 +808,23 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } + current.push(next); return current; } @@ -894,14 +858,15 @@ function forEachAccumulated(arr, cb, scope) { * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ -var eventQueue = null; +var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ + var executeDispatchesAndRelease = function(event) { if (event) { executeDispatchesInOrder(event); @@ -911,6 +876,7 @@ var executeDispatchesAndRelease = function(event) { } } }; + var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(e); }; @@ -918,10 +884,9 @@ var executeDispatchesAndReleaseTopLevel = function(e) { function runEventsInBatch(events) { if (events !== null) { eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more + } // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. + var processingEventQueue = eventQueue; eventQueue = null; @@ -930,16 +895,13 @@ function runEventsInBatch(events) { } forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - (function() { - if (!!eventQueue) { - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) - ); - } - })(); - // This would be a good time to rethrow if any of the event handlers threw. + + if (!!eventQueue) { + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + } // This would be a good time to rethrow if any of the event handlers threw. + rethrowCaughtError(); } @@ -965,11 +927,11 @@ function shouldPreventMouseEvent(name, type, props) { case "onMouseUp": case "onMouseUpCapture": return !!(props.disabled && isInteractive(type)); + default: return false; } } - /** * This is a unified interface for event plugins to be installed and configured. * @@ -996,6 +958,7 @@ function shouldPreventMouseEvent(name, type, props) { /** * Methods for injecting dependencies. */ + var injection = { /** * @param {array} InjectedEventPluginOrder @@ -1008,47 +971,48 @@ var injection = { */ injectEventPluginsByName: injectEventPluginsByName }; - /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ -function getListener(inst, registrationName) { - var listener = void 0; - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not +function getListener(inst, registrationName) { + var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon + var stateNode = inst.stateNode; + if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } + var props = getFiberCurrentPropsFromNode(stateNode); + if (!props) { // Work in progress. return null; } + listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - (function() { - if (!(!listener || typeof listener === "function")) { - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) - ); - } - })(); + + if (!(!listener || typeof listener === "function")) { + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + return listener; } - /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. @@ -1056,28 +1020,35 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ + function extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = null; + for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; + if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); + if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } + return events; } @@ -1085,13 +1056,15 @@ function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); runEventsInBatch(events); } @@ -1099,8 +1072,11 @@ function runExtractedPluginEventsInBatch( var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + var HostComponent = 5; var HostText = 6; var Fragment = 7; @@ -1114,101 +1090,111 @@ var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; -var DehydratedSuspenseComponent = 18; +var DehydratedFragment = 18; var SuspenseListComponent = 19; var FundamentalComponent = 20; +var ScopeComponent = 21; function getParent(inst) { do { - inst = inst.return; - // TODO: If this is a HostRoot we might want to bail out. + inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); + if (inst) { return inst; } + return null; } - /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ + function getLowestCommonAncestor(instA, instB) { var depthA = 0; + for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } + var depthB = 0; + for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; - } + } // If A is deeper, crawl up. - // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; - } + } // If B is deeper, crawl up. - // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; - } + } // Walk in lockstep until we find a match. - // Walk in lockstep until we find a match. var depth = depthA; + while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } + instA = getParent(instA); instB = getParent(instB); } + return null; } - /** * Return if A is an ancestor of B. */ + function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } + instB = getParent(instB); } + return false; } - /** * Return the parent instance of the passed-in instance. */ + function getParentInstance(inst) { return getParent(inst); } - /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ + function traverseTwoPhase(inst, fn, arg) { var path = []; + while (inst) { path.push(inst); inst = getParent(inst); } - var i = void 0; + + var i; + for (i = path.length; i-- > 0; ) { fn(path[i], "captured", arg); } + for (i = 0; i < path.length; i++) { fn(path[i], "bubbled", arg); } } - /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. @@ -1226,7 +1212,6 @@ function listenerAtPhase(inst, event, propagationPhase) { event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } - /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which @@ -1243,13 +1228,16 @@ function listenerAtPhase(inst, event, propagationPhase) { * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ + function accumulateDirectionalDispatches(inst, phase, event) { { !inst ? warningWithoutStack$1(false, "Dispatching inst must not be null") : void 0; } + var listener = listenerAtPhase(inst, event, phase); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1258,7 +1246,6 @@ function accumulateDirectionalDispatches(inst, phase, event) { event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } - /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through @@ -1266,15 +1253,16 @@ function accumulateDirectionalDispatches(inst, phase, event) { * single traversal for the entire collection of events because each event may * have a different target. */ + function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } - /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ + function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; @@ -1282,16 +1270,17 @@ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } - /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ + function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1301,12 +1290,12 @@ function accumulateDispatches(inst, ignoredDirection, event) { } } } - /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ + function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); @@ -1316,7 +1305,6 @@ function accumulateDirectDispatchesSingle(event) { function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } - function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } @@ -1326,13 +1314,12 @@ function accumulateDirectDispatches(events) { } /* eslint valid-typeof: 0 */ - var EVENT_POOL_SIZE = 10; - /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ + var EventInterface = { type: null, target: null, @@ -1357,7 +1344,6 @@ function functionThatReturnsTrue() { function functionThatReturnsFalse() { return false; } - /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. @@ -1376,6 +1362,7 @@ function functionThatReturnsFalse() { * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ + function SyntheticEvent( dispatchConfig, targetInst, @@ -1394,16 +1381,19 @@ function SyntheticEvent( this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; - var Interface = this.constructor.Interface; + for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } + { delete this[propName]; // this has a getter/setter for warnings } + var normalize = Interface[propName]; + if (normalize) { this[propName] = normalize(nativeEvent); } else { @@ -1419,11 +1409,13 @@ function SyntheticEvent( nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } + this.isPropagationStopped = functionThatReturnsFalse; return this; } @@ -1432,6 +1424,7 @@ Object.assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; + if (!event) { return; } @@ -1441,11 +1434,12 @@ Object.assign(SyntheticEvent.prototype, { } else if (typeof event.returnValue !== "unknown") { event.returnValue = false; } + this.isDefaultPrevented = functionThatReturnsTrue; }, - stopPropagation: function() { var event = this.nativeEvent; + if (!event) { return; } @@ -1485,6 +1479,7 @@ Object.assign(SyntheticEvent.prototype, { */ destructor: function() { var Interface = this.constructor.Interface; + for (var propName in Interface) { { Object.defineProperty( @@ -1494,6 +1489,7 @@ Object.assign(SyntheticEvent.prototype, { ); } } + this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; @@ -1501,6 +1497,7 @@ Object.assign(SyntheticEvent.prototype, { this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; + { Object.defineProperty( this, @@ -1536,35 +1533,33 @@ Object.assign(SyntheticEvent.prototype, { } } }); - SyntheticEvent.Interface = EventInterface; - /** * Helper to reduce boilerplate when creating subclasses. */ + SyntheticEvent.extend = function(Interface) { var Super = this; var E = function() {}; + E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } + Object.assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; - Class.Interface = Object.assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); - return Class; }; addEventPoolingTo(SyntheticEvent); - /** * Helper to nullify syntheticEvent instance properties when destructing * @@ -1572,6 +1567,7 @@ addEventPoolingTo(SyntheticEvent); * @param {?object} getVal * @return {object} defineProperty object */ + function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === "function"; return { @@ -1614,6 +1610,7 @@ function getPooledWarningPropertyDefinition(propName, getVal) { function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; + if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call( @@ -1625,6 +1622,7 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { ); return instance; } + return new EventConstructor( dispatchConfig, targetInst, @@ -1635,16 +1633,15 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - (function() { - if (!(event instanceof EventConstructor)) { - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) - ); - } - })(); + + if (!(event instanceof EventConstructor)) { + throw Error( + "Trying to release an event instance into a pool of a different type." + ); + } + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } @@ -1661,6 +1658,7 @@ function addEventPoolingTo(EventConstructor) { * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ + var ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function(nativeEvent) { return null; // Actually doesn't even look at the native event. @@ -1673,19 +1671,15 @@ var TOP_TOUCH_END = "topTouchEnd"; var TOP_TOUCH_CANCEL = "topTouchCancel"; var TOP_SCROLL = "topScroll"; var TOP_SELECTION_CHANGE = "topSelectionChange"; - function isStartish(topLevelType) { return topLevelType === TOP_TOUCH_START; } - function isMoveish(topLevelType) { return topLevelType === TOP_TOUCH_MOVE; } - function isEndish(topLevelType) { return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL; } - var startDependencies = [TOP_TOUCH_START]; var moveDependencies = [TOP_TOUCH_MOVE]; var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END]; @@ -1714,11 +1708,11 @@ function timestampForTouch(touch) { // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } - /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ + function createTouchRecord(touch) { return { touchActive: true, @@ -1750,11 +1744,10 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - (function() { - if (!(identifier != null)) { - throw ReactError(Error("Touch object is missing identifier.")); - } - })(); + if (!(identifier != null)) { + throw Error("Touch object is missing identifier."); + } + { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1766,22 +1759,26 @@ function getTouchIdentifier(_ref) { ) : void 0; } + return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; + if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1803,6 +1800,7 @@ function recordTouchMove(touch) { function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1833,9 +1831,11 @@ function printTouch(touch) { function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + if (touchBank.length > MAX_TOUCH_BANK) { printed += " (original size: " + touchBank.length + ")"; } + return printed; } @@ -1846,6 +1846,7 @@ var ResponderTouchHistoryStore = { } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; @@ -1853,14 +1854,17 @@ var ResponderTouchHistoryStore = { } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; + if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } + { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; !(activeRecord != null && activeRecord.touchActive) @@ -1870,7 +1874,6 @@ var ResponderTouchHistoryStore = { } } }, - touchHistory: touchHistory }; @@ -1881,23 +1884,19 @@ var ResponderTouchHistoryStore = { * * @return {*|array<*>} An accumulation of items. */ + function accumulate(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulate(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { return current.concat(next); } @@ -1913,17 +1912,19 @@ function accumulate(current, next) { * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ -var responderInst = null; +var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ + var trackedTouchCount = 0; var changeResponder = function(nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; + if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange( oldResponderInst, @@ -2026,7 +2027,6 @@ var eventTypes = { dependencies: [] } }; - /** * * Responder System: @@ -2229,17 +2229,15 @@ function setResponderAndExtractTransfer( ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder - : eventTypes.scrollShouldSetResponder; + : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. - // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst - : getLowestCommonAncestor(responderInst, targetInst); - - // When capturing/bubbling the "shouldSet" event, we want to skip the target + : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. + var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent.getPooled( shouldSetEventType, @@ -2248,12 +2246,15 @@ function setResponderAndExtractTransfer( nativeEventTarget ); shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; + if (skipOverBubbleShouldSetFrom) { accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { accumulateTwoPhaseDispatches(shouldSetEvent); } + var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent); + if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } @@ -2261,7 +2262,8 @@ function setResponderAndExtractTransfer( if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } - var extracted = void 0; + + var extracted; var grantEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, wantsResponderInst, @@ -2269,9 +2271,9 @@ function setResponderAndExtractTransfer( nativeEventTarget ); grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; - accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch(grantEvent) === true; + if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderTerminationRequest, @@ -2285,6 +2287,7 @@ function setResponderAndExtractTransfer( var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent); + if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } @@ -2315,9 +2318,9 @@ function setResponderAndExtractTransfer( extracted = accumulate(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } + return extracted; } - /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer @@ -2326,10 +2329,10 @@ function setResponderAndExtractTransfer( * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ + function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return ( - topLevelInst && - // responderIgnoreScroll: We are trying to migrate away from specifically + topLevelInst && // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead ((topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll) || @@ -2338,7 +2341,6 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { isMoveish(topLevelType)) ); } - /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. @@ -2346,22 +2348,28 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ + function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; + if (!touches || touches.length === 0) { return true; } + for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; + if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = getInstanceFromNode(target); + if (isAncestor(responderInst, targetInst)) { return false; } } } + return true; } @@ -2370,7 +2378,6 @@ var ResponderEventPlugin = { _getResponder: function() { return responderInst; }, - eventTypes: eventTypes, /** @@ -2382,7 +2389,8 @@ var ResponderEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (isStartish(topLevelType)) { trackedTouchCount += 1; @@ -2390,7 +2398,7 @@ var ResponderEventPlugin = { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ); return null; @@ -2398,7 +2406,6 @@ var ResponderEventPlugin = { } ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); - var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer( topLevelType, @@ -2406,8 +2413,7 @@ var ResponderEventPlugin = { nativeEvent, nativeEventTarget ) - : null; - // Responder may or may not have transferred on a new touch start/move. + : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional @@ -2417,6 +2423,7 @@ var ResponderEventPlugin = { // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). + var isResponderTouchStart = responderInst && isStartish(topLevelType); var isResponderTouchMove = responderInst && isMoveish(topLevelType); var isResponderTouchEnd = responderInst && isEndish(topLevelType); @@ -2452,6 +2459,7 @@ var ResponderEventPlugin = { : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { var finalEvent = ResponderSyntheticEvent.getPooled( finalTouch, @@ -2467,9 +2475,7 @@ var ResponderEventPlugin = { return extracted; }, - GlobalResponderHandler: null, - injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler @@ -2482,14 +2488,12 @@ var ResponderEventPlugin = { } }; -// Module provided by RN: var customBubblingEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customBubblingEventTypes; var customDirectEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customDirectEventTypes; - var ReactNativeBridgeEventPlugin = { eventTypes: {}, @@ -2500,29 +2504,30 @@ var ReactNativeBridgeEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (targetInst == null) { // Probably a node belonging to another renderer's tree. return null; } + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; var directDispatchConfig = customDirectEventTypes[topLevelType]; - (function() { - if (!(bubbleDispatchConfig || directDispatchConfig)) { - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) - ); - } - })(); + + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget ); + if (bubbleDispatchConfig) { accumulateTwoPhaseDispatches(event); } else if (directDispatchConfig) { @@ -2530,6 +2535,7 @@ var ReactNativeBridgeEventPlugin = { } else { return null; } + return event; } }; @@ -2549,12 +2555,13 @@ var ReactNativeEventPluginOrder = [ /** * Inject module for resolving DOM hierarchy and plugin ordering. */ -injection.injectEventPluginOrder(ReactNativeEventPluginOrder); +injection.injectEventPluginOrder(ReactNativeEventPluginOrder); /** * Some important event plugins included by default (without having to require * them). */ + injection.injectEventPluginsByName({ ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin @@ -2566,11 +2573,11 @@ function getInstanceFromInstance(instanceHandle) { function getTagFromInstance(inst) { var tag = inst.stateNode.canonical._nativeTag; - (function() { - if (!tag) { - throw ReactError(Error("All native instances should have a tag.")); - } - })(); + + if (!tag) { + throw Error("All native instances should have a tag."); + } + return tag; } @@ -2598,7 +2605,6 @@ setComponentTree( getInstanceFromInstance, getTagFromInstance ); - ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactFabricGlobalResponderHandler ); @@ -2628,16 +2634,16 @@ function set(key, value) { } var ReactSharedInternals = - React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -// Prevent newer renderers from RTE when used with older react package versions. + React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentDispatcher")) { ReactSharedInternals.ReactCurrentDispatcher = { current: null }; } + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null @@ -2647,7 +2653,6 @@ if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === "function" && Symbol.for; - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 0xeacb; @@ -2656,8 +2661,7 @@ var REACT_STRICT_MODE_TYPE = hasSymbol : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; -// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_CONCURRENT_MODE_TYPE = hasSymbol @@ -2676,30 +2680,105 @@ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 0xead6; - +var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } + var maybeIterator = (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { return maybeIterator; } + return null; } +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = warningWithoutStack$1; + +{ + warning = function(condition, format) { + if (condition) { + return; + } + + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args + + for ( + var _len = arguments.length, + args = new Array(_len > 2 ? _len - 2 : 0), + _key = 2; + _key < _len; + _key++ + ) { + args[_key - 2] = arguments[_key]; + } + + warningWithoutStack$1.apply( + void 0, + [false, format + "%s"].concat(args, [stack]) + ); + }; +} + +var warning$1 = warning; + +var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; - function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then( + function(moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; + + { + if (defaultExport === undefined) { + 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 + ); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, + function(error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + } + ); + } +} function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ""; @@ -2714,6 +2793,7 @@ function getComponentName(type) { // Host root, text node or just invalid type. return null; } + { if (typeof type.tag === "number") { warningWithoutStack$1( @@ -2723,73 +2803,123 @@ function getComponentName(type) { ); } } + if (typeof type === "function") { return type.displayName || type.name || null; } + if (typeof type === "string") { return type; } + switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; + case REACT_PORTAL_TYPE: return "Portal"; + case REACT_PROFILER_TYPE: return "Profiler"; + case REACT_STRICT_MODE_TYPE: return "StrictMode"; + case REACT_SUSPENSE_TYPE: return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } + if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return "Context.Consumer"; + case REACT_PROVIDER_TYPE: return "Context.Provider"; + case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: return getComponentName(type.type); + case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); + if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; } } } + return null; } // Don't change these two values. They're used by React Dev Tools. -var NoEffect = /* */ 0; -var PerformedWork = /* */ 1; - -// You can change the rest (and add more). -var Placement = /* */ 2; -var Update = /* */ 4; -var PlacementAndUpdate = /* */ 6; -var Deletion = /* */ 8; -var ContentReset = /* */ 16; -var Callback = /* */ 32; -var DidCapture = /* */ 64; -var Ref = /* */ 128; -var Snapshot = /* */ 256; -var Passive = /* */ 512; - -// Passive & Update & Callback & Ref & Snapshot -var LifecycleEffectMask = /* */ 932; - -// Union of all host effects -var HostEffectMask = /* */ 1023; - -var Incomplete = /* */ 1024; -var ShouldCapture = /* */ 2048; +var NoEffect = + /* */ + 0; +var PerformedWork = + /* */ + 1; // You can change the rest (and add more). + +var Placement = + /* */ + 2; +var Update = + /* */ + 4; +var PlacementAndUpdate = + /* */ + 6; +var Deletion = + /* */ + 8; +var ContentReset = + /* */ + 16; +var Callback = + /* */ + 32; +var DidCapture = + /* */ + 64; +var Ref = + /* */ + 128; +var Snapshot = + /* */ + 256; +var Passive = + /* */ + 512; +var Hydrating = + /* */ + 1024; +var HydratingAndUpdate = + /* */ + 1028; // Passive & Update & Callback & Ref & Snapshot + +var LifecycleEffectMask = + /* */ + 932; // Union of all host effects + +var HostEffectMask = + /* */ + 2047; +var Incomplete = + /* */ + 2048; +var ShouldCapture = + /* */ + 4096; var debugRenderPhaseSideEffects = false; var debugRenderPhaseSideEffectsForStrictMode = false; @@ -2802,61 +2932,64 @@ var enableSuspenseServerRenderer = false; var enableFlareAPI = false; var enableFundamentalAPI = false; +var enableScopeAPI = false; var warnAboutUnmockedScheduler = false; -var revertPassiveEffectsChange = false; var flushSuspenseFallbacksInTests = true; -var enableUserBlockingEvents = false; var enableSuspenseCallback = false; var warnAboutDefaultPropsOnFunctionComponents = false; var warnAboutStringRefs = false; var disableLegacyContext = false; var disableSchedulerTimeoutBasedOnReactExpirationTime = false; - // Only used in www builds. -var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; +// Flow magic to verify the exports of this file match the original version. -function isFiberMountedImpl(fiber) { +var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; +function getNearestMountedFiber(fiber) { var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node.return) { - node = node.return; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; + var nextNode = node; + + do { + node = nextNode; + + if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; } - } + + nextNode = node.return; + } while (nextNode); } else { while (node.return) { node = node.return; } } + if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. - return UNMOUNTED; + + return null; } function isFiberMounted(fiber) { - return isFiberMountedImpl(fiber) === MOUNTED; + return getNearestMountedFiber(fiber) === fiber; } - function isMounted(component) { { var owner = ReactCurrentOwner$1.current; + if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; @@ -2876,90 +3009,93 @@ function isMounted(component) { } var fiber = get(component); + if (!fiber) { return false; } - return isFiberMountedImpl(fiber) === MOUNTED; + + return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { - (function() { - if (!(isFiberMountedImpl(fiber) === MOUNTED)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); - } - })(); + if (!(getNearestMountedFiber(fiber) === fiber)) { + throw Error("Unable to find node on an unmounted component."); + } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; + if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. - var state = isFiberMountedImpl(fiber); - (function() { - if (!(state !== UNMOUNTED)) { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - if (state === MOUNTING) { + var nearestMounted = getNearestMountedFiber(fiber); + + if (!(nearestMounted !== null)) { + throw Error("Unable to find node on an unmounted component."); + } + + if (nearestMounted !== fiber) { return null; } + return fiber; - } - // If we have two possible branches, we'll walk backwards up to the root + } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. + var a = fiber; var b = alternate; + while (true) { var parentA = a.return; + if (parentA === null) { // We're at the root. break; } + var parentB = parentA.alternate; + if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; + if (nextParent !== null) { a = b = nextParent; continue; - } - // If there's no parent, we're at the root. - break; - } + } // If there's no parent, we're at the root. - // If both copies of the parent fiber point to the same child, we can + break; + } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. + if (parentA.child === parentB.child) { var child = parentA.child; + while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } + if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } + child = child.sibling; - } - // We should never have an alternate for any mounting node. So the only + } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); + + { + throw Error("Unable to find node on an unmounted component."); + } } if (a.return !== b.return) { @@ -2977,6 +3113,7 @@ function findCurrentFiberUsingSlowPath(fiber) { // Search parent A's child set var didFindChild = false; var _child = parentA.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -2984,17 +3121,21 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentB; break; } + if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } + _child = _child.sibling; } + if (!didFindChild) { // Search parent B's child set _child = parentB.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3002,59 +3143,53 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentA; break; } + if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } + _child = _child.sibling; } - (function() { - if (!didFindChild) { - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) - ); - } - })(); + + if (!didFindChild) { + 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." + ); + } } } - (function() { - if (!(a.alternate === b)) { - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - (function() { - if (!(a.tag === HostRoot)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (!(a.alternate === b)) { + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - })(); + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. + + if (!(a.tag === HostRoot)) { + throw Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; - } - // Otherwise B has to be current branch. + } // Otherwise B has to be current branch. + return alternate; } - function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { return null; - } + } // Next we'll drill down this component to find the first HostComponent/Text. - // Next we'll drill down this component to find the first HostComponent/Text. var node = currentParent; + while (true) { if (node.tag === HostComponent || node.tag === HostText) { return node; @@ -3063,20 +3198,24 @@ function findCurrentHostFiber(parent) { node = node.child; continue; } + if (node === currentParent) { return null; } + while (!node.sibling) { if (!node.return || node.return === currentParent) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. + } // Flow needs the return null here, but ESLint complains about it. // eslint-disable-next-line no-unreachable + return null; } @@ -3088,24 +3227,20 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return function() { if (!callback) { return undefined; - } - // This protects against createClass() components. + } // This protects against createClass() components. // We don't know if there is code depending on it. // We intentionally don't use isMounted() because even accessing // isMounted property on a React ES6 class will trigger a warning. + if (typeof context.__isMounted === "boolean") { if (!context.__isMounted) { return undefined; } - } - - // FIXME: there used to be other branches that protected + } // FIXME: there used to be other branches that protected // against unmounted host components. But RN host components don't // define isMounted() anymore, so those checks didn't do anything. - // They caused false positive warning noise so we removed them: // https://github.com/facebook/react-native/issues/18868#issuecomment-413579095 - // However, this means that the callback is NOT guaranteed to be safe // for host components. The solution we should implement is to make // UIManager.measure() and similar calls truly cancelable. Then we @@ -3114,7 +3249,6 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return callback.apply(context, arguments); }; } - function throwOnStylesProp(component, props) { if (props.styles !== undefined) { var owner = component._owner || null; @@ -3124,6 +3258,7 @@ function throwOnStylesProp(component, props) { name + "`, did " + "you mean `style` (singular)?"; + if (owner && owner.constructor && owner.constructor.displayName) { msg += "\n\nCheck the `" + @@ -3131,10 +3266,10 @@ function throwOnStylesProp(component, props) { "` parent " + " component."; } + throw new Error(msg); } } - function warnForStyleProps(props, validAttributes) { for (var key in validAttributes.style) { if (!(validAttributes[key] || props[key] === undefined)) { @@ -3153,7 +3288,6 @@ function warnForStyleProps(props, validAttributes) { // Modules provided by RN: var emptyObject = {}; - /** * Create a payload that contains all the updates between two sets of props. * @@ -3184,6 +3318,7 @@ function restoreDeletedValuesInNestedArray( ) { if (Array.isArray(node)) { var i = node.length; + while (i-- && removedKeyCount > 0) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3193,16 +3328,20 @@ function restoreDeletedValuesInNestedArray( } } else if (node && removedKeyCount > 0) { var obj = node; + for (var propKey in removedKeys) { if (!removedKeys[propKey]) { continue; } + var nextProp = obj[propKey]; + if (nextProp === undefined) { continue; } var attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3210,6 +3349,7 @@ function restoreDeletedValuesInNestedArray( if (typeof nextProp === "function") { nextProp = true; } + if (typeof nextProp === "undefined") { nextProp = null; } @@ -3228,6 +3368,7 @@ function restoreDeletedValuesInNestedArray( : nextProp; updatePayload[propKey] = nextValue; } + removedKeys[propKey] = false; removedKeyCount--; } @@ -3242,7 +3383,8 @@ function diffNestedArrayProperty( ) { var minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; - var i = void 0; + var i; + for (i = 0; i < minLength; i++) { // Diff any items in the array in the forward direction. Repeated keys // will be overwritten by later values. @@ -3253,6 +3395,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < prevArray.length; i++) { // Clear out all remaining properties. updatePayload = clearNestedProperty( @@ -3261,6 +3404,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < nextArray.length; i++) { // Add all remaining properties. updatePayload = addNestedProperty( @@ -3269,6 +3413,7 @@ function diffNestedArrayProperty( validAttributes ); } + return updatePayload; } @@ -3288,9 +3433,11 @@ function diffNestedProperty( if (nextProp) { return addNestedProperty(updatePayload, nextProp, validAttributes); } + if (prevProp) { return clearNestedProperty(updatePayload, prevProp, validAttributes); } + return updatePayload; } @@ -3311,10 +3458,8 @@ function diffNestedProperty( if (Array.isArray(prevProp)) { return diffProperties( - updatePayload, - // $FlowFixMe - We know that this is always an object when the input is. - ReactNativePrivateInterface.flattenStyle(prevProp), - // $FlowFixMe - We know that this isn't an array because of above flow. + updatePayload, // $FlowFixMe - We know that this is always an object when the input is. + ReactNativePrivateInterface.flattenStyle(prevProp), // $FlowFixMe - We know that this isn't an array because of above flow. nextProp, validAttributes ); @@ -3322,18 +3467,17 @@ function diffNestedProperty( return diffProperties( updatePayload, - prevProp, - // $FlowFixMe - We know that this is always an object when the input is. + prevProp, // $FlowFixMe - We know that this is always an object when the input is. ReactNativePrivateInterface.flattenStyle(nextProp), validAttributes ); } - /** * addNestedProperty takes a single set of props and valid attribute * attribute configurations. It processes each prop and adds it to the * updatePayload. */ + function addNestedProperty(updatePayload, nextProp, validAttributes) { if (!nextProp) { return updatePayload; @@ -3355,11 +3499,11 @@ function addNestedProperty(updatePayload, nextProp, validAttributes) { return updatePayload; } - /** * clearNestedProperty takes a single set of props and valid attributes. It * adds a null sentinel to the updatePayload, for each prop key. */ + function clearNestedProperty(updatePayload, prevProp, validAttributes) { if (!prevProp) { return updatePayload; @@ -3378,44 +3522,45 @@ function clearNestedProperty(updatePayload, prevProp, validAttributes) { validAttributes ); } + return updatePayload; } - /** * diffProperties takes two sets of props and a set of valid attributes * and write to updatePayload the values that changed or were deleted. * If no updatePayload is provided, a new one is created and returned if * anything changed. */ + function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { - var attributeConfig = void 0; - var nextProp = void 0; - var prevProp = void 0; + var attributeConfig; + var nextProp; + var prevProp; for (var propKey in nextProps) { attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } prevProp = prevProps[propKey]; - nextProp = nextProps[propKey]; - - // functions are converted to booleans as markers that the associated + nextProp = nextProps[propKey]; // functions are converted to booleans as markers that the associated // events should be sent from native. + if (typeof nextProp === "function") { - nextProp = true; - // If nextProp is not a function, then don't bother changing prevProp + nextProp = true; // If nextProp is not a function, then don't bother changing prevProp // since nextProp will win and go into the updatePayload regardless. + if (typeof prevProp === "function") { prevProp = true; } - } - - // An explicit value of undefined is treated as a null because it overrides + } // An explicit value of undefined is treated as a null because it overrides // any other preceding value. + if (typeof nextProp === "undefined") { nextProp = null; + if (typeof prevProp === "undefined") { prevProp = null; } @@ -3430,7 +3575,6 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // value diffed. Since we're now later in the nested arrays our value is // more important so we need to calculate it and override the existing // value. It doesn't matter if nothing changed, we'll set it anyway. - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case @@ -3446,14 +3590,14 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { : nextProp; updatePayload[propKey] = nextValue; } + continue; } if (prevProp === nextProp) { continue; // nothing changed - } + } // Pattern match on: attributeConfig - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case if (defaultDiffer(prevProp, nextProp)) { @@ -3470,25 +3614,28 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { (typeof attributeConfig.diff === "function" ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + if (shouldUpdate) { var _nextValue = typeof attributeConfig.process === "function" ? attributeConfig.process(nextProp) : nextProp; + (updatePayload || (updatePayload = {}))[propKey] = _nextValue; } } else { // default: fallthrough case when nested properties are defined removedKeys = null; - removedKeyCount = 0; - // We think that attributeConfig is not CustomAttributeConfiguration at + removedKeyCount = 0; // We think that attributeConfig is not CustomAttributeConfiguration at // this point so we assume it must be AttributeConfiguration. + updatePayload = diffNestedProperty( updatePayload, prevProp, nextProp, attributeConfig ); + if (removedKeyCount > 0 && updatePayload) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3498,16 +3645,17 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { removedKeys = null; } } - } - - // Also iterate through all the previous props to catch any that have been + } // Also iterate through all the previous props to catch any that have been // removed and make sure native gets the signal so it can reset them to the // default. + for (var _propKey in prevProps) { if (nextProps[_propKey] !== undefined) { continue; // we've already covered this key in the previous pass } + attributeConfig = validAttributes[_propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3518,10 +3666,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { } prevProp = prevProps[_propKey]; + if (prevProp === undefined) { continue; // was already empty anyway - } - // Pattern match on: attributeConfig + } // Pattern match on: attributeConfig + if ( typeof attributeConfig !== "object" || typeof attributeConfig.diff === "function" || @@ -3530,9 +3679,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // case: CustomAttributeConfiguration | !Object // Flag the leaf property for removal by sending a sentinel. (updatePayload || (updatePayload = {}))[_propKey] = null; + if (!removedKeys) { removedKeys = {}; } + if (!removedKeys[_propKey]) { removedKeys[_propKey] = true; removedKeyCount++; @@ -3548,21 +3699,22 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ); } } + return updatePayload; } - /** * addProperties adds all the valid props to the payload after being processed. */ + function addProperties(updatePayload, props, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, emptyObject, props, validAttributes); } - /** * clearProperties clears all the previous props by adding a null sentinel * to the payload for each valid key. */ + function clearProperties(updatePayload, prevProps, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); @@ -3575,7 +3727,6 @@ function create(props, validAttributes) { validAttributes ); } - function diff(prevProps, nextProps, validAttributes) { return diffProperties( null, // updatePayload @@ -3585,7 +3736,7 @@ function diff(prevProps, nextProps, validAttributes) { ); } -// Use to restore controlled state after a change event has fired. +var PLUGIN_EVENT_SYSTEM = 1; var restoreImpl = null; var restoreTarget = null; @@ -3595,19 +3746,18 @@ function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { // Unmounted return; } - (function() { - if (!(typeof restoreImpl === "function")) { - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof restoreImpl === "function")) { + 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." + ); + } + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, props); } @@ -3615,17 +3765,17 @@ function restoreStateOfTarget(target) { function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } - function restoreStateIfNeeded() { if (!restoreTarget) { return; } + var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; - restoreStateOfTarget(target); + if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); @@ -3633,23 +3783,25 @@ function restoreStateIfNeeded() { } } -// Used as a way to call batchedUpdates when we don't have a reference to // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. - // Defaults + var batchedUpdatesImpl = function(fn, bookkeeping) { return fn(bookkeeping); }; + var discreteUpdatesImpl = function(fn, a, b, c) { return fn(a, b, c); }; + var flushDiscreteUpdatesImpl = function() {}; -var batchedEventUpdatesImpl = batchedUpdatesImpl; +var batchedEventUpdatesImpl = batchedUpdatesImpl; var isInsideEventHandler = false; +var isBatchingEventUpdates = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important @@ -3657,6 +3809,7 @@ function finishEventHandler() { // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React @@ -3672,7 +3825,9 @@ function batchedUpdates(fn, bookkeeping) { // fully completes before restoring state. return fn(bookkeeping); } + isInsideEventHandler = true; + try { return batchedUpdatesImpl(fn, bookkeeping); } finally { @@ -3680,35 +3835,48 @@ function batchedUpdates(fn, bookkeeping) { finishEventHandler(); } } - function batchedEventUpdates(fn, a, b) { - if (isInsideEventHandler) { + if (isBatchingEventUpdates) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(a, b); } - isInsideEventHandler = true; + + isBatchingEventUpdates = true; + try { return batchedEventUpdatesImpl(fn, a, b); } finally { - isInsideEventHandler = false; + isBatchingEventUpdates = false; finishEventHandler(); } -} +} // This is for the React Flare event system +function executeUserEventHandler(fn, value) { + var previouslyInEventHandler = isInsideEventHandler; + + try { + isInsideEventHandler = true; + var type = typeof value === "object" && value !== null ? value.type : ""; + invokeGuardedCallbackAndCatchFirstError(type, fn, undefined, value); + } finally { + isInsideEventHandler = previouslyInEventHandler; + } +} function discreteUpdates(fn, a, b, c) { var prevIsInsideEventHandler = isInsideEventHandler; isInsideEventHandler = true; + try { return discreteUpdatesImpl(fn, a, b, c); } finally { isInsideEventHandler = prevIsInsideEventHandler; + if (!isInsideEventHandler) { finishEventHandler(); } } } - var lastFlushedEventTimeStamp = 0; function flushDiscreteUpdatesIfNeeded(timeStamp) { // event.timeStamp isn't overly reliable due to inconsistencies in @@ -3733,7 +3901,6 @@ function flushDiscreteUpdatesIfNeeded(timeStamp) { flushDiscreteUpdatesImpl(); } } - function setBatchingImplementation( _batchedUpdatesImpl, _discreteUpdatesImpl, @@ -3746,176 +3913,99 @@ function setBatchingImplementation( batchedEventUpdatesImpl = _batchedEventUpdatesImpl; } -function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } /** * Class only exists for its Flow type. */ -var ReactNativeComponent = (function(_React$Component) { - _inherits(ReactNativeComponent, _React$Component); +var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); - function ReactNativeComponent() { - _classCallCheck$1(this, ReactNativeComponent); - - return _possibleConstructorReturn( - this, - _React$Component.apply(this, arguments) - ); - } - - ReactNativeComponent.prototype.blur = function blur() {}; - - ReactNativeComponent.prototype.focus = function focus() {}; + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } - ReactNativeComponent.prototype.measure = function measure(callback) {}; + var _proto = ReactNativeComponent.prototype; - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) {}; + _proto.blur = function blur() {}; - ReactNativeComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail - ) {}; + _proto.focus = function focus() {}; - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) {}; + _proto.measure = function measure(callback) {}; - return ReactNativeComponent; -})(React.Component); + _proto.measureInWindow = function measureInWindow(callback) {}; -// This type is only used for FlowTests. It shouldn't be imported directly + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) {}; -/** - * This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync. - * It can also provide types for ReactNative applications that use NMM or refs. - */ + _proto.setNativeProps = function setNativeProps(nativeProps) {}; -/** - * Flat ReactNative renderer bundles are too big for Flow to parse efficiently. - * Provide minimal Flow typing for the high-level RN API and call it a day. - */ + return ReactNativeComponent; + })(React.Component); // This type is only used for FlowTests. It shouldn't be imported directly var DiscreteEvent = 0; var UserBlockingEvent = 1; var ContinuousEvent = 2; -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warning = warningWithoutStack$1; - -{ - warning = function(condition, format) { - if (condition) { - return; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - // eslint-disable-next-line react-internal/warning-and-invariant-args - - for ( - var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key]; - } - - warningWithoutStack$1.apply( - undefined, - [false, format + "%s"].concat(args, [stack]) - ); - }; -} - -var warning$1 = warning; - -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; var runWithPriority = Scheduler.unstable_runWithPriority; var _nativeFabricUIManage$2 = nativeFabricUIManager; var measureInWindow = _nativeFabricUIManage$2.measureInWindow; - -var activeTimeouts = new Map(); var rootEventTypesToEventResponderInstances = new Map(); -var ownershipChangeListeners = new Set(); - -var globalOwner = null; - var currentTimeStamp = 0; -var currentTimers = new Map(); var currentInstance = null; -var currentEventQueue = null; -var currentEventQueuePriority = ContinuousEvent; -var currentTimerIDCounter = 0; - var eventResponderContext = { dispatchEvent: function(eventValue, eventListener, eventPriority) { validateResponderContext(); validateEventValue(eventValue); - if (eventPriority < currentEventQueuePriority) { - currentEventQueuePriority = eventPriority; + + switch (eventPriority) { + case DiscreteEvent: { + flushDiscreteUpdatesIfNeeded(currentTimeStamp); + discreteUpdates(function() { + return executeUserEventHandler(eventListener, eventValue); + }); + break; + } + + case UserBlockingEvent: { + runWithPriority(UserBlockingPriority, function() { + return executeUserEventHandler(eventListener, eventValue); + }); + break; + } + + case ContinuousEvent: { + executeUserEventHandler(eventListener, eventValue); + break; + } } - currentEventQueue.push(createEventQueueItem(eventValue, eventListener)); }, isTargetWithinNode: function(childTarget, parentTarget) { validateResponderContext(); var childFiber = getFiberFromTarget(childTarget); var parentFiber = getFiberFromTarget(parentTarget); - var node = childFiber; + while (node !== null) { if (node === parentFiber) { return true; } + node = node.return; } + return false; }, getTargetBoundingRect: function(target, callback) { @@ -3930,6 +4020,7 @@ var eventResponderContext = { }, addRootEventTypes: function(rootEventTypes) { validateResponderContext(); + for (var i = 0; i < rootEventTypes.length; i++) { var rootEventType = rootEventTypes[i]; var eventResponderInstance = currentInstance; @@ -3938,85 +4029,51 @@ var eventResponderContext = { }, removeRootEventTypes: function(rootEventTypes) { validateResponderContext(); + for (var i = 0; i < rootEventTypes.length; i++) { var rootEventType = rootEventTypes[i]; - var rootEventResponders = rootEventTypesToEventResponderInstances.get( rootEventType ); var rootEventTypesSet = currentInstance.rootEventTypes; + if (rootEventTypesSet !== null) { rootEventTypesSet.delete(rootEventType); } + if (rootEventResponders !== undefined) { rootEventResponders.delete(currentInstance); } } }, - setTimeout: function(func, delay) { + getTimeStamp: function() { validateResponderContext(); - if (currentTimers === null) { - currentTimers = new Map(); - } - var timeout = currentTimers.get(delay); - - var timerId = currentTimerIDCounter++; - if (timeout === undefined) { - var _timers = new Map(); - var _id = setTimeout(function() { - processTimers(_timers, delay); - }, delay); - timeout = { - id: _id, - timers: _timers - }; - currentTimers.set(delay, timeout); - } - timeout.timers.set(timerId, { - instance: currentInstance, - func: func, - id: timerId, - timeStamp: currentTimeStamp - }); - activeTimeouts.set(timerId, timeout); - return timerId; + return currentTimeStamp; }, - clearTimeout: function(timerId) { + getResponderNode: function() { validateResponderContext(); - var timeout = activeTimeouts.get(timerId); + var responderFiber = currentInstance.fiber; - if (timeout !== undefined) { - var _timers2 = timeout.timers; - _timers2.delete(timerId); - if (_timers2.size === 0) { - clearTimeout(timeout.id); - } + if (responderFiber.tag === ScopeComponent) { + return null; } - }, - getTimeStamp: function() { - validateResponderContext(); - return currentTimeStamp; + + return responderFiber.stateNode; } }; -function createEventQueueItem(value, listener) { - return { - value: value, - listener: listener - }; -} - function validateEventValue(eventValue) { if (typeof eventValue === "object" && eventValue !== null) { var target = eventValue.target, type = eventValue.type, - _timeStamp = eventValue.timeStamp; + timeStamp = eventValue.timeStamp; - if (target == null || type == null || _timeStamp == null) { + if (target == null || type == null || timeStamp == null) { throw new Error( 'context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.' ); } + var showWarning = function(name) { { warning$1( @@ -4028,27 +4085,31 @@ function validateEventValue(eventValue) { ); } }; + eventValue.preventDefault = function() { { showWarning("preventDefault()"); } }; + eventValue.stopPropagation = function() { { showWarning("stopPropagation()"); } }; + eventValue.isDefaultPrevented = function() { { showWarning("isDefaultPrevented()"); } }; + eventValue.isPropagationStopped = function() { { showWarning("isPropagationStopped()"); } - }; - // $FlowFixMe: we don't need value, Flow thinks we do + }; // $FlowFixMe: we don't need value, Flow thinks we do + Object.defineProperty(eventValue, "nativeEvent", { get: function() { { @@ -4063,143 +4124,48 @@ function getFiberFromTarget(target) { if (target === null) { return null; } - return target.canonical._internalInstanceHandle || null; -} -function processTimers(timers, delay) { - var timersArr = Array.from(timers.values()); - currentEventQueuePriority = ContinuousEvent; - try { - for (var i = 0; i < timersArr.length; i++) { - var _timersArr$i = timersArr[i], - _instance = _timersArr$i.instance, - _func = _timersArr$i.func, - _id2 = _timersArr$i.id, - _timeStamp2 = _timersArr$i.timeStamp; - - currentInstance = _instance; - currentEventQueue = []; - currentTimeStamp = _timeStamp2 + delay; - try { - _func(); - } finally { - activeTimeouts.delete(_id2); - } - } - processEventQueue(); - } finally { - currentTimers = null; - currentInstance = null; - currentEventQueue = null; - currentTimeStamp = 0; - } + return target.canonical._internalInstanceHandle || null; } function createFabricResponderEvent(topLevelType, nativeEvent, target) { return { nativeEvent: nativeEvent, - responderTarget: target, target: target, type: topLevelType }; } function validateResponderContext() { - (function() { - if (!(currentEventQueue && currentInstance)) { - throw ReactError( - Error( - "An event responder context was used outside of an event cycle. Use context.setTimeout() to use asynchronous responder context outside of event cycle ." - ) - ); - } - })(); -} - -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic -function processEventQueue() { - var eventQueue = currentEventQueue; - if (eventQueue.length === 0) { - return; - } - switch (currentEventQueuePriority) { - case DiscreteEvent: { - flushDiscreteUpdatesIfNeeded(currentTimeStamp); - discreteUpdates(function() { - batchedEventUpdates(processEvents, eventQueue); - }); - break; - } - case UserBlockingEvent: { - if (enableUserBlockingEvents) { - runWithPriority( - UserBlockingPriority, - batchedEventUpdates.bind(null, processEvents, eventQueue) - ); - } else { - batchedEventUpdates(processEvents, eventQueue); - } - break; - } - case ContinuousEvent: { - batchedEventUpdates(processEvents, eventQueue); - break; - } - } -} - -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic -function releaseOwnershipForEventResponderInstance(eventResponderInstance) { - if (globalOwner === eventResponderInstance) { - globalOwner = null; - triggerOwnershipListeners(); - return true; + if (!currentInstance) { + throw Error( + "An event responder context was used outside of an event cycle." + ); } - return false; -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic -function processEvents(eventQueue) { - for (var i = 0, length = eventQueue.length; i < length; i++) { - var _eventQueue$i = eventQueue[i], - _value = _eventQueue$i.value, - _listener = _eventQueue$i.listener; - - var type = typeof _value === "object" && _value !== null ? _value.type : ""; - invokeGuardedCallbackAndCatchFirstError(type, _listener, undefined, _value); - } -} -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic function responderEventTypesContainType(eventTypes, type) { for (var i = 0, len = eventTypes.length; i < len; i++) { if (eventTypes[i] === type) { return true; } } + return false; } function validateResponderTargetEventTypes(eventType, responder) { - var targetEventTypes = responder.targetEventTypes; - // Validate the target event type exists on the responder + var targetEventTypes = responder.targetEventTypes; // Validate the target event type exists on the responder if (targetEventTypes !== null) { return responderEventTypesContainType(targetEventTypes, eventType); } - return false; -} -function validateOwnership(responderInstance) { - return globalOwner === null || globalOwner === responderInstance; -} - -// TODO this function is almost an exact copy of the DOM version, we should + return false; +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function traverseAndHandleEventResponderInstances( eventType, targetFiber, @@ -4208,7 +4174,6 @@ function traverseAndHandleEventResponderInstances( // Trigger event responders in this order: // - Bubble target responder phase // - Root responder phase - var responderEvent = createFabricResponderEvent( eventType, nativeEvent, @@ -4216,180 +4181,131 @@ function traverseAndHandleEventResponderInstances( ); var visitedResponders = new Set(); var node = targetFiber; + while (node !== null) { var _node = node, dependencies = _node.dependencies, tag = _node.tag; - if (tag === HostComponent && dependencies !== null) { + if ( + (tag === HostComponent || tag === ScopeComponent) && + dependencies !== null + ) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for (var i = 0, length = responderInstances.length; i < length; i++) { var responderInstance = responderInstances[i]; + var props = responderInstance.props, + responder = responderInstance.responder, + state = responderInstance.state; - if (validateOwnership(responderInstance)) { - var props = responderInstance.props, - responder = responderInstance.responder, - state = responderInstance.state, - target = responderInstance.target; + if ( + !visitedResponders.has(responder) && + validateResponderTargetEventTypes(eventType, responder) + ) { + var onEvent = responder.onEvent; + visitedResponders.add(responder); - if ( - !visitedResponders.has(responder) && - validateResponderTargetEventTypes(eventType, responder) - ) { - var onEvent = responder.onEvent; - visitedResponders.add(responder); - if (onEvent !== null) { - currentInstance = responderInstance; - responderEvent.responderTarget = target; - onEvent(responderEvent, eventResponderContext, props, state); - } + if (onEvent !== null) { + currentInstance = responderInstance; + onEvent(responderEvent, eventResponderContext, props, state); } } } } } + node = node.return; - } - // Root phase + } // Root phase + var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( eventType ); + if (rootEventResponderInstances !== undefined) { var _responderInstances = Array.from(rootEventResponderInstances); for (var _i = 0; _i < _responderInstances.length; _i++) { var _responderInstance = _responderInstances[_i]; - if (!validateOwnership(_responderInstance)) { - continue; - } - var _props = _responderInstance.props, - _responder = _responderInstance.responder, - _state = _responderInstance.state, - _target = _responderInstance.target; + var props = _responderInstance.props, + responder = _responderInstance.responder, + state = _responderInstance.state; + var onRootEvent = responder.onRootEvent; - var onRootEvent = _responder.onRootEvent; if (onRootEvent !== null) { currentInstance = _responderInstance; - responderEvent.responderTarget = _target; - onRootEvent(responderEvent, eventResponderContext, _props, _state); + onRootEvent(responderEvent, eventResponderContext, props, state); } } } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function dispatchEventForResponderEventSystem( topLevelType, targetFiber, nativeEvent ) { - var previousEventQueue = currentEventQueue; var previousInstance = currentInstance; - var previousTimers = currentTimers; - var previousTimeStamp = currentTimeStamp; - var previousEventQueuePriority = currentEventQueuePriority; - currentTimers = null; - currentEventQueue = []; - currentEventQueuePriority = ContinuousEvent; - // We might want to control timeStamp another way here + var previousTimeStamp = currentTimeStamp; // We might want to control timeStamp another way here + currentTimeStamp = Date.now(); + try { - traverseAndHandleEventResponderInstances( - topLevelType, - targetFiber, - nativeEvent - ); - processEventQueue(); + batchedEventUpdates(function() { + traverseAndHandleEventResponderInstances( + topLevelType, + targetFiber, + nativeEvent + ); + }); } finally { - currentTimers = previousTimers; currentInstance = previousInstance; - currentEventQueue = previousEventQueue; currentTimeStamp = previousTimeStamp; - currentEventQueuePriority = previousEventQueuePriority; } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic -function triggerOwnershipListeners() { - var listeningInstances = Array.from(ownershipChangeListeners); - var previousInstance = currentInstance; - var previousEventQueuePriority = currentEventQueuePriority; - var previousEventQueue = currentEventQueue; - try { - for (var i = 0; i < listeningInstances.length; i++) { - var _instance2 = listeningInstances[i]; - var props = _instance2.props, - responder = _instance2.responder, - state = _instance2.state; - - currentInstance = _instance2; - currentEventQueuePriority = ContinuousEvent; - currentEventQueue = []; - var onOwnershipChange = responder.onOwnershipChange; - if (onOwnershipChange !== null) { - onOwnershipChange(eventResponderContext, props, state); - } - } - processEventQueue(); - } finally { - currentInstance = previousInstance; - currentEventQueue = previousEventQueue; - currentEventQueuePriority = previousEventQueuePriority; - } -} -// TODO this function is almost an exact copy of the DOM version, we should -// somehow share the logic function mountEventResponder(responder, responderInstance, props, state) { - if (responder.onOwnershipChange !== null) { - ownershipChangeListeners.add(responderInstance); - } var onMount = responder.onMount; + if (onMount !== null) { - currentEventQueuePriority = ContinuousEvent; currentInstance = responderInstance; - currentEventQueue = []; + try { - onMount(eventResponderContext, props, state); - processEventQueue(); + batchedEventUpdates(function() { + onMount(eventResponderContext, props, state); + }); } finally { - currentEventQueue = null; currentInstance = null; - currentTimers = null; } } -} - -// TODO this function is almost an exact copy of the DOM version, we should +} // TODO this function is almost an exact copy of the DOM version, we should // somehow share the logic + function unmountEventResponder(responderInstance) { var responder = responderInstance.responder; var onUnmount = responder.onUnmount; + if (onUnmount !== null) { var props = responderInstance.props, state = responderInstance.state; - - currentEventQueue = []; - currentEventQueuePriority = ContinuousEvent; currentInstance = responderInstance; + try { - onUnmount(eventResponderContext, props, state); - processEventQueue(); + batchedEventUpdates(function() { + onUnmount(eventResponderContext, props, state); + }); } finally { - currentEventQueue = null; currentInstance = null; - currentTimers = null; } } - releaseOwnershipForEventResponderInstance(responderInstance); - if (responder.onOwnershipChange !== null) { - ownershipChangeListeners.delete(responderInstance); - } + var rootEventTypesSet = responderInstance.rootEventTypes; + if (rootEventTypesSet !== null) { var rootEventTypes = Array.from(rootEventTypesSet); @@ -4398,6 +4314,7 @@ function unmountEventResponder(responderInstance) { var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( topLevelEventType ); + if (rootEventResponderInstances !== undefined) { rootEventResponderInstances.delete(responderInstance); } @@ -4409,6 +4326,7 @@ function registerRootEventType(rootEventType, responderInstance) { var rootEventResponderInstances = rootEventTypesToEventResponderInstances.get( rootEventType ); + if (rootEventResponderInstances === undefined) { rootEventResponderInstances = new Set(); rootEventTypesToEventResponderInstances.set( @@ -4416,21 +4334,21 @@ function registerRootEventType(rootEventType, responderInstance) { rootEventResponderInstances ); } + var rootEventTypesSet = responderInstance.rootEventTypes; + if (rootEventTypesSet === null) { rootEventTypesSet = responderInstance.rootEventTypes = new Set(); } - (function() { - if (!!rootEventTypesSet.has(rootEventType)) { - throw ReactError( - Error( - 'addRootEventTypes() found a duplicate root event type of "' + - rootEventType + - '". This might be because the event type exists in the event responder "rootEventTypes" array or because of a previous addRootEventTypes() using this root event type.' - ) - ); - } - })(); + + if (!!rootEventTypesSet.has(rootEventType)) { + 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.' + ); + } + rootEventTypesSet.add(rootEventType); rootEventResponderInstances.add(responderInstance); } @@ -4447,39 +4365,35 @@ function addRootEventTypesForResponderInstance( function dispatchEvent(target, topLevelType, nativeEvent) { var targetFiber = target; + if (enableFlareAPI) { // React Flare event system dispatchEventForResponderEventSystem(topLevelType, target, nativeEvent); } + batchedUpdates(function() { // Heritage plugin event system runExtractedPluginEventsInBatch( topLevelType, targetFiber, nativeEvent, - nativeEvent.target + nativeEvent.target, + PLUGIN_EVENT_SYSTEM ); - }); - // React Native doesn't use ReactControlledComponent but if it did, here's + }); // React Native doesn't use ReactControlledComponent but if it did, here's // where it would do it. } -// Renderers that don't support mutation // can re-export everything from this module. function shim() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} + { + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Mutation (when unsupported) -// Mutation (when unsupported) var supportsMutation = false; var appendChild = shim; var appendChildToContainer = shim; @@ -4496,22 +4410,15 @@ var hideTextInstance = shim; var unhideInstance = shim; var unhideTextInstance = shim; -// Renderers that don't support hydration // can re-export everything from this module. function shim$1() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} - -// Hydration (when unsupported) + { + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Hydration (when unsupported) var supportsHydration = false; var canHydrateInstance = shim$1; @@ -4524,7 +4431,10 @@ var getNextHydratableSibling = shim$1; var getFirstHydratableChild = shim$1; var hydrateInstance = shim$1; var hydrateTextInstance = shim$1; +var hydrateSuspenseInstance = shim$1; var getNextHydratableInstanceAfterSuspenseInstance = shim$1; +var commitHydratedContainer = shim$1; +var commitHydratedSuspenseInstance = shim$1; var clearSuspenseBoundary = shim$1; var clearSuspenseBoundaryFromContainer = shim$1; var didNotMatchHydratedContainerTextInstance = shim$1; @@ -4538,13 +4448,6 @@ var didNotFindHydratableInstance = shim$1; var didNotFindHydratableTextInstance = shim$1; var didNotFindHydratableSuspenseInstance = shim$1; -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -// Modules provided by RN: var _nativeFabricUIManage$1 = nativeFabricUIManager; var createNode = _nativeFabricUIManage$1.createNode; var cloneNode = _nativeFabricUIManage$1.cloneNode; @@ -4561,9 +4464,7 @@ var fabricMeasure = _nativeFabricUIManage$1.measure; var fabricMeasureInWindow = _nativeFabricUIManage$1.measureInWindow; var fabricMeasureLayout = _nativeFabricUIManage$1.measureLayout; var getViewConfigForType = - ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; - -// Counter for uniquely identifying views. + ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; // Counter for uniquely identifying views. // % 10 === 1 means it is a rootTag. // % 2 === 0 means it is a Fabric tag. // This means that they never overlap. @@ -4577,93 +4478,90 @@ if (registerEventHandler) { */ registerEventHandler(dispatchEvent); } - /** * This is used for refs on host components. */ -var ReactFabricHostComponent = (function() { - function ReactFabricHostComponent( - tag, - viewConfig, - props, - internalInstanceHandle - ) { - _classCallCheck(this, ReactFabricHostComponent); +var ReactFabricHostComponent = + /*#__PURE__*/ + (function() { + function ReactFabricHostComponent( + tag, + viewConfig, + props, + internalInstanceHandle + ) { + this._nativeTag = tag; + this.viewConfig = viewConfig; + this.currentProps = props; + this._internalInstanceHandle = internalInstanceHandle; + } - this._nativeTag = tag; - this.viewConfig = viewConfig; - this.currentProps = props; - this._internalInstanceHandle = internalInstanceHandle; - } + var _proto = ReactFabricHostComponent.prototype; - ReactFabricHostComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); - }; + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); + }; - ReactFabricHostComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); - }; + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + this._nativeTag + ); + }; - ReactFabricHostComponent.prototype.measure = function measure(callback) { - fabricMeasure( - this._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; + _proto.measure = function measure(callback) { + fabricMeasure( + this._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactFabricHostComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - fabricMeasureInWindow( - this._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; + _proto.measureInWindow = function measureInWindow(callback) { + fabricMeasureInWindow( + this._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactFabricHostComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - if ( - typeof relativeToNativeNode === "number" || - !(relativeToNativeNode instanceof ReactFabricHostComponent) - ) { + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) /* currently unused */ + { + if ( + typeof relativeToNativeNode === "number" || + !(relativeToNativeNode instanceof ReactFabricHostComponent) + ) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a ref to a native component." + ); + return; + } + + fabricMeasureLayout( + this._internalInstanceHandle.stateNode.node, + relativeToNativeNode._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + }; + + _proto.setNativeProps = function setNativeProps(nativeProps) { warningWithoutStack$1( false, - "Warning: ref.measureLayout must be called with a ref to a native component." + "Warning: setNativeProps is not currently supported in Fabric" ); - return; - } - - fabricMeasureLayout( - this._internalInstanceHandle.stateNode.node, - relativeToNativeNode._internalInstanceHandle.stateNode.node, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; - - ReactFabricHostComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - - return; - }; + }; - return ReactFabricHostComponent; -})(); + return ReactFabricHostComponent; + })(); // eslint-disable-next-line no-unused-expressions function appendInitialChild(parentInstance, child) { appendChildNode(parentInstance.node, child.node); } - function createInstance( type, props, @@ -4673,7 +4571,6 @@ function createInstance( ) { var tag = nextReactTag; nextReactTag += 2; - var viewConfig = getViewConfigForType(type); { @@ -4687,7 +4584,6 @@ function createInstance( } var updatePayload = create(props, viewConfig.validAttributes); - var node = createNode( tag, // reactTag viewConfig.uiViewClassName, // viewName @@ -4695,50 +4591,42 @@ function createInstance( updatePayload, // props internalInstanceHandle // internalInstanceHandle ); - var component = new ReactFabricHostComponent( tag, viewConfig, props, internalInstanceHandle ); - return { node: node, canonical: component }; } - function createTextInstance( text, rootContainerInstance, hostContext, internalInstanceHandle ) { - (function() { - if (!hostContext.isInAParentText) { - throw ReactError( - Error("Text strings must be rendered within a component.") - ); - } - })(); + if (!hostContext.isInAParentText) { + throw Error("Text strings must be rendered within a component."); + } var tag = nextReactTag; nextReactTag += 2; - var node = createNode( tag, // reactTag "RCTRawText", // viewName rootContainerInstance, // rootTag - { text: text }, // props + { + text: text + }, // props internalInstanceHandle // instance handle ); - return { node: node }; } - function finalizeInitialChildren( parentInstance, type, @@ -4748,11 +4636,11 @@ function finalizeInitialChildren( ) { return false; } - function getRootHostContext(rootContainerInstance) { - return { isInAParentText: false }; + return { + isInAParentText: false + }; } - function getChildHostContext(parentHostContext, type, rootContainerInstance) { var prevIsInAParentText = parentHostContext.isInAParentText; var isInAParentText = @@ -4763,20 +4651,19 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { type === "RCTVirtualText"; if (prevIsInAParentText !== isInAParentText) { - return { isInAParentText: isInAParentText }; + return { + isInAParentText: isInAParentText + }; } else { return parentHostContext; } } - function getPublicInstance(instance) { return instance.canonical; } - function prepareForCommit(containerInfo) { // Noop } - function prepareUpdate( instance, type, @@ -4786,22 +4673,19 @@ function prepareUpdate( hostContext ) { var viewConfig = instance.canonical.viewConfig; - var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); - // TODO: If the event handlers have changed, we need to update the current props + var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); // TODO: If the event handlers have changed, we need to update the current props // in the commit phase but there is no host config hook to do it yet. // So instead we hack it by updating it in the render phase. + instance.canonical.currentProps = newProps; return updatePayload; } - function resetAfterCommit(containerInfo) { // Noop } - function shouldDeprioritizeSubtree(type, props) { return false; } - function shouldSetTextContent(type, props) { // TODO (bvaughn) Revisit this decision. // Always returning false simplifies the createInstance() implementation, @@ -4810,24 +4694,18 @@ function shouldSetTextContent(type, props) { // It's not clear to me which is better so I'm deferring for now. // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 return false; -} +} // The Fabric renderer is secondary to the existing React Native renderer. -// The Fabric renderer is secondary to the existing React Native renderer. -var isPrimaryRenderer = false; +var isPrimaryRenderer = false; // The Fabric renderer shouldn't trigger missing act() warnings -// The Fabric renderer shouldn't trigger missing act() warnings var warnsIfNotActing = false; - var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; -var noTimeout = -1; - -// ------------------- +var noTimeout = -1; // ------------------- // Persistence // ------------------- var supportsPersistence = true; - function cloneInstance( instance, updatePayload, @@ -4839,7 +4717,8 @@ function cloneInstance( recyclableInstance ) { var node = instance.node; - var clone = void 0; + var clone; + if (keepChildren) { if (updatePayload !== null) { clone = cloneNodeWithNewProps(node, updatePayload); @@ -4853,17 +4732,21 @@ function cloneInstance( clone = cloneNodeWithNewChildren(node); } } + return { node: clone, canonical: instance.canonical }; } - function cloneHiddenInstance(instance, type, props, internalInstanceHandle) { var viewConfig = instance.canonical.viewConfig; var node = instance.node; var updatePayload = create( - { style: { display: "none" } }, + { + style: { + display: "none" + } + }, viewConfig.validAttributes ); return { @@ -4871,19 +4754,15 @@ function cloneHiddenInstance(instance, type, props, internalInstanceHandle) { canonical: instance.canonical }; } - function cloneHiddenTextInstance(instance, text, internalInstanceHandle) { throw new Error("Not yet implemented."); } - function createContainerChildSet(container) { return createChildNodeSet(container); } - function appendChildToContainerChildSet(childSet, child) { appendChildNodeToSet(childSet, child.node); } - function finalizeContainerChildren(container, newChildren) { completeRoot(container, newChildren); } @@ -4893,8 +4772,7 @@ function mountResponderInstance( responderInstance, props, state, - instance, - rootContainerInstance + instance ) { if (enableFlareAPI) { var rootEventTypes = responder.rootEventTypes; @@ -4902,55 +4780,55 @@ function mountResponderInstance( if (rootEventTypes !== null) { addRootEventTypesForResponderInstance(responderInstance, rootEventTypes); } + mountEventResponder(responder, responderInstance, props, state); } } - function unmountResponderInstance(responderInstance) { if (enableFlareAPI) { // TODO stop listening to targetEventTypes unmountEventResponder(responderInstance); } } - function getFundamentalComponentInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } - function mountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function shouldUpdateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function updateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function unmountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function cloneFundamentalInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } +function getInstanceFromNode$1(node) { + throw new Error("Not yet implemented."); +} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; - var describeComponentFrame = function(name, source, ownerName) { var sourceInfo = ""; + if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ""); + { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); + if (match) { var pathBeforeSlash = match[1]; + if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ""); fileName = folderName + "/" + fileName; @@ -4958,10 +4836,12 @@ var describeComponentFrame = function(name, source, ownerName) { } } } + sourceInfo = " (at " + fileName + ":" + source.lineNumber + ")"; } else if (ownerName) { sourceInfo = " (created by " + ownerName + ")"; } + return "\n in " + (name || "Unknown") + sourceInfo; }; @@ -4976,14 +4856,17 @@ function describeFiber(fiber) { case ContextProvider: case ContextConsumer: return ""; + default: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName(fiber.type); var ownerName = null; + if (owner) { ownerName = getComponentName(owner.type); } + return describeComponentFrame(name, source, ownerName); } } @@ -4991,41 +4874,43 @@ function describeFiber(fiber) { function getStackByFiberInDevAndProd(workInProgress) { var info = ""; var node = workInProgress; + do { info += describeFiber(node); node = node.return; } while (node); + return info; } - var current = null; var phase = null; - function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { return getComponentName(owner.type); } } + return null; } - function getCurrentFiberStackInDev() { { if (current === null) { return ""; - } - // Safe because if current fiber exists, we are reconciling, + } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. + return getStackByFiberInDevAndProd(current); } + return ""; } - function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; @@ -5033,7 +4918,6 @@ function resetCurrentFiber() { phase = null; } } - function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; @@ -5041,7 +4925,6 @@ function setCurrentFiber(fiber) { phase = null; } } - function setCurrentPhase(lifeCyclePhase) { { phase = lifeCyclePhase; @@ -5057,28 +4940,26 @@ var supportsUserTiming = 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. + typeof performance.clearMeasures === "function"; // Keep track of current fiber so that we know the path to unwind on pause. // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? -var currentFiber = null; -// If we're in the middle of user code, which fiber and method is it? + +var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). + var currentPhase = null; -var currentPhaseFiber = null; -// Did lifecycle hook schedule an update? This is often a performance problem, +var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. + var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; -var isWaitingForCallback = false; -// During commits, we only show a measurement once per method name // to avoid stretch the commit phase with measurement overhead. + var labelsInCurrentCommit = new Set(); var formatMarkName = function(markName) { @@ -5102,14 +4983,14 @@ var clearMark = function(markName) { var endMark = function(label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); + try { performance.measure(formattedLabel, formattedMarkName); - } catch (err) {} - // If previous mark was missing for some reason, this will throw. + } catch (err) {} // If previous mark was missing for some reason, this will throw. // This could only happen if React crashed in an unexpected place earlier. // Don't pile on with more errors. - // Clear marks immediately to avoid growing buffer. + performance.clearMarks(formattedMarkName); performance.clearMeasures(formattedLabel); }; @@ -5140,8 +5021,8 @@ var beginFiberMark = function(fiber, phase) { // want to stretch the commit phase beyond necessary. return false; } - labelsInCurrentCommit.add(label); + labelsInCurrentCommit.add(label); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; @@ -5178,6 +5059,7 @@ var shouldIgnoreFiber = function(fiber) { case ContextConsumer: case Mode: return true; + default: return false; } @@ -5187,6 +5069,7 @@ var clearPendingPhaseMeasurement = function() { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } + currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; @@ -5196,10 +5079,12 @@ var pauseTimers = function() { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; + while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } + fiber = fiber.return; } }; @@ -5208,6 +5093,7 @@ var resumeTimersRecursively = function(fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } + if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } @@ -5225,12 +5111,12 @@ function recordEffect() { effectCountInCurrentCommit++; } } - function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } + if ( currentPhase !== null && currentPhase !== "componentWillMount" && @@ -5241,143 +5127,125 @@ function recordScheduleUpdate() { } } -function startRequestCallbackTimer() { - if (enableUserTimingAPI) { - if (supportsUserTiming && !isWaitingForCallback) { - isWaitingForCallback = true; - beginMark("(Waiting for async callback...)"); - } - } -} - -function stopRequestCallbackTimer(didExpire) { - if (enableUserTimingAPI) { - if (supportsUserTiming) { - isWaitingForCallback = false; - var warning = didExpire - ? "Update expired; will flush synchronously" - : null; - endMark( - "(Waiting for async callback...)", - "(Waiting for async callback...)", - warning - ); - } - } -} - function startWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, this is the fiber to unwind from. + } // If we pause, this is the fiber to unwind from. + currentFiber = fiber; + if (!beginFiberMark(fiber, null)) { return; } + fiber._debugIsCurrentlyTiming = true; } } - function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // Remember we shouldn't complete measurement for this fiber. + } // Remember we shouldn't complete measurement for this fiber. // Otherwise flamechart will be deep even for small updates. + fiber._debugIsCurrentlyTiming = false; clearFiberMark(fiber, null); } } - function stopWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; endFiberMark(fiber, null, null); } } - function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; var warning = - fiber.tag === SuspenseComponent || - fiber.tag === DehydratedSuspenseComponent + fiber.tag === SuspenseComponent ? "Rendering was suspended" : "An error was thrown inside this error boundary"; endFiberMark(fiber, null, warning); } } - function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + clearPendingPhaseMeasurement(); + if (!beginFiberMark(fiber, phase)) { return; } + currentPhaseFiber = fiber; currentPhase = phase; } } - function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? "Scheduled a cascading update" : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } + currentPhase = null; currentPhaseFiber = null; } } - function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; + if (!supportsUserTiming) { return; } - commitCountInCurrentWorkLoop = 0; - // This is top level call. + + commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. - beginMark("(React Tree Reconciliation)"); - // Resume any measurements that were in progress during the last loop. + + beginMark("(React Tree Reconciliation)"); // Resume any measurements that were in progress during the last loop. + resumeTimers(); } } - function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var warning = null; + if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = "A top-level update interrupted the previous render"; @@ -5389,28 +5257,28 @@ function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { } else if (commitCountInCurrentWorkLoop > 1) { warning = "There were cascading updates"; } + commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? "(React Tree Reconciliation: Completed Root)" - : "(React Tree Reconciliation: Yielded)"; - // Pause any measurements until the next loop. + : "(React Tree Reconciliation: Yielded)"; // Pause any measurements until the next loop. + pauseTimers(); endMark(label, "(React Tree Reconciliation)", warning); } } - function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark("(Committing Changes)"); } } - function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { @@ -5418,35 +5286,36 @@ function stopCommitTimer() { } var warning = null; + if (hasScheduledUpdateInCurrentCommit) { warning = "Lifecycle hook scheduled a cascading update"; } else if (commitCountInCurrentWorkLoop > 0) { warning = "Caused by a cascading update in earlier commit"; } + hasScheduledUpdateInCurrentCommit = false; commitCountInCurrentWorkLoop++; isCommitting = false; labelsInCurrentCommit.clear(); - endMark("(Committing Changes)", "(Committing Changes)", warning); } } - function startCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Snapshot Effects)"); } } - function stopCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5456,22 +5325,22 @@ function stopCommitSnapshotEffectsTimer() { ); } } - function startCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Host Effects)"); } } - function stopCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5481,22 +5350,22 @@ function stopCommitHostEffectsTimer() { ); } } - function startCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Calling Lifecycle Methods)"); } } - function stopCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5508,8 +5377,7 @@ function stopCommitLifeCyclesTimer() { } var valueStack = []; - -var fiberStack = void 0; +var fiberStack; { fiberStack = []; @@ -5528,6 +5396,7 @@ function pop(cursor, fiber) { { warningWithoutStack$1(false, "Unexpected pop."); } + return; } @@ -5538,7 +5407,6 @@ function pop(cursor, fiber) { } cursor.current = valueStack[index]; - valueStack[index] = null; { @@ -5550,7 +5418,6 @@ function pop(cursor, fiber) { function push(cursor, value, fiber) { index++; - valueStack[index] = cursor.current; { @@ -5560,24 +5427,24 @@ function push(cursor, value, fiber) { cursor.current = value; } -var warnedAboutMissingGetChildContext = void 0; +var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; + { Object.freeze(emptyContextObject); -} +} // A cursor to the current merged context object on the stack. + +var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. -// A cursor to the current merged context object on the stack. -var contextStackCursor = createCursor(emptyContextObject); -// A cursor to a boolean indicating whether the context has changed. -var didPerformWorkStackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. +var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. + var previousContext = emptyContextObject; function getUnmaskedContext( @@ -5595,6 +5462,7 @@ function getUnmaskedContext( // previous (parent) context instead for a context provider. return previousContext; } + return contextStackCursor.current; } } @@ -5615,14 +5483,15 @@ function getMaskedContext(workInProgress, unmaskedContext) { } else { var type = workInProgress.type; var contextTypes = type.contextTypes; + if (!contextTypes) { return emptyContextObject; - } - - // Avoid recreating masked context unless unmasked context has changed. + } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. + var instance = workInProgress.stateNode; + if ( instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext @@ -5631,6 +5500,7 @@ function getMaskedContext(workInProgress, unmaskedContext) { } var context = {}; + for (var key in contextTypes) { context[key] = unmaskedContext[key]; } @@ -5644,10 +5514,9 @@ function getMaskedContext(workInProgress, unmaskedContext) { name, getCurrentFiberStackInDev ); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. + if (instance) { cacheContext(workInProgress, unmaskedContext, context); } @@ -5695,15 +5564,11 @@ function pushTopLevelContextObject(fiber, context, didChange) { if (disableLegacyContext) { return; } else { - (function() { - if (!(contextStackCursor.current === emptyContextObject)) { - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(contextStackCursor.current === emptyContextObject)) { + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." + ); + } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -5715,10 +5580,9 @@ function processChildContext(fiber, type, parentContext) { return parentContext; } else { var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== "function") { { var componentName = getComponentName(type) || "Unknown"; @@ -5735,41 +5599,42 @@ function processChildContext(fiber, type, parentContext) { ); } } + return parentContext; } - var childContext = void 0; + var childContext; + { setCurrentPhase("getChildContext"); } + startPhaseTimer(fiber, "getChildContext"); childContext = instance.getChildContext(); stopPhaseTimer(); + { setCurrentPhase(null); } + for (var contextKey in childContext) { - (function() { - if (!(contextKey in childContextTypes)) { - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) - ); - } - })(); + if (!(contextKey in childContextTypes)) { + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } } + { var name = getComponentName(type) || "Unknown"; checkPropTypes( childContextTypes, childContext, "child context", - name, - // In practice, there is one case in which we won't get a stack. It's when + name, // In practice, there is one case in which we won't get a stack. It's when // somebody calls unstable_renderSubtreeIntoContainer() and we process // context from the parent component instance. The stack will be missing // because it's outside of the reconciliation, and so the pointer has not @@ -5778,7 +5643,7 @@ function processChildContext(fiber, type, parentContext) { ); } - return Object.assign({}, parentContext, childContext); + return Object.assign({}, parentContext, {}, childContext); } } @@ -5786,16 +5651,15 @@ function pushContextProvider(workInProgress) { if (disableLegacyContext) { return false; } else { - var instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. + var memoizedMergedChildContext = (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - - // Remember the parent context so we can merge with it later. + emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. + previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push( @@ -5803,7 +5667,6 @@ function pushContextProvider(workInProgress) { didPerformWorkStackCursor.current, workInProgress ); - return true; } } @@ -5813,15 +5676,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { return; } else { var instance = workInProgress.stateNode; - (function() { - if (!instance) { - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!instance) { + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." + ); + } if (didChange) { // Merge parent and own context. @@ -5832,13 +5692,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { type, previousContext ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. + pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. + push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { @@ -5854,40 +5713,38 @@ function findCurrentUnmaskedContext(fiber) { } else { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - (function() { - if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + 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." + ); + } var node = fiber; + do { switch (node.tag) { case HostRoot: return node.stateNode.context; + case ClassComponent: { var Component = node.type; + if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } + break; } } + node = node.return; } while (node !== null); - (function() { - { - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -5915,77 +5772,69 @@ if (enableSchedulerTracing) { // Provide explicit error message when production+profiling bundle of e.g. // react-dom is used with production (non-profiling) bundle of // scheduler/tracing - (function() { - if ( - !( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null - ) - ) { - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) - ); - } - })(); + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + 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" + ); + } } -var fakeCallbackNode = {}; - -// Except for NoPriority, these correspond to Scheduler priorities. We use +var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use // ascending numbers so we can compare them like numbers. They start at 90 to // avoid clashing with Scheduler's priorities. + var ImmediatePriority = 99; var UserBlockingPriority$1 = 98; var NormalPriority = 97; var LowPriority = 96; -var IdlePriority = 95; -// NoPriority is the absence of priority. Also React-only. -var NoPriority = 90; +var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only. +var NoPriority = 90; var shouldYield = Scheduler_shouldYield; -var requestPaint = - // Fall back gracefully if we're running an older version of Scheduler. +var requestPaint = // Fall back gracefully if we're running an older version of Scheduler. Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function() {}; - var syncQueue = null; var immediateQueueCallbackNode = null; var isFlushingSyncQueue = false; -var initialTimeMs = Scheduler_now(); - -// If the initial timestamp is reasonably small, use Scheduler's `now` directly. +var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly. // This will be the case for modern browsers that support `performance.now`. In // older browsers, Scheduler falls back to `Date.now`, which returns a Unix // timestamp. In that case, subtract the module initialization time to simulate // the behavior of performance.now and keep our times small enough to fit // within 32 bits. // TODO: Consider lifting this into Scheduler. + var now = initialTimeMs < 10000 ? Scheduler_now : function() { return Scheduler_now() - initialTimeMs; }; - function getCurrentPriorityLevel() { switch (Scheduler_getCurrentPriorityLevel()) { case Scheduler_ImmediatePriority: return ImmediatePriority; + case Scheduler_UserBlockingPriority: return UserBlockingPriority$1; + case Scheduler_NormalPriority: return NormalPriority; + case Scheduler_LowPriority: return LowPriority; + case Scheduler_IdlePriority: return IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5993,20 +5842,22 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { switch (reactPriorityLevel) { case ImmediatePriority: return Scheduler_ImmediatePriority; + case UserBlockingPriority$1: return Scheduler_UserBlockingPriority; + case NormalPriority: return Scheduler_NormalPriority; + case LowPriority: return Scheduler_LowPriority; + case IdlePriority: return Scheduler_IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -6014,18 +5865,16 @@ function runWithPriority$1(reactPriorityLevel, fn) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_runWithPriority(priorityLevel, fn); } - function scheduleCallback(reactPriorityLevel, callback, options) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_scheduleCallback(priorityLevel, callback, options); } - function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { - syncQueue = [callback]; - // Flush the queue in the next tick, at the earliest. + syncQueue = [callback]; // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl @@ -6035,19 +5884,21 @@ function scheduleSyncCallback(callback) { // we already scheduled one when we created the queue. syncQueue.push(callback); } + return fakeCallbackNode; } - function cancelCallback(callbackNode) { if (callbackNode !== fakeCallbackNode) { Scheduler_cancelCallback(callbackNode); } } - function flushSyncCallbackQueue() { if (immediateQueueCallbackNode !== null) { - Scheduler_cancelCallback(immediateQueueCallbackNode); + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); } + flushSyncCallbackQueueImpl(); } @@ -6056,12 +5907,14 @@ function flushSyncCallbackQueueImpl() { // Prevent re-entrancy. isFlushingSyncQueue = true; var i = 0; + try { var _isSync = true; var queue = syncQueue; runWithPriority$1(ImmediatePriority, function() { for (; i < queue.length; i++) { var callback = queue[i]; + do { callback = callback(_isSync); } while (callback !== null); @@ -6072,8 +5925,8 @@ function flushSyncCallbackQueueImpl() { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); - } - // Resume flushing in the next tick + } // Resume flushing in the next tick + Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueue @@ -6086,9 +5939,9 @@ function flushSyncCallbackQueueImpl() { } var NoMode = 0; -var StrictMode = 1; -// TODO: Remove BatchedMode and ConcurrentMode by reading from the root +var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root // tag instead + var BatchedMode = 2; var ConcurrentMode = 4; var ProfileMode = 8; @@ -6098,20 +5951,27 @@ var ProfileMode = 8; // 0b111111111111111111111111111111 var MAX_SIGNED_31_BIT_INT = 1073741823; -var NoWork = 0; -var Never = 1; +var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that +// Never work can be committed in an inconsistent state without tearing the UI. +// The main example is offscreen content, like a hidden subtree. So one possible +// name is Offscreen. However, it also includes dehydrated Suspense boundaries, +// which are inconsistent in the sense that they haven't finished yet, but +// aren't visibly inconsistent because the server rendered HTML matches what the +// hydrated tree would look like. + +var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in +// order to be consistent. + +var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle var Sync = MAX_SIGNED_31_BIT_INT; var Batched = Sync - 1; - var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = Batched - 1; +var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms. -// 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0); } - function expirationTimeToMs(expirationTime) { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } @@ -6128,13 +5988,11 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { bucketSizeMs / UNIT_SIZE ) ); -} - -// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update +} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update // the names to reflect. + var LOW_PRIORITY_EXPIRATION = 5000; var LOW_PRIORITY_BATCH_SIZE = 250; - function computeAsyncExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -6142,7 +6000,6 @@ function computeAsyncExpiration(currentTime) { LOW_PRIORITY_BATCH_SIZE ); } - function computeSuspenseExpiration(currentTime, timeoutMs) { // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time? return computeExpirationBucket( @@ -6150,9 +6007,7 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { timeoutMs, LOW_PRIORITY_BATCH_SIZE ); -} - -// We intentionally set a higher expiration time for interactive updates in +} // We intentionally set a higher expiration time for interactive updates in // dev than in production. // // If the main thread is being blocked so long that you hit the expiration, @@ -6163,9 +6018,9 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { // // In production we opt for better UX at the risk of masking scheduling // problems, by expiring fast. + var HIGH_PRIORITY_EXPIRATION = 500; var HIGH_PRIORITY_BATCH_SIZE = 100; - function computeInteractiveExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -6178,24 +6033,27 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (expirationTime === Sync) { return ImmediatePriority; } - if (expirationTime === Never) { + + if (expirationTime === Never || expirationTime === Idle) { return IdlePriority; } + var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime); + if (msUntil <= 0) { return ImmediatePriority; } + if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) { return UserBlockingPriority$1; } + if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) { return NormalPriority; - } - - // TODO: Handle LowPriority - + } // TODO: Handle LowPriority // Assume anything lower has idle priority + return IdlePriority; } @@ -6209,15 +6067,17 @@ function is(x, y) { ); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = typeof Object.is === "function" ? Object.is : is; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ + function shallowEqual(objA, objB) { - if (is(objA, objB)) { + if (is$1(objA, objB)) { return true; } @@ -6235,13 +6095,12 @@ function shallowEqual(objA, objB) { if (keysA.length !== keysB.length) { return false; - } + } // Test for A's keys different from B. - // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if ( !hasOwnProperty.call(objB, keysA[i]) || - !is(objA[keysA[i]], objB[keysA[i]]) + !is$1(objA[keysA[i]], objB[keysA[i]]) ) { return false; } @@ -6263,14 +6122,13 @@ function shallowEqual(objA, objB) { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - -var lowPriorityWarning = function() {}; +var lowPriorityWarningWithoutStack = function() {}; { var printWarning = function(format) { for ( var _len = arguments.length, - args = Array(_len > 1 ? _len - 1 : 0), + args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ @@ -6284,9 +6142,11 @@ var lowPriorityWarning = function() {}; format.replace(/%s/g, function() { return args[argIndex++]; }); + if (typeof console !== "undefined") { console.warn(message); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -6295,17 +6155,18 @@ var lowPriorityWarning = function() {}; } catch (x) {} }; - lowPriorityWarning = function(condition, format) { + lowPriorityWarningWithoutStack = function(condition, format) { if (format === undefined) { throw new Error( - "`lowPriorityWarning(condition, format, ...args)` requires a warning " + + "`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning " + "message argument" ); } + if (!condition) { for ( var _len2 = arguments.length, - args = Array(_len2 > 2 ? _len2 - 2 : 0), + args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++ @@ -6313,12 +6174,12 @@ var lowPriorityWarning = function() {}; args[_key2 - 2] = arguments[_key2]; } - printWarning.apply(undefined, [format].concat(args)); + printWarning.apply(void 0, [format].concat(args)); } }; } -var lowPriorityWarning$1 = lowPriorityWarning; +var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack; var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function(fiber, instance) {}, @@ -6331,12 +6192,13 @@ var ReactStrictModeWarnings = { { var findStrictRoot = function(fiber) { var maybeStrictRoot = null; - var node = fiber; + while (node !== null) { if (node.mode & StrictMode) { maybeStrictRoot = node; } + node = node.return; } @@ -6356,9 +6218,8 @@ var ReactStrictModeWarnings = { var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function( @@ -6371,8 +6232,7 @@ var ReactStrictModeWarnings = { } if ( - typeof instance.componentWillMount === "function" && - // Don't warn about react-lifecycles-compat polyfilled components. + typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true ) { pendingComponentWillMountWarnings.push(fiber); @@ -6417,6 +6277,7 @@ var ReactStrictModeWarnings = { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); + if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function(fiber) { componentWillMountUniqueNames.add( @@ -6428,6 +6289,7 @@ var ReactStrictModeWarnings = { } var UNSAFE_componentWillMountUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { UNSAFE_componentWillMountUniqueNames.add( @@ -6439,6 +6301,7 @@ var ReactStrictModeWarnings = { } var componentWillReceivePropsUniqueNames = new Set(); + if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { componentWillReceivePropsUniqueNames.add( @@ -6446,11 +6309,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add( @@ -6458,11 +6321,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); + if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function(fiber) { componentWillUpdateUniqueNames.add( @@ -6470,11 +6333,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { UNSAFE_componentWillUpdateUniqueNames.add( @@ -6482,18 +6345,16 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - - // Finally, we flush all the warnings + } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' + if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); warningWithoutStack$1( false, "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6504,11 +6365,12 @@ var ReactStrictModeWarnings = { var _sortedNames = setToSortedString( UNSAFE_componentWillReceivePropsUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6522,11 +6384,12 @@ var ReactStrictModeWarnings = { var _sortedNames2 = setToSortedString( UNSAFE_componentWillUpdateUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6536,10 +6399,10 @@ var ReactStrictModeWarnings = { if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillMount has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6555,10 +6418,10 @@ var ReactStrictModeWarnings = { componentWillReceivePropsUniqueNames ); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6575,10 +6438,10 @@ var ReactStrictModeWarnings = { if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6590,9 +6453,8 @@ var ReactStrictModeWarnings = { } }; - var pendingLegacyContextWarning = new Map(); + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function( @@ -6600,6 +6462,7 @@ var ReactStrictModeWarnings = { instance ) { var strictRoot = findStrictRoot(fiber); + if (strictRoot === null) { warningWithoutStack$1( false, @@ -6607,9 +6470,8 @@ var ReactStrictModeWarnings = { "This error is likely caused by a bug in React. Please file an issue." ); return; - } + } // Dedup strategy: Warn once per component. - // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } @@ -6625,6 +6487,7 @@ var ReactStrictModeWarnings = { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } + warningsForRoot.push(fiber); } }; @@ -6636,20 +6499,18 @@ var ReactStrictModeWarnings = { uniqueNames.add(getComponentName(fiber.type) || "Component"); didWarnAboutLegacyContext.add(fiber.type); }); - var sortedNames = setToSortedString(uniqueNames); var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); - warningWithoutStack$1( false, - "Legacy context API has been detected within a strict-mode tree: %s" + + "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:" + - "\nhttps://fb.me/react-legacy-context", - strictRootComponentStack, - sortedNames + "\n\nLearn more about this warning here: https://fb.me/react-legacy-context" + + "%s", + sortedNames, + strictRootComponentStack ); }); }; @@ -6665,47 +6526,43 @@ var ReactStrictModeWarnings = { }; } -// Resolves type to a family. +var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -// Used by React Refresh runtime through DevTools Global Hook. - -var resolveFamily = null; -// $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; - var setRefreshHandler = function(handler) { { resolveFamily = handler; } }; - function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } - function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if ( @@ -6717,24 +6574,27 @@ function resolveForwardRefForHotReloading(type) { // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); + if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; + if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } + return syntheticType; } } + return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { @@ -6743,11 +6603,9 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } var prevType = fiber.elementType; - var nextType = element.type; + var nextType = element.type; // If we got here, we know types aren't === equal. - // If we got here, we know types aren't === equal. var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof @@ -6758,8 +6616,10 @@ function isCompatibleFamilyForHotReloading(fiber, element) { if (typeof nextType === "function") { needsCompareFamilies = true; } + break; } + case FunctionComponent: { if (typeof nextType === "function") { needsCompareFamilies = true; @@ -6770,16 +6630,20 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } + break; } + case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { @@ -6789,13 +6653,14 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + default: return false; - } + } // Check if both types have a family and it's the same one. - // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. @@ -6803,50 +6668,52 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } + return false; } } - function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } + if (typeof WeakSet !== "function") { return; } + if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } + failedBoundaries.add(fiber); } } - var scheduleRefresh = function(root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } - var _staleFamilies = update.staleFamilies, - _updatedFamilies = update.updatedFamilies; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function() { scheduleFibersWithFamiliesRecursively( root.current, - _updatedFamilies, - _staleFamilies + updatedFamilies, + staleFamilies ); }); } }; - var scheduleRoot = function(root, element) { { if (root.context !== emptyContextObject) { @@ -6855,8 +6722,11 @@ var scheduleRoot = function(root, element) { // Just ignore. We'll delete this with _renderSubtree code path later. return; } + flushPassiveEffects(); - updateContainerAtExpirationTime(element, root, null, Sync, null); + syncUpdates(function() { + updateContainer(element, root, null, null); + }); } }; @@ -6871,17 +6741,19 @@ function scheduleFibersWithFamiliesRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } @@ -6892,8 +6764,10 @@ function scheduleFibersWithFamiliesRecursively( var needsRender = false; var needsRemount = false; + if (candidateType !== null) { var family = resolveFamily(candidateType); + if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; @@ -6906,6 +6780,7 @@ function scheduleFibersWithFamiliesRecursively( } } } + if (failedBoundaries !== null) { if ( failedBoundaries.has(fiber) || @@ -6918,9 +6793,11 @@ function scheduleFibersWithFamiliesRecursively( if (needsRemount) { fiber._debugNeedsRemount = true; } + if (needsRemount || needsRender) { scheduleWork(fiber, Sync); } + if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively( child, @@ -6928,6 +6805,7 @@ function scheduleFibersWithFamiliesRecursively( staleFamilies ); } + if (sibling !== null) { scheduleFibersWithFamiliesRecursively( sibling, @@ -6965,22 +6843,25 @@ function findHostInstancesForMatchingFibersRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } var didMatch = false; + if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; @@ -7019,26 +6900,32 @@ function findHostInstancesForFiberShallowly(fiber, hostInstances) { fiber, hostInstances ); + if (foundHostInstances) { return; - } - // If we didn't find any host children, fallback to closest host parent. + } // If we didn't find any host children, fallback to closest host parent. + var node = fiber; + while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; + case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; + case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } + if (node.return === null) { throw new Error("Expected to reach root first."); } + node = node.return; } } @@ -7048,30 +6935,35 @@ function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; + while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; - hostInstances.add(node.stateNode); - // There may still be more, so keep searching. + hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === fiber) { return foundHostInstances; } + while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } + return false; } @@ -7080,78 +6972,31 @@ function resolveDefaultProps(Component, baseProps) { // Resolve default props. Taken from ReactElement var props = Object.assign({}, baseProps); var defaultProps = Component.defaultProps; + for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } + return props; } + return baseProps; } - function readLazyComponentType(lazyComponent) { - var status = lazyComponent._status; - var result = lazyComponent._result; - switch (status) { - case Resolved: { - var Component = result; - return Component; - } - case Rejected: { - var error = result; - throw error; - } - case Pending: { - var thenable = result; - throw thenable; - } - default: { - lazyComponent._status = Pending; - var ctor = lazyComponent._ctor; - var _thenable = ctor(); - _thenable.then( - function(moduleObject) { - if (lazyComponent._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === undefined) { - 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 - ); - } - } - lazyComponent._status = Resolved; - lazyComponent._result = defaultExport; - } - }, - function(error) { - if (lazyComponent._status === Pending) { - lazyComponent._status = Rejected; - lazyComponent._result = error; - } - } - ); - // Handle synchronous thenables. - switch (lazyComponent._status) { - case Resolved: - return lazyComponent._result; - case Rejected: - throw lazyComponent._result; - } - lazyComponent._result = _thenable; - throw _thenable; - } + initializeLazyComponentType(lazyComponent); + + if (lazyComponent._status !== Resolved) { + throw lazyComponent._result; } + + return lazyComponent._result; } var valueCursor = createCursor(null); +var rendererSigil; -var rendererSigil = void 0; { // Use this to detect multiple renderers using the same context rendererSigil = {}; @@ -7160,39 +7005,35 @@ var rendererSigil = void 0; var currentlyRenderingFiber = null; var lastContextDependency = null; var lastContextWithAllBitsObserved = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; + { isDisallowedContextReadInDEV = false; } } - function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } - function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } - function pushProvider(providerFiber, nextValue) { var context = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; + { !( context._currentRenderer === undefined || @@ -7209,8 +7050,8 @@ function pushProvider(providerFiber, nextValue) { } } else { push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; + { !( context._currentRenderer2 === undefined || @@ -7227,22 +7068,19 @@ function pushProvider(providerFiber, nextValue) { } } } - function popProvider(providerFiber) { var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - var context = providerFiber.type._context; + if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } - function calculateChangedBits(context, newValue, oldValue) { - if (is(oldValue, newValue)) { + if (is$1(oldValue, newValue)) { // No change return 0; } else { @@ -7261,18 +7099,21 @@ function calculateChangedBits(context, newValue, oldValue) { ) : void 0; } + return changedBits | 0; } } - function scheduleWorkOnParentPath(parent, renderExpirationTime) { // Update the child expiration time of all the ancestors, including // the alternates. var node = parent; + while (node !== null) { var alternate = node.alternate; + if (node.childExpirationTime < renderExpirationTime) { node.childExpirationTime = renderExpirationTime; + if ( alternate !== null && alternate.childExpirationTime < renderExpirationTime @@ -7289,10 +7130,10 @@ function scheduleWorkOnParentPath(parent, renderExpirationTime) { // ancestor path already has sufficient priority. break; } + node = node.return; } } - function propagateContextChange( workInProgress, context, @@ -7300,19 +7141,21 @@ function propagateContextChange( renderExpirationTime ) { var fiber = workInProgress.child; + if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } + while (fiber !== null) { - var nextFiber = void 0; + var nextFiber = void 0; // Visit this fiber. - // Visit this fiber. var list = fiber.dependencies; + if (list !== null) { nextFiber = fiber.child; - var dependency = list.firstContext; + while (dependency !== null) { // Check if the context matches. if ( @@ -7320,22 +7163,23 @@ function propagateContextChange( (dependency.observedBits & changedBits) !== 0 ) { // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var update = createUpdate(renderExpirationTime, null); - update.tag = ForceUpdate; - // TODO: Because we don't have a work-in-progress, this will add the + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. + enqueueUpdate(fiber, update); } if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } + var alternate = fiber.alternate; + if ( alternate !== null && alternate.expirationTime < renderExpirationTime @@ -7343,17 +7187,16 @@ function propagateContextChange( alternate.expirationTime = renderExpirationTime; } - scheduleWorkOnParentPath(fiber.return, renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. - // Mark the expiration time on the list, too. if (list.expirationTime < renderExpirationTime) { list.expirationTime = renderExpirationTime; - } - - // Since we already found a match, we can stop traversing the + } // Since we already found a match, we can stop traversing the // dependency list. + break; } + dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { @@ -7361,26 +7204,36 @@ function propagateContextChange( nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if ( enableSuspenseServerRenderer && - fiber.tag === DehydratedSuspenseComponent + fiber.tag === DehydratedFragment ) { - // If a dehydrated suspense component is in this subtree, we don't know + // If a dehydrated suspense bounudary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is - // mark it as having updates on its children. - if (fiber.expirationTime < renderExpirationTime) { - fiber.expirationTime = renderExpirationTime; + // mark it as having updates. + var parentSuspense = fiber.return; + + if (!(parentSuspense !== null)) { + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + } + + if (parentSuspense.expirationTime < renderExpirationTime) { + parentSuspense.expirationTime = renderExpirationTime; } - var _alternate = fiber.alternate; + + var _alternate = parentSuspense.alternate; + if ( _alternate !== null && _alternate.expirationTime < renderExpirationTime ) { _alternate.expirationTime = renderExpirationTime; - } - // This is intentionally passing this fiber as the parent + } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. - scheduleWorkOnParentPath(fiber, renderExpirationTime); + + scheduleWorkOnParentPath(parentSuspense, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. @@ -7393,46 +7246,49 @@ function propagateContextChange( } else { // No child. Traverse to next sibling. nextFiber = fiber; + while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } + var sibling = nextFiber.sibling; + if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; - } - // No more siblings. Traverse up. + } // No more siblings. Traverse up. + nextFiber = nextFiber.return; } } + fiber = nextFiber; } } - function prepareToReadContext(workInProgress, renderExpirationTime) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; - var dependencies = workInProgress.dependencies; + if (dependencies !== null) { var firstContext = dependencies.firstContext; + if (firstContext !== null) { if (dependencies.expirationTime >= renderExpirationTime) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); - } - // Reset the work-in-progress list + } // Reset the work-in-progress list + dependencies.firstContext = null; } } } - function readContext(context, observedBits) { { // This warning would fire if you read context inside a Hook like useMemo. @@ -7453,7 +7309,8 @@ function readContext(context, observedBits) { } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { - var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. + var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types. + if ( typeof observedBits !== "number" || observedBits === MAX_SIGNED_31_BIT_INT @@ -7472,17 +7329,12 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - (function() { - if (!(currentlyRenderingFiber !== null)) { - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) - ); - } - })(); + if (!(currentlyRenderingFiber !== null)) { + 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()." + ); + } // This is the first dependency for this component. Create a new list. - // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { expirationTime: NoWork, @@ -7494,6 +7346,7 @@ function readContext(context, observedBits) { lastContextDependency = lastContextDependency.next = contextItem; } } + return isPrimaryRenderer ? context._currentValue : context._currentValue2; } @@ -7573,19 +7426,16 @@ function readContext(context, observedBits) { // updates when preceding updates are skipped, the final result is deterministic // regardless of priority. Intermediate state may vary according to system // resources, but the final state is always the same. - var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; -var CaptureUpdate = 3; - -// Global state that is reset at the beginning of calling `processUpdateQueue`. +var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. -var hasForceUpdate = false; -var didWarnUpdateInsideUpdate = void 0; -var currentlyProcessingQueue = void 0; +var hasForceUpdate = false; +var didWarnUpdateInsideUpdate; +var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; @@ -7612,15 +7462,12 @@ function cloneUpdateQueue(currentQueue) { baseState: currentQueue.baseState, firstUpdate: currentQueue.firstUpdate, lastUpdate: currentQueue.lastUpdate, - // TODO: With resuming, if we bail out and resuse the child tree, we should // keep these effects. firstCapturedUpdate: null, lastCapturedUpdate: null, - firstEffect: null, lastEffect: null, - firstCapturedEffect: null, lastCapturedEffect: null }; @@ -7631,17 +7478,17 @@ function createUpdate(expirationTime, suspenseConfig) { var update = { expirationTime: expirationTime, suspenseConfig: suspenseConfig, - tag: UpdateState, payload: null, callback: null, - next: null, nextEffect: null }; + { update.priority = getCurrentPriorityLevel(); } + return update; } @@ -7659,12 +7506,14 @@ function appendUpdateToQueue(queue, update) { function enqueueUpdate(fiber, update) { // Update queues are created lazily. var alternate = fiber.alternate; - var queue1 = void 0; - var queue2 = void 0; + var queue1; + var queue2; + if (alternate === null) { // There's only one fiber. queue1 = fiber.updateQueue; queue2 = null; + if (queue1 === null) { queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); } @@ -7672,6 +7521,7 @@ function enqueueUpdate(fiber, update) { // There are two owners. queue1 = fiber.updateQueue; queue2 = alternate.updateQueue; + if (queue1 === null) { if (queue2 === null) { // Neither fiber has an update queue. Create new ones. @@ -7692,6 +7542,7 @@ function enqueueUpdate(fiber, update) { } } } + if (queue2 === null || queue1 === queue2) { // There's only a single queue. appendUpdateToQueue(queue1, update); @@ -7706,8 +7557,8 @@ function enqueueUpdate(fiber, update) { } else { // Both queues are non-empty. The last update is the same in both lists, // because of structural sharing. So, only append to one of the lists. - appendUpdateToQueue(queue1, update); - // But we still need to update the `lastUpdate` pointer of queue2. + appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2. + queue2.lastUpdate = update; } } @@ -7730,11 +7581,11 @@ function enqueueUpdate(fiber, update) { } } } - function enqueueCapturedUpdate(workInProgress, update) { // Captured updates go into a separate list, and only on the work-in- // progress queue. var workInProgressQueue = workInProgress.updateQueue; + if (workInProgressQueue === null) { workInProgressQueue = workInProgress.updateQueue = createUpdateQueue( workInProgress.memoizedState @@ -7747,9 +7598,8 @@ function enqueueCapturedUpdate(workInProgress, update) { workInProgress, workInProgressQueue ); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. if (workInProgressQueue.lastCapturedUpdate === null) { // This is the first render phase update workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update; @@ -7761,6 +7611,7 @@ function enqueueCapturedUpdate(workInProgress, update) { function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { var current = workInProgress.alternate; + if (current !== null) { // If the work-in-progress queue is equal to the current queue, // we need to clone it first. @@ -7768,6 +7619,7 @@ function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { queue = workInProgress.updateQueue = cloneUpdateQueue(queue); } } + return queue; } @@ -7781,68 +7633,82 @@ function getStateFromUpdate( ) { switch (update.tag) { case ReplaceState: { - var _payload = update.payload; - if (typeof _payload === "function") { + var payload = update.payload; + + if (typeof payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload.call(instance, prevState, nextProps); + payload.call(instance, prevState, nextProps); } } - var nextState = _payload.call(instance, prevState, nextProps); + + var nextState = payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } + return nextState; - } - // State object - return _payload; + } // State object + + return payload; } + case CaptureUpdate: { workInProgress.effectTag = (workInProgress.effectTag & ~ShouldCapture) | DidCapture; } // Intentional fallthrough + case UpdateState: { - var _payload2 = update.payload; - var partialState = void 0; - if (typeof _payload2 === "function") { + var _payload = update.payload; + var partialState; + + if (typeof _payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload2.call(instance, prevState, nextProps); + _payload.call(instance, prevState, nextProps); } } - partialState = _payload2.call(instance, prevState, nextProps); + + partialState = _payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } } else { // Partial state object - partialState = _payload2; + partialState = _payload; } + if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + return Object.assign({}, prevState, partialState); } + case ForceUpdate: { hasForceUpdate = true; return prevState; } } + return prevState; } @@ -7854,50 +7720,47 @@ function processUpdateQueue( renderExpirationTime ) { hasForceUpdate = false; - queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue); { currentlyProcessingQueue = queue; - } + } // These values may change as we process the queue. - // These values may change as we process the queue. var newBaseState = queue.baseState; var newFirstUpdate = null; - var newExpirationTime = NoWork; + var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result. - // Iterate through the list of updates to compute the result. var update = queue.firstUpdate; var resultState = newBaseState; + while (update !== null) { var updateExpirationTime = update.expirationTime; + if (updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstUpdate === null) { // This is the first skipped update. It will be the first update in // the new list. - newFirstUpdate = update; - // Since this is the first update that was skipped, the current result + newFirstUpdate = update; // Since this is the first update that was skipped, the current result // is the new base state. + newBaseState = resultState; - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < updateExpirationTime) { newExpirationTime = updateExpirationTime; } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. // TODO: We should skip this update if it was already committed but currently // we have no way of detecting the difference between a committed and suspended // update here. - markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); + markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result. - // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -7906,11 +7769,13 @@ function processUpdateQueue( props, instance ); - var _callback = update.callback; - if (_callback !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var callback = update.callback; + + if (callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastEffect === null) { queue.firstEffect = queue.lastEffect = update; } else { @@ -7918,30 +7783,31 @@ function processUpdateQueue( queue.lastEffect = update; } } - } - // Continue to the next update. + } // Continue to the next update. + update = update.next; - } + } // Separately, iterate though the list of captured updates. - // Separately, iterate though the list of captured updates. var newFirstCapturedUpdate = null; update = queue.firstCapturedUpdate; + while (update !== null) { var _updateExpirationTime = update.expirationTime; + if (_updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstCapturedUpdate === null) { // This is the first skipped captured update. It will be the first // update in the new list. - newFirstCapturedUpdate = update; - // If this is the first update that was skipped, the current result is + newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is // the new base state. + if (newFirstUpdate === null) { newBaseState = resultState; } - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < _updateExpirationTime) { newExpirationTime = _updateExpirationTime; } @@ -7956,11 +7822,13 @@ function processUpdateQueue( props, instance ); - var _callback2 = update.callback; - if (_callback2 !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var _callback = update.callback; + + if (_callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastCapturedEffect === null) { queue.firstCapturedEffect = queue.lastCapturedEffect = update; } else { @@ -7969,17 +7837,20 @@ function processUpdateQueue( } } } + update = update.next; } if (newFirstUpdate === null) { queue.lastUpdate = null; } + if (newFirstCapturedUpdate === null) { queue.lastCapturedUpdate = null; } else { workInProgress.effectTag |= Callback; } + if (newFirstUpdate === null && newFirstCapturedUpdate === null) { // We processed every update, without skipping. That means the new base // state is the same as the result state. @@ -7988,15 +7859,15 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; - queue.firstCapturedUpdate = newFirstCapturedUpdate; - - // Set the remaining expiration time to be whatever is remaining in the queue. + queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. + + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; @@ -8006,27 +7877,22 @@ function processUpdateQueue( } function callCallback(callback, context) { - (function() { - if (!(typeof callback === "function")) { - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - callback - ) - ); - } - })(); + if (!(typeof callback === "function")) { + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } - function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } - function commitUpdateQueue( finishedWork, finishedQueue, @@ -8042,53 +7908,50 @@ function commitUpdateQueue( if (finishedQueue.lastUpdate !== null) { finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate; finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate; - } - // Clear the list of captured updates. + } // Clear the list of captured updates. + finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null; - } + } // Commit the effects - // Commit the effects commitUpdateEffects(finishedQueue.firstEffect, instance); finishedQueue.firstEffect = finishedQueue.lastEffect = null; - commitUpdateEffects(finishedQueue.firstCapturedEffect, instance); finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null; } function commitUpdateEffects(effect, instance) { while (effect !== null) { - var _callback3 = effect.callback; - if (_callback3 !== null) { + var callback = effect.callback; + + if (callback !== null) { effect.callback = null; - callCallback(_callback3, instance); + callCallback(callback, instance); } + effect = effect.nextEffect; } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - function requestCurrentSuspenseConfig() { return ReactCurrentBatchConfig.suspense; } var fakeInternalInstance = {}; -var isArray$1 = Array.isArray; - -// React.Component uses a shared frozen object by default. +var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. -var emptyRefsObject = new React.Component().refs; -var didWarnAboutStateAssignmentForComponent = void 0; -var didWarnAboutUninitializedState = void 0; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; -var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; -var didWarnAboutUndefinedDerivedState = void 0; -var warnOnUndefinedDerivedState = void 0; -var warnOnInvalidCallback = void 0; -var didWarnAboutDirectlyAssigningPropsToState = void 0; -var didWarnAboutContextTypeAndContextTypes = void 0; -var didWarnAboutInvalidateContextType = void 0; +var emptyRefsObject = new React.Component().refs; +var didWarnAboutStateAssignmentForComponent; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; { didWarnAboutStateAssignmentForComponent = new Set(); @@ -8099,14 +7962,15 @@ var didWarnAboutInvalidateContextType = void 0; didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function(callback, callerName) { if (callback === null || typeof callback === "function") { return; } + var key = callerName + "_" + callback; + if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); warningWithoutStack$1( @@ -8122,6 +7986,7 @@ var didWarnAboutInvalidateContextType = void 0; warnOnUndefinedDerivedState = function(type, partialState) { if (partialState === undefined) { var componentName = getComponentName(type) || "Component"; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); warningWithoutStack$1( @@ -8132,25 +7997,20 @@ var didWarnAboutInvalidateContextType = void 0; ); } } - }; - - // This is so gross but it's at least non-critical and can be removed if + }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. + Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - (function() { - { - throw ReactError( - Error( - "_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)." - ) - ); - } - })(); + { + 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)." + ); + } } }); Object.freeze(fakeInternalInstance); @@ -8179,22 +8039,21 @@ function applyDerivedStateFromProps( { warnOnUndefinedDerivedState(ctor, partialState); - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + var memoizedState = partialState === null || partialState === undefined ? prevState : Object.assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; - - // Once the update queue is empty, persist the derived state onto the + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. + var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null && workInProgress.expirationTime === NoWork) { updateQueue.baseState = memoizedState; } } - var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { @@ -8206,19 +8065,17 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.payload = payload; + if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, "setState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -8231,7 +8088,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ReplaceState; update.payload = payload; @@ -8240,12 +8096,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "replaceState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -8258,7 +8112,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ForceUpdate; @@ -8266,12 +8119,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "forceUpdate"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); } @@ -8287,6 +8138,7 @@ function checkShouldComponentUpdate( nextContext ) { var instance = workInProgress.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { startPhaseTimer(workInProgress, "shouldComponentUpdate"); var shouldUpdate = instance.shouldComponentUpdate( @@ -8321,6 +8173,7 @@ function checkShouldComponentUpdate( function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; + { var name = getComponentName(ctor) || "Component"; var renderPresent = instance.render; @@ -8396,6 +8249,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (ctor.contextTypes) { warningWithoutStack$1( false, @@ -8442,6 +8296,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ) : void 0; + if ( ctor.prototype && ctor.prototype.isPureReactComponent && @@ -8455,6 +8310,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { getComponentName(ctor) || "A pure component" ); } + var noComponentDidUnmount = typeof instance.componentDidUnmount !== "function"; !noComponentDidUnmount @@ -8565,6 +8421,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { ) : void 0; var _state = instance.state; + if (_state && (typeof _state !== "object" || isArray$1(_state))) { warningWithoutStack$1( false, @@ -8572,6 +8429,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (typeof instance.getChildContext === "function") { !(typeof ctor.childContextTypes === "object") ? warningWithoutStack$1( @@ -8587,9 +8445,10 @@ function checkClassInstance(workInProgress, ctor, newProps) { function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates + set(instance, workInProgress); + { instance._reactInternalInstance = fakeInternalInstance; } @@ -8608,8 +8467,7 @@ function constructClassInstance( { if ("contextType" in ctor) { - var isValid = - // Allow null for conditional declaration + var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && @@ -8617,8 +8475,8 @@ function constructClassInstance( if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + if (contextType === undefined) { addendum = " However, it is set to undefined. " + @@ -8638,6 +8496,7 @@ function constructClassInstance( Object.keys(contextType).join(", ") + "}."; } + warningWithoutStack$1( false, "%s defines an invalid contextType. " + @@ -8659,9 +8518,8 @@ function constructClassInstance( context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } + } // Instantiate twice to help detect side-effects. - // Instantiate twice to help detect side-effects. { if ( debugRenderPhaseSideEffects || @@ -8682,6 +8540,7 @@ function constructClassInstance( { if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); warningWithoutStack$1( @@ -8695,11 +8554,10 @@ function constructClassInstance( componentName ); } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. + } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. + if ( typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function" @@ -8707,6 +8565,7 @@ function constructClassInstance( var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; + if ( typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true @@ -8715,6 +8574,7 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillMount === "function") { foundWillMountName = "UNSAFE_componentWillMount"; } + if ( typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true @@ -8725,6 +8585,7 @@ function constructClassInstance( ) { foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; } + if ( typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true @@ -8733,16 +8594,19 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { foundWillUpdateName = "UNSAFE_componentWillUpdate"; } + if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { var _componentName = getComponentName(ctor) || "Component"; + var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); warningWithoutStack$1( @@ -8750,7 +8614,7 @@ function constructClassInstance( "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://fb.me/react-async-component-lifecycle-hooks", + "https://fb.me/react-unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -8762,10 +8626,9 @@ function constructClassInstance( } } } - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. + if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } @@ -8780,6 +8643,7 @@ function callComponentWillMount(workInProgress, instance) { if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } @@ -8796,6 +8660,7 @@ function callComponentWillMount(workInProgress, instance) { getComponentName(workInProgress.type) || "Component" ); } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } @@ -8808,17 +8673,21 @@ function callComponentWillReceiveProps( ) { var oldState = instance.state; startPhaseTimer(workInProgress, "componentWillReceiveProps"); + if (typeof instance.componentWillReceiveProps === "function") { instance.componentWillReceiveProps(newProps, nextContext); } + if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } + stopPhaseTimer(); if (instance.state !== oldState) { { var componentName = getComponentName(workInProgress.type) || "Component"; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); warningWithoutStack$1( @@ -8830,11 +8699,11 @@ function callComponentWillReceiveProps( ); } } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } -} +} // Invokes the mount life-cycles on a previously never rendered instance. -// Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance( workInProgress, ctor, @@ -8849,8 +8718,8 @@ function mountClassInstance( instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; - var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else if (disableLegacyContext) { @@ -8863,6 +8732,7 @@ function mountClassInstance( { if (instance.state === newProps) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); warningWithoutStack$1( @@ -8891,6 +8761,7 @@ function mountClassInstance( } var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8903,6 +8774,7 @@ function mountClassInstance( } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -8911,20 +8783,20 @@ function mountClassInstance( newProps ); instance.state = workInProgress.memoizedState; - } - - // In order to support react-lifecycles-compat polyfilled components, + } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function") ) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. + updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8949,13 +8821,12 @@ function resumeMountClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = oldProps; - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8970,14 +8841,12 @@ function resumeMountClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8994,10 +8863,10 @@ function resumeMountClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -9008,6 +8877,7 @@ function resumeMountClassInstance( ); newState = workInProgress.memoizedState; } + if ( oldProps === newProps && oldState === newState && @@ -9019,6 +8889,7 @@ function resumeMountClassInstance( if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } + return false; } @@ -9053,14 +8924,18 @@ function resumeMountClassInstance( typeof instance.componentWillMount === "function") ) { startPhaseTimer(workInProgress, "componentWillMount"); + if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } + stopPhaseTimer(); } + if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } @@ -9069,24 +8944,20 @@ function resumeMountClassInstance( // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; -} +} // Invokes the update life-cycles and returns false if it shouldn't rerender. -// Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance( current, workInProgress, @@ -9095,16 +8966,15 @@ function updateClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -9115,14 +8985,12 @@ function updateClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -9139,10 +9007,10 @@ function updateClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -9170,6 +9038,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -9178,6 +9047,7 @@ function updateClassInstance( workInProgress.effectTag |= Snapshot; } } + return false; } @@ -9212,17 +9082,22 @@ function updateClassInstance( typeof instance.componentWillUpdate === "function") ) { startPhaseTimer(workInProgress, "componentWillUpdate"); + if (typeof instance.componentWillUpdate === "function") { instance.componentWillUpdate(newProps, newState, nextContext); } + if (typeof instance.UNSAFE_componentWillUpdate === "function") { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } + stopPhaseTimer(); } + if (typeof instance.componentDidUpdate === "function") { workInProgress.effectTag |= Update; } + if (typeof instance.getSnapshotBeforeUpdate === "function") { workInProgress.effectTag |= Snapshot; } @@ -9237,6 +9112,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -9244,40 +9120,38 @@ function updateClassInstance( ) { workInProgress.effectTag |= Snapshot; } - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; } -var didWarnAboutMaps = void 0; -var didWarnAboutGenerators = void 0; -var didWarnAboutStringRefs = void 0; -var ownerHasKeyUseWarning = void 0; -var ownerHasFunctionTypeWarning = void 0; +var didWarnAboutMaps; +var didWarnAboutGenerators; +var didWarnAboutStringRefs; +var ownerHasKeyUseWarning; +var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; - /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ + ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; @@ -9285,30 +9159,29 @@ var warnForMissingKey = function(child) {}; if (child === null || typeof child !== "object") { return; } + if (!child._store || child._store.validated || child.key != null) { return; } - (function() { - if (!(typeof child._store === "object")) { - throw ReactError( - Error( - "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - child._store.validated = true; + if (!(typeof child._store === "object")) { + throw Error( + "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." + ); + } + + child._store.validated = true; var currentComponentErrorInfo = "Each child in a list should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information." + getCurrentFiberStackInDev(); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning$1( false, "Each child in a list should have a unique " + @@ -9322,6 +9195,7 @@ var isArray = Array.isArray; function coerceRef(returnFiber, current$$1, element) { var mixedRef = element.ref; + if ( mixedRef !== null && typeof mixedRef !== "function" && @@ -9332,16 +9206,16 @@ function coerceRef(returnFiber, current$$1, element) { // everyone, because the strict mode case will no longer be relevant if (returnFiber.mode & StrictMode || warnAboutStringRefs) { var componentName = getComponentName(returnFiber.type) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { if (warnAboutStringRefs) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://fb.me/react-strict-mode-string-ref%s", componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber) @@ -9351,14 +9225,14 @@ function coerceRef(returnFiber, current$$1, element) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "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) ); } + didWarnAboutStringRefs[componentName] = true; } } @@ -9366,33 +9240,30 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { var owner = element._owner; - var inst = void 0; + var inst; + if (owner) { var ownerFiber = owner; - (function() { - if (!(ownerFiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) - ); - } - })(); - inst = ownerFiber.stateNode; - } - (function() { - if (!inst) { - throw ReactError( - Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a bug in React. Please file an issue." - ) + + if (!(ownerFiber.tag === ClassComponent)) { + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); } - })(); - var stringRef = "" + mixedRef; - // Check if previous string ref matches new string ref + + inst = ownerFiber.stateNode; + } + + if (!inst) { + throw Error( + "Missing owner for string ref " + + mixedRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + } + + var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + if ( current$$1 !== null && current$$1.ref !== null && @@ -9401,69 +9272,65 @@ function coerceRef(returnFiber, current$$1, element) { ) { return current$$1.ref; } + var ref = function(value) { var refs = inst.refs; + if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = inst.refs = {}; } + if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; + ref._stringRef = stringRef; return ref; } else { - (function() { - if (!(typeof mixedRef === "string")) { - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) - ); - } - })(); - (function() { - if (!element._owner) { - throw ReactError( - Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information." - ) - ); - } - })(); + if (!(typeof mixedRef === "string")) { + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + + if (!element._owner) { + 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." + ); + } } } + return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { if (returnFiber.type !== "textarea") { var addendum = ""; + { addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentFiberStackInDev(); } - (function() { - { - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - (Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." + - addendum - ) - ); - } - })(); + + { + 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 + ); + } } } @@ -9477,38 +9344,39 @@ function warnOnFunctionType() { if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } - ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; + ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning$1( false, "Functions are not valid as a React child. This may happen if " + "you return a Component instead of from render. " + "Or maybe you meant to call this function rather than return it." ); -} - -// This wrapper function exists because I expect to clone the code in each path +} // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. + function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; - } - // Deletions are added in reversed order so we add it to the front. + } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } + childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } @@ -9517,32 +9385,36 @@ function ChildReconciler(shouldTrackSideEffects) { if (!shouldTrackSideEffects) { // Noop. return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by + } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. + var childToDelete = currentFirstChild; + while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } + return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index + // instead. var existingChildren = new Map(); - var existingChild = currentFirstChild; + while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } + existingChild = existingChild.sibling; } + return existingChildren; } @@ -9557,13 +9429,17 @@ function ChildReconciler(shouldTrackSideEffects) { function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; + if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } + var current$$1 = newFiber.alternate; + if (current$$1 !== null) { var oldIndex = current$$1.index; + if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; @@ -9585,6 +9461,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } + return newFiber; } @@ -9614,18 +9491,19 @@ function ChildReconciler(shouldTrackSideEffects) { function updateElement(returnFiber, current$$1, element, expirationTime) { if ( current$$1 !== null && - (current$$1.elementType === element.type || - // Keep this check inline so it only runs on the false path: + (current$$1.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current$$1, element)) ) { // Move based on index var existing = useFiber(current$$1, element.props, expirationTime); existing.ref = coerceRef(returnFiber, current$$1, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { // Insert @@ -9714,16 +9592,19 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } + case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal( newChild, returnFiber.mode, expirationTime ); + _created2.return = returnFiber; return _created2; } @@ -9736,6 +9617,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime, null ); + _created3.return = returnFiber; return _created3; } @@ -9754,7 +9636,6 @@ function ChildReconciler(shouldTrackSideEffects) { function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === "string" || typeof newChild === "number") { @@ -9764,6 +9645,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (key !== null) { return null; } + return updateTextNode( returnFiber, oldFiber, @@ -9785,6 +9667,7 @@ function ChildReconciler(shouldTrackSideEffects) { key ); } + return updateElement( returnFiber, oldFiber, @@ -9795,6 +9678,7 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } } + case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal( @@ -9861,6 +9745,7 @@ function ChildReconciler(shouldTrackSideEffects) { existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment( returnFiber, @@ -9870,6 +9755,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChild.key ); } + return updateElement( returnFiber, _matchedFiber, @@ -9877,11 +9763,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ); } + case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + return updatePortal( returnFiber, _matchedFiber2, @@ -9893,6 +9781,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; + return updateFragment( returnFiber, _matchedFiber3, @@ -9913,32 +9802,37 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } - /** * Warns if there is a duplicate or missing key */ + function warnOnInvalidKey(child, knownKeys) { { if (typeof child !== "object" || child === null) { return knownKeys; } + switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); var key = child.key; + if (typeof key !== "string") { break; } + if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } + if (!knownKeys.has(key)) { knownKeys.add(key); break; } + warning$1( false, "Encountered two children with the same key, `%s`. " + @@ -9949,10 +9843,12 @@ function ChildReconciler(shouldTrackSideEffects) { key ); break; + default: break; } } + return knownKeys; } @@ -9966,7 +9862,6 @@ function ChildReconciler(shouldTrackSideEffects) { // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. - // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in @@ -9974,16 +9869,14 @@ function ChildReconciler(shouldTrackSideEffects) { // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. - { // First, validate keys. var knownKeys = null; + for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9992,11 +9885,11 @@ function ChildReconciler(shouldTrackSideEffects) { var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; @@ -10004,12 +9897,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, newChildren[newIdx], expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -10018,8 +9913,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -10027,7 +9924,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -10038,6 +9937,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -10057,25 +9957,28 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber === null) { continue; } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } + previousNewFiber = _newFiber; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( existingChildren, @@ -10084,6 +9987,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { @@ -10096,12 +10000,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } + previousNewFiber = _newFiber2; } } @@ -10125,24 +10032,19 @@ function ChildReconciler(shouldTrackSideEffects) { ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - (function() { - if (!(typeof iteratorFn === "function")) { - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof iteratorFn === "function")) { + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); + } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if ( - typeof Symbol === "function" && - // $FlowFixMe Flow doesn't know about toStringTag + typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === "Generator" ) { !didWarnAboutGenerators @@ -10156,9 +10058,8 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutGenerators = true; - } + } // Warn about using Maps as children - // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { !didWarnAboutMaps ? warning$1( @@ -10169,14 +10070,16 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutMaps = true; - } - - // First, validate keys. + } // First, validate keys. // We'll get a different iterator later for the main pass. + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) { var knownKeys = null; + var _step = _newChildren.next(); + for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -10185,21 +10088,19 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - (function() { - if (!(newChildren != null)) { - throw ReactError(Error("An iterable object provided no iterator.")); - } - })(); + + if (!(newChildren != null)) { + throw Error("An iterable object provided no iterator."); + } var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; - var step = newChildren.next(); + for ( ; oldFiber !== null && !step.done; @@ -10211,12 +10112,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, step.value, expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -10225,8 +10128,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -10234,7 +10139,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -10245,6 +10152,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -10260,25 +10168,28 @@ function ChildReconciler(shouldTrackSideEffects) { // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, expirationTime); + if (_newFiber3 === null) { continue; } + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } + previousNewFiber = _newFiber3; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( existingChildren, @@ -10287,6 +10198,7 @@ function ChildReconciler(shouldTrackSideEffects) { step.value, expirationTime ); + if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { @@ -10299,12 +10211,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } + previousNewFiber = _newFiber4; } } @@ -10335,9 +10250,9 @@ function ChildReconciler(shouldTrackSideEffects) { var existing = useFiber(currentFirstChild, textContent, expirationTime); existing.return = returnFiber; return existing; - } - // The existing first child is not a text node so we need to create one + } // The existing first child is not a text node so we need to create one // and delete the existing ones. + deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText( textContent, @@ -10356,6 +10271,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = element.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10363,8 +10279,7 @@ function ChildReconciler(shouldTrackSideEffects) { 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: + : child.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) { deleteRemainingChildren(returnFiber, child.sibling); @@ -10377,10 +10292,12 @@ function ChildReconciler(shouldTrackSideEffects) { ); existing.ref = coerceRef(returnFiber, child, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { deleteRemainingChildren(returnFiber, child); @@ -10389,6 +10306,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10407,6 +10325,7 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; @@ -10421,6 +10340,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = portal.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10441,6 +10361,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10451,11 +10372,10 @@ function ChildReconciler(shouldTrackSideEffects) { ); created.return = returnFiber; return created; - } - - // This API will tag the children with the side-effect of the reconciliation + } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. + function reconcileChildFibers( returnFiber, currentFirstChild, @@ -10466,7 +10386,6 @@ function ChildReconciler(shouldTrackSideEffects) { // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]} and <>.... // We treat the ambiguous cases above the same. @@ -10475,11 +10394,11 @@ function ChildReconciler(shouldTrackSideEffects) { newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; - } + } // Handle object types - // Handle object types var isObject = typeof newChild === "object" && newChild !== null; if (isObject) { @@ -10493,6 +10412,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) ); + case REACT_PORTAL_TYPE: return placeSingleChild( reconcileSinglePortal( @@ -10543,6 +10463,7 @@ function ChildReconciler(shouldTrackSideEffects) { warnOnFunctionType(); } } + if (typeof newChild === "undefined" && !isUnkeyedTopLevelFragment) { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, @@ -10551,6 +10472,7 @@ function ChildReconciler(shouldTrackSideEffects) { case ClassComponent: { { var instance = returnFiber.stateNode; + if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; @@ -10560,23 +10482,20 @@ function ChildReconciler(shouldTrackSideEffects) { // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough + case FunctionComponent: { var Component = returnFiber.type; - (function() { - { - throw ReactError( - Error( - (Component.displayName || Component.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) - ); - } - })(); + + { + 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." + ); + } } } - } + } // Remaining cases are all treated as empty. - // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } @@ -10585,13 +10504,10 @@ function ChildReconciler(shouldTrackSideEffects) { var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current$$1, workInProgress) { - (function() { - if (!(current$$1 === null || workInProgress.child === current$$1.child)) { - throw ReactError(Error("Resuming work not yet implemented.")); - } - })(); + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw Error("Resuming work not yet implemented."); + } if (workInProgress.child === null) { return; @@ -10604,8 +10520,8 @@ function cloneChildFibers(current$$1, workInProgress) { currentChild.expirationTime ); workInProgress.child = newChild; - newChild.return = workInProgress; + while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress( @@ -10615,12 +10531,13 @@ function cloneChildFibers(current$$1, workInProgress) { ); newChild.return = workInProgress; } + newChild.sibling = null; -} +} // Reset a workInProgress child set to prepare it for a second pass. -// Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, renderExpirationTime) { var child = workInProgress.child; + while (child !== null) { resetWorkInProgress(child, renderExpirationTime); child = child.sibling; @@ -10628,21 +10545,17 @@ function resetChildFibers(workInProgress, renderExpirationTime) { } var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - (function() { - if (!(c !== NO_CONTEXT)) { - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(c !== NO_CONTEXT)) { + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + return c; } @@ -10654,19 +10567,18 @@ function getRootHostContainer() { function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - // Finally, we need to push the host context to the stack. + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. + push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. + pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } @@ -10685,15 +10597,13 @@ function getHostContext() { function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; - } - - // Track the context and the Fiber that provided it. + } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. + push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } @@ -10709,98 +10619,100 @@ function popHostContext(fiber) { pop(contextFiberStackCursor, fiber); } -var DefaultSuspenseContext = 0; - -// The Suspense Context is split into two parts. The lower bits is +var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. -var SubtreeSuspenseContextMask = 1; - -// Subtree Flags: +var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. -var InvisibleParentSuspenseContext = 1; - -// Shallow Flags: +var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. -var ForceSuspenseFallback = 2; +var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } - function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } - function setShallowSuspenseContext(parentContext, shallowContext) { return (parentContext & SubtreeSuspenseContextMask) | shallowContext; } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } - function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } - function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } -// TODO: This is now an empty object. Should we switch this to a boolean? -// Alternatively we can make this use an effect tag similar to SuspenseList. - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } + return false; } - var props = workInProgress.memoizedProps; - // In order to capture, the Suspense component must have a fallback prop. + + var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop. + if (props.fallback === undefined) { return false; - } - // Regular boundaries always capture. + } // Regular boundaries always capture. + if (props.unstable_avoidThisFallback !== true) { return true; - } - // If it's a boundary we should avoid, then we prefer to bubble up to the + } // If it's a boundary we should avoid, then we prefer to bubble up to the // parent boundary if it is currently invisible. + if (hasInvisibleParent) { return false; - } - // If the parent is not able to handle it, we must handle it. + } // If the parent is not able to handle it, we must handle it. + return true; } - function findFirstSuspended(row) { var node = row; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - return node; + var dehydrated = state.dehydrated; + + if ( + dehydrated === null || + isSuspenseInstancePending(dehydrated) || + isSuspenseInstanceFallback(dehydrated) + ) { + return node; + } } } else if ( - node.tag === SuspenseListComponent && - // revealOrder undefined can't be trusted because it don't + node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { var didSuspend = (node.effectTag & DidCapture) !== NoEffect; + if (didSuspend) { return node; } @@ -10809,37 +10721,32 @@ function findFirstSuspended(row) { node = node.child; continue; } + if (node === row) { return null; } + while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - return null; -} -function createResponderListener(responder, props) { - var eventResponderListener = { - responder: responder, - props: props - }; - { - Object.freeze(eventResponderListener); - } - return eventResponderListener; + return null; } +var emptyObject$1 = {}; +var isArray$2 = Array.isArray; function createResponderInstance( responder, responderProps, responderState, - target, fiber ) { return { @@ -10847,75 +10754,263 @@ function createResponderInstance( props: responderProps, responder: responder, rootEventTypes: null, - state: responderState, - target: target + state: responderState }; } -var NoEffect$1 = /* */ 0; -var UnmountSnapshot = /* */ 2; -var UnmountMutation = /* */ 4; -var MountMutation = /* */ 8; -var UnmountLayout = /* */ 16; -var MountLayout = /* */ 32; -var MountPassive = /* */ 64; -var UnmountPassive = /* */ 128; +function mountEventResponder$1( + responder, + responderProps, + fiber, + respondersMap, + rootContainerInstance +) { + var responderState = emptyObject$1; + var getInitialState = responder.getInitialState; -var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + if (getInitialState !== null) { + responderState = getInitialState(responderProps); + } -var didWarnAboutMismatchedHooksForComponent = void 0; -{ - didWarnAboutMismatchedHooksForComponent = new Set(); -} + var responderInstance = createResponderInstance( + responder, + responderProps, + responderState, + fiber + ); -// These are set right before calling the component. -var renderExpirationTime$1 = NoWork; -// The work-in-progress fiber. I've named it differently to distinguish it from -// the work-in-progress hook. -var currentlyRenderingFiber$1 = null; + if (!rootContainerInstance) { + var node = fiber; -// Hooks are stored as a linked list on the fiber's memoizedState field. The -// current hook list is the list that belongs to the current fiber. The -// work-in-progress hook list is a new list that will be added to the -// work-in-progress fiber. -var currentHook = null; -var nextCurrentHook = null; -var firstWorkInProgressHook = null; -var workInProgressHook = null; -var nextWorkInProgressHook = null; + while (node !== null) { + var tag = node.tag; -var remainingExpirationTime = NoWork; -var componentUpdateQueue = null; -var sideEffectTag = 0; + if (tag === HostComponent) { + rootContainerInstance = node.stateNode; + break; + } else if (tag === HostRoot) { + rootContainerInstance = node.stateNode.containerInfo; + break; + } -// Updates scheduled during render will trigger an immediate re-render at the -// end of the current pass. We can't store these updates on the normal queue, -// because if the work is aborted, they should be discarded. Because this is -// a relatively rare case, we also don't want to add an additional field to -// either the hook or queue object types. So we store them in a lazily create -// map of queue -> render-phase updates, which are discarded once the component -// completes without re-rendering. + node = node.return; + } + } -// Whether an update was scheduled during the currently executing render pass. -var didScheduleRenderPhaseUpdate = false; -// Lazily created map of render-phase updates -var renderPhaseUpdates = null; -// Counter to prevent infinite loops. -var numberOfReRenders = 0; -var RE_RENDER_LIMIT = 25; + mountResponderInstance( + responder, + responderInstance, + responderProps, + responderState, + rootContainerInstance + ); + respondersMap.set(responder, responderInstance); +} -// In DEV, this is the name of the currently executing primitive hook -var currentHookNameInDev = null; +function updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance +) { + var responder; + var props; -// In DEV, this list ensures that hooks are called in the same order between renders. -// The list stores the order of hooks used during the initial render (mount). -// Subsequent renders (updates) reference this list. -var hookTypesDev = null; -var hookTypesUpdateIndexDev = -1; + if (listener) { + responder = listener.responder; + props = listener.props; + } -// In DEV, this tracks whether currently rendering component needs to ignore + if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { + throw Error( + "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()." + ); + } + + var listenerProps = props; + + if (visistedResponders.has(responder)) { + // show warning + { + 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 + ); + } + + return; + } + + visistedResponders.add(responder); + var responderInstance = respondersMap.get(responder); + + if (responderInstance === undefined) { + // Mount (happens in either complete or commit phase) + mountEventResponder$1( + responder, + listenerProps, + fiber, + respondersMap, + rootContainerInstance + ); + } else { + // Update (happens during commit phase only) + responderInstance.props = listenerProps; + responderInstance.fiber = fiber; + } +} + +function updateEventListeners(listeners, fiber, rootContainerInstance) { + var visistedResponders = new Set(); + var dependencies = fiber.dependencies; + + if (listeners != null) { + if (dependencies === null) { + dependencies = fiber.dependencies = { + expirationTime: NoWork, + firstContext: null, + responders: new Map() + }; + } + + var respondersMap = dependencies.responders; + + if (respondersMap === null) { + respondersMap = new Map(); + } + + if (isArray$2(listeners)) { + for (var i = 0, length = listeners.length; i < length; i++) { + var listener = listeners[i]; + updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } else { + updateEventListener( + listeners, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } + + if (dependencies !== null) { + var _respondersMap = dependencies.responders; + + if (_respondersMap !== null) { + // Unmount + var mountedResponders = Array.from(_respondersMap.keys()); + + for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { + var mountedResponder = mountedResponders[_i]; + + if (!visistedResponders.has(mountedResponder)) { + var responderInstance = _respondersMap.get(mountedResponder); + + unmountResponderInstance(responderInstance); + + _respondersMap.delete(mountedResponder); + } + } + } + } +} +function createResponderListener(responder, props) { + var eventResponderListener = { + responder: responder, + props: props + }; + + { + Object.freeze(eventResponderListener); + } + + return eventResponderListener; +} + +var NoEffect$1 = + /* */ + 0; +var UnmountSnapshot = + /* */ + 2; +var UnmountMutation = + /* */ + 4; +var MountMutation = + /* */ + 8; +var UnmountLayout = + /* */ + 16; +var MountLayout = + /* */ + 32; +var MountPassive = + /* */ + 64; +var UnmountPassive = + /* */ + 128; + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var didWarnAboutMismatchedHooksForComponent; + +{ + didWarnAboutMismatchedHooksForComponent = new Set(); +} + +// These are set right before calling the component. +var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from +// the work-in-progress hook. + +var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The +// current hook list is the list that belongs to the current fiber. The +// work-in-progress hook list is a new list that will be added to the +// work-in-progress fiber. + +var currentHook = null; +var nextCurrentHook = null; +var firstWorkInProgressHook = null; +var workInProgressHook = null; +var nextWorkInProgressHook = null; +var remainingExpirationTime = NoWork; +var componentUpdateQueue = null; +var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the +// end of the current pass. We can't store these updates on the normal queue, +// because if the work is aborted, they should be discarded. Because this is +// a relatively rare case, we also don't want to add an additional field to +// either the hook or queue object types. So we store them in a lazily create +// map of queue -> render-phase updates, which are discarded once the component +// completes without re-rendering. +// Whether an update was scheduled during the currently executing render pass. + +var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook + +var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. +// The list stores the order of hooks used during the initial render (mount). +// Subsequent renders (updates) reference this list. + +var hookTypesDev = null; +var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. + var ignorePreviousDependencies = false; function mountHookTypesDev() { @@ -10936,6 +11031,7 @@ function updateHookTypesDev() { if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } @@ -10962,29 +11058,26 @@ function checkDepsAreArrayDev(deps) { function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentName(currentlyRenderingFiber$1.type); + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ""; - var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - - var row = i + 1 + ". " + oldHookName; - - // Extra space so second column lines up + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { row += " "; } row += newHookName + "\n"; - table += row; } @@ -11006,15 +11099,11 @@ function warnOnHookMismatchInDev(currentHookName) { } function throwInvalidHookError() { - (function() { - { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) - ); - } - })(); + { + 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." + ); + } } function areHookInputsEqual(nextDeps, prevDeps) { @@ -11035,6 +11124,7 @@ function areHookInputsEqual(nextDeps, prevDeps) { currentHookNameInDev ); } + return false; } @@ -11054,12 +11144,15 @@ function areHookInputsEqual(nextDeps, prevDeps) { ); } } + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (is(nextDeps[i], prevDeps[i])) { + if (is$1(nextDeps[i], prevDeps[i])) { continue; } + return false; } + return true; } @@ -11077,31 +11170,26 @@ function renderWithHooks( { hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: + hookTypesUpdateIndexDev = -1; // Used for hot reloading: + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - // The following should have already been reset + } // The following should have already been reset // currentHook = null; // workInProgressHook = null; - // remainingExpirationTime = NoWork; // componentUpdateQueue = null; - // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; // sideEffectTag = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because nextCurrentHook === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so nextCurrentHook would be null during updates and mounts. + { if (nextCurrentHook !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; @@ -11123,16 +11211,15 @@ function renderWithHooks( do { didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; + { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; - } + } // Start over from the beginning of the list - // Start over from the beginning of the list nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; - currentHook = null; workInProgressHook = null; componentUpdateQueue = null; @@ -11143,20 +11230,16 @@ function renderWithHooks( } ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - children = Component(props, refOrContext); } while (didScheduleRenderPhaseUpdate); renderPhaseUpdates = null; numberOfReRenders = 0; - } - - // We can assume the previous dispatcher is always this one, since we set it + } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; var renderedWork = currentlyRenderingFiber$1; - renderedWork.memoizedState = firstWorkInProgressHook; renderedWork.expirationTime = remainingExpirationTime; renderedWork.updateQueue = componentUpdateQueue; @@ -11164,15 +11247,12 @@ function renderWithHooks( { renderedWork._debugHookTypes = hookTypesDev; - } - - // This check uses currentHook so that it works the same in DEV and prod bundles. + } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -11187,45 +11267,36 @@ function renderWithHooks( remainingExpirationTime = NoWork; componentUpdateQueue = null; - sideEffectTag = 0; - - // These were reset above + sideEffectTag = 0; // These were reset above // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; - (function() { - if (!!didRenderTooFewHooks) { - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) - ); - } - })(); + if (!!didRenderTooFewHooks) { + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } return children; } - function bailoutHooks(current, workInProgress, expirationTime) { workInProgress.updateQueue = current.updateQueue; workInProgress.effectTag &= ~(Passive | Update); + if (current.expirationTime <= expirationTime) { current.expirationTime = NoWork; } } - function resetHooks() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - // This is used to reset the state of this module when a component throws. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws. // It's also called inside mountIndeterminateComponent if we determine the // component is a module-style component. + renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -11235,14 +11306,12 @@ function resetHooks() { { hookTypesDev = null; hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -11251,11 +11320,9 @@ function resetHooks() { function mountWorkInProgressHook() { var hook = { memoizedState: null, - baseState: null, queue: null, baseUpdate: null, - next: null }; @@ -11266,6 +11333,7 @@ function mountWorkInProgressHook() { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } + return workInProgressHook; } @@ -11279,27 +11347,20 @@ function updateWorkInProgressHook() { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - (function() { - if (!(nextCurrentHook !== null)) { - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); - } - })(); - currentHook = nextCurrentHook; + if (!(nextCurrentHook !== null)) { + throw Error("Rendered more hooks than during the previous render."); + } + currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, queue: currentHook.queue, baseUpdate: currentHook.baseUpdate, - next: null }; @@ -11310,8 +11371,10 @@ function updateWorkInProgressHook() { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } + nextCurrentHook = currentHook.next; } + return workInProgressHook; } @@ -11327,12 +11390,14 @@ function basicStateReducer(state, action) { function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); - var initialState = void 0; + var initialState; + if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11341,8 +11406,7 @@ function mountReducer(reducer, initialArg, init) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11352,68 +11416,67 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - (function() { - if (!(queue !== null)) { - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(queue !== null)) { + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + } queue.lastRenderedReducer = reducer; if (numberOfReRenders > 0) { // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. var _dispatch = queue.dispatch; + if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = hook.memoizedState; var update = firstRenderPhaseUpdate; + do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. - var _action = update.action; - newState = reducer(newState, _action); + var action = update.action; + newState = reducer(newState, action); update = update.next; - } while (update !== null); - - // Mark that the fiber performed work, but only if the new state is + } while (update !== null); // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(newState, hook.memoizedState)) { + + if (!is$1(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } - hook.memoizedState = newState; - // Don't persist the state accumulated from the render phase updates to + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. + if (hook.baseUpdate === queue.last) { hook.baseState = newState; } queue.lastRenderedState = newState; - return [newState, _dispatch]; } } + return [hook.memoizedState, _dispatch]; - } + } // The last update in the entire queue + + var last = queue.last; // The last update that is part of the base state. - // The last update in the entire queue - var last = queue.last; - // The last update that is part of the base state. var baseUpdate = hook.baseUpdate; - var baseState = hook.baseState; + var baseState = hook.baseState; // Find the first unprocessed update. + + var first; - // Find the first unprocessed update. - var first = void 0; if (baseUpdate !== null) { if (last !== null) { // For the first update, the queue is a circular linked list where @@ -11421,10 +11484,12 @@ function updateReducer(reducer, initialArg, init) { // the `baseUpdate` is no longer empty, we can unravel the list. last.next = null; } + first = baseUpdate.next; } else { first = last !== null ? last.next : null; } + if (first !== null) { var _newState = baseState; var newBaseState = null; @@ -11432,8 +11497,10 @@ function updateReducer(reducer, initialArg, init) { var prevUpdate = baseUpdate; var _update = first; var didSkip = false; + do { var updateExpirationTime = _update.expirationTime; + if (updateExpirationTime < renderExpirationTime$1) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base @@ -11442,14 +11509,14 @@ function updateReducer(reducer, initialArg, init) { didSkip = true; newBaseUpdate = prevUpdate; newBaseState = _newState; - } - // Update the remaining priority in the queue. + } // Update the remaining priority in the queue. + if (updateExpirationTime > remainingExpirationTime) { remainingExpirationTime = updateExpirationTime; + markUnprocessedUpdateTime(remainingExpirationTime); } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. @@ -11459,18 +11526,18 @@ function updateReducer(reducer, initialArg, init) { markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig - ); + ); // Process this update. - // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the // current reducer, we can use the eagerly computed state. _newState = _update.eagerState; } else { - var _action2 = _update.action; - _newState = reducer(_newState, _action2); + var _action = _update.action; + _newState = reducer(_newState, _action); } } + prevUpdate = _update; _update = _update.next; } while (_update !== null && _update !== first); @@ -11478,18 +11545,16 @@ function updateReducer(reducer, initialArg, init) { if (!didSkip) { newBaseUpdate = prevUpdate; newBaseState = _newState; - } - - // Mark that the fiber performed work, but only if the new state is + } // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(_newState, hook.memoizedState)) { + + if (!is$1(_newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = _newState; hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.lastRenderedState = _newState; } @@ -11499,9 +11564,11 @@ function updateReducer(reducer, initialArg, init) { function mountState(initialState) { var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { initialState = initialState(); } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11510,8 +11577,7 @@ function mountState(initialState) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11531,29 +11597,36 @@ function pushEffect(tag, create, destroy, deps) { // Circular next: null }; + if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); componentUpdateQueue.lastEffect = effect.next = effect; } else { - var _lastEffect = componentUpdateQueue.lastEffect; - if (_lastEffect === null) { + var lastEffect = componentUpdateQueue.lastEffect; + + if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { - var firstEffect = _lastEffect.next; - _lastEffect.next = effect; + var firstEffect = lastEffect.next; + lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } + return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); - var ref = { current: initialValue }; + var ref = { + current: initialValue + }; + { Object.seal(ref); } + hook.memoizedState = ref; return ref; } @@ -11578,8 +11651,10 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; + if (nextDeps !== null) { var prevDeps = prevEffect.deps; + if (areHookInputsEqual(nextDeps, prevDeps)) { pushEffect(NoEffect$1, create, destroy, nextDeps); return; @@ -11598,6 +11673,7 @@ function mountEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return mountEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11613,6 +11689,7 @@ function updateEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return updateEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11632,13 +11709,16 @@ function updateLayoutEffect(create, deps) { function imperativeHandleEffect(create, ref) { if (typeof ref === "function") { var refCallback = ref; + var _inst = create(); + refCallback(_inst); return function() { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; + { !refObject.hasOwnProperty("current") ? warning$1( @@ -11649,7 +11729,9 @@ function imperativeHandleEffect(create, ref) { ) : void 0; } + var _inst2 = create(); + refObject.current = _inst2; return function() { refObject.current = null; @@ -11667,12 +11749,10 @@ function mountImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return mountEffectImpl( Update, UnmountMutation | MountLayout, @@ -11691,12 +11771,10 @@ function updateImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl( Update, UnmountMutation | MountLayout, @@ -11724,14 +11802,17 @@ function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + hook.memoizedState = [callback, nextDeps]; return callback; } @@ -11748,33 +11829,32 @@ function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function dispatchAction(fiber, queue, action) { - (function() { - if (!(numberOfReRenders < RE_RENDER_LIMIT)) { - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) - ); - } - })(); + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } { - !(arguments.length <= 3) + !(typeof arguments[3] !== "function") ? warning$1( false, "State updates from the useState() and useReducer() Hooks don't support the " + @@ -11785,6 +11865,7 @@ function dispatchAction(fiber, queue, action) { } var alternate = fiber.alternate; + if ( fiber === currentlyRenderingFiber$1 || (alternate !== null && alternate === currentlyRenderingFiber$1) @@ -11801,39 +11882,40 @@ function dispatchAction(fiber, queue, action) { eagerState: null, next: null }; + { update.priority = getCurrentPriorityLevel(); } + if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } + lastRenderPhaseUpdate.next = update; } } else { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } - var currentTime = requestCurrentTime(); - var _suspenseConfig = requestCurrentSuspenseConfig(); - var _expirationTime = computeExpirationForFiber( + var suspenseConfig = requestCurrentSuspenseConfig(); + var expirationTime = computeExpirationForFiber( currentTime, fiber, - _suspenseConfig + suspenseConfig ); - var _update2 = { - expirationTime: _expirationTime, - suspenseConfig: _suspenseConfig, + expirationTime: expirationTime, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, @@ -11842,21 +11924,24 @@ function dispatchAction(fiber, queue, action) { { _update2.priority = getCurrentPriorityLevel(); - } + } // Append the update to the end of the list. + + var last = queue.last; - // Append the update to the end of the list. - var _last = queue.last; - if (_last === null) { + if (last === null) { // This is the first update. Create a circular list. _update2.next = _update2; } else { - var first = _last.next; + var first = last.next; + if (first !== null) { // Still circular. _update2.next = first; } - _last.next = _update2; + + last.next = _update2; } + queue.last = _update2; if ( @@ -11866,23 +11951,27 @@ function dispatchAction(fiber, queue, action) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. - var _lastRenderedReducer = queue.lastRenderedReducer; - if (_lastRenderedReducer !== null) { - var prevDispatcher = void 0; + var lastRenderedReducer = queue.lastRenderedReducer; + + if (lastRenderedReducer !== null) { + var prevDispatcher; + { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } + try { var currentState = queue.lastRenderedState; - var _eagerState = _lastRenderedReducer(currentState, action); - // Stash the eagerly computed state, and the reducer used to compute + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. - _update2.eagerReducer = _lastRenderedReducer; - _update2.eagerState = _eagerState; - if (is(_eagerState, currentState)) { + + _update2.eagerReducer = lastRenderedReducer; + _update2.eagerState = eagerState; + + if (is$1(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that @@ -11898,6 +11987,7 @@ function dispatchAction(fiber, queue, action) { } } } + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -11905,13 +11995,13 @@ function dispatchAction(fiber, queue, action) { warnIfNotCurrentlyActingUpdatesInDev(fiber); } } - scheduleWork(fiber, _expirationTime); + + scheduleWork(fiber, expirationTime); } } var ContextOnlyDispatcher = { readContext: readContext, - useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, @@ -11924,7 +12014,6 @@ var ContextOnlyDispatcher = { useDebugValue: throwInvalidHookError, useResponder: throwInvalidHookError }; - var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; @@ -11991,6 +12080,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12002,6 +12092,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12018,6 +12109,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12035,7 +12127,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -12070,6 +12161,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12081,6 +12173,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12097,6 +12190,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12114,7 +12208,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -12149,6 +12242,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -12160,6 +12254,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -12176,6 +12271,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -12193,7 +12289,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -12235,6 +12330,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -12247,6 +12343,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -12265,6 +12362,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -12284,7 +12382,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -12326,6 +12423,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -12338,6 +12436,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -12356,6 +12455,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -12377,10 +12477,9 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }; } -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. -var now$1 = Scheduler.unstable_now; +var now$1 = Scheduler.unstable_now; var commitTime = 0; var profilerStartTime = -1; @@ -12392,6 +12491,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } + commitTime = now$1(); } @@ -12411,6 +12511,7 @@ function stopProfilerTimerIfRunning(fiber) { if (!enableProfilerTimer) { return; } + profilerStartTime = -1; } @@ -12422,15 +12523,17 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } + profilerStartTime = -1; } } -// The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. + var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; @@ -12458,12 +12561,14 @@ function enterHydrationState(fiber) { return true; } -function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) { +function reenterHydrationStateFromDehydratedSuspenseInstance( + fiber, + suspenseInstance +) { if (!supportsHydration) { return false; } - var suspenseInstance = fiber.stateNode; nextHydratableInstance = getNextHydratableSibling(suspenseInstance); popToNextHostParent(fiber); isHydrating = true; @@ -12479,6 +12584,7 @@ function deleteHydratableInstance(returnFiber, instance) { instance ); break; + case HostComponent: didNotHydrateInstance( returnFiber.type, @@ -12493,13 +12599,12 @@ function deleteHydratableInstance(returnFiber, instance) { var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; - childToDelete.effectTag = Deletion; - - // This might seem like it belongs on progressedFirstDeletion. However, + childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However, // these children are not part of the reconciliation list of children. // Even if we abort and rereconcile the children, that will try to hydrate // again and the nodes are still in the host tree so these will be // recreated. + if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; @@ -12509,31 +12614,38 @@ function deleteHydratableInstance(returnFiber, instance) { } function insertNonHydratedInstance(returnFiber, fiber) { - fiber.effectTag |= Placement; + fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement; + { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; + switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableContainerInstance(parentContainer, type, props); break; + case HostText: var text = fiber.pendingProps; didNotFindHydratableContainerTextInstance(parentContainer, text); break; + case SuspenseComponent: didNotFindHydratableContainerSuspenseInstance(parentContainer); break; } + break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; + switch (fiber.tag) { case HostComponent: var _type = fiber.type; @@ -12546,6 +12658,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _props ); break; + case HostText: var _text = fiber.pendingProps; didNotFindHydratableTextInstance( @@ -12555,6 +12668,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _text ); break; + case SuspenseComponent: didNotFindHydratableSuspenseInstance( parentType, @@ -12563,8 +12677,10 @@ function insertNonHydratedInstance(returnFiber, fiber) { ); break; } + break; } + default: return; } @@ -12577,33 +12693,53 @@ function tryHydrate(fiber, nextInstance) { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type, props); + if (instance !== null) { fiber.stateNode = instance; return true; } + return false; } + case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); + if (textInstance !== null) { fiber.stateNode = textInstance; return true; } + return false; } + case SuspenseComponent: { if (enableSuspenseServerRenderer) { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); + if (suspenseInstance !== null) { - // Downgrade the tag to a dehydrated component until we've hydrated it. - fiber.tag = DehydratedSuspenseComponent; - fiber.stateNode = suspenseInstance; + var suspenseState = { + dehydrated: suspenseInstance, + retryTime: Never + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. + + var dehydratedFragment = createFiberFromDehydratedFragment( + suspenseInstance + ); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; return true; } } + return false; } + default: return false; } @@ -12613,7 +12749,9 @@ function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } + var nextInstance = nextHydratableInstance; + if (!nextInstance) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); @@ -12621,25 +12759,29 @@ function tryToClaimNextHydratableInstance(fiber) { hydrationParentFiber = fiber; return; } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; - } - // We matched the next one, we'll now assume that the first one was + } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. + deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance); } + hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(nextInstance); } @@ -12650,15 +12792,11 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var instance = fiber.stateNode; @@ -12669,38 +12807,37 @@ function prepareToHydrateHostInstance( rootContainerInstance, hostContext, fiber - ); - // TODO: Type this specific to this type of component. - fiber.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. + if (updatePayload !== null) { return true; } + return false; } function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); + { if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { @@ -12712,6 +12849,7 @@ function prepareToHydrateHostTextInstance(fiber) { ); break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; @@ -12729,46 +12867,66 @@ function prepareToHydrateHostTextInstance(fiber) { } } } + return shouldUpdate; } -function skipPastDehydratedSuspenseInstance(fiber) { +function prepareToHydrateHostSuspenseInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } - var suspenseInstance = fiber.stateNode; - (function() { - if (!suspenseInstance) { - throw ReactError( - Error( - "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." - ) + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + hydrateSuspenseInstance(suspenseInstance, fiber); +} + +function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + { + throw Error( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." ); } - })(); - nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( - suspenseInstance - ); + } + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; + while ( parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && - parent.tag !== DehydratedSuspenseComponent + parent.tag !== SuspenseComponent ) { parent = parent.return; } + hydrationParentFiber = parent; } @@ -12776,11 +12934,13 @@ function popHydrationState(fiber) { if (!supportsHydration) { return false; } + if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } + if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our @@ -12790,13 +12950,12 @@ function popHydrationState(fiber) { return false; } - var type = fiber.type; - - // If we have any remaining hydratable nodes, we need to delete them now. + var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. // TODO: Better heuristic. + if ( fiber.tag !== HostComponent || (type !== "head" && @@ -12804,6 +12963,7 @@ function popHydrationState(fiber) { !shouldSetTextContent(type, fiber.memoizedProps)) ) { var nextInstance = nextHydratableInstance; + while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); @@ -12811,9 +12971,15 @@ function popHydrationState(fiber) { } popToNextHostParent(fiber); - nextHydratableInstance = hydrationParentFiber - ? getNextHydratableSibling(fiber.stateNode) - : null; + + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber + ? getNextHydratableSibling(fiber.stateNode) + : null; + } + return true; } @@ -12828,19 +12994,17 @@ function resetHydrationState() { } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - -var didWarnAboutBadClass = void 0; -var didWarnAboutModulePatternComponent = void 0; -var didWarnAboutContextTypeOnFunctionComponent = void 0; -var didWarnAboutGetDerivedStateOnFunctionComponent = void 0; -var didWarnAboutFunctionRefs = void 0; -var didWarnAboutReassigningProps = void 0; -var didWarnAboutMaxDuration = void 0; -var didWarnAboutRevealOrder = void 0; -var didWarnAboutTailOptions = void 0; -var didWarnAboutDefaultPropsOnFunctionComponent = void 0; +var didWarnAboutBadClass; +var didWarnAboutModulePatternComponent; +var didWarnAboutContextTypeOnFunctionComponent; +var didWarnAboutGetDerivedStateOnFunctionComponent; +var didWarnAboutFunctionRefs; +var didWarnAboutReassigningProps; +var didWarnAboutMaxDuration; +var didWarnAboutRevealOrder; +var didWarnAboutTailOptions; +var didWarnAboutDefaultPropsOnFunctionComponent; { didWarnAboutBadClass = {}; @@ -12876,7 +13040,6 @@ function reconcileChildren( // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers( @@ -12907,11 +13070,11 @@ function forceUnmountCurrentAndReconcile( current$$1.child, null, renderExpirationTime - ); - // In the second pass, we mount the new children. The trick here is that we + ); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their their // identity matches. + workInProgress.child = reconcileChildFibers( workInProgress, null, @@ -12930,12 +13093,12 @@ function updateForwardRef( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12949,11 +13112,11 @@ function updateForwardRef( } var render = Component.render; - var ref = workInProgress.ref; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - // The rest is a fork of updateFunctionComponent - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12965,6 +13128,7 @@ function updateForwardRef( ref, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12982,6 +13146,7 @@ function updateForwardRef( ); } } + setCurrentPhase(null); } @@ -12992,9 +13157,8 @@ function updateForwardRef( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -13015,24 +13179,27 @@ function updateMemoComponent( ) { if (current$$1 === null) { var type = Component.type; + if ( isSimpleFunctionComponent(type) && - Component.compare === null && - // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined ) { var resolvedType = type; + { resolvedType = resolveFunctionForHotReloading(type); - } - // If this is a plain function component without default props, + } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. + workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; + { validateFunctionComponentInDev(workInProgress, type); } + return updateSimpleMemoComponent( current$$1, workInProgress, @@ -13042,8 +13209,10 @@ function updateMemoComponent( renderExpirationTime ); } + { var innerPropTypes = type.propTypes; + if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -13056,6 +13225,7 @@ function updateMemoComponent( ); } } + var child = createFiberFromTypeAndProps( Component.type, null, @@ -13069,9 +13239,11 @@ function updateMemoComponent( workInProgress.child = child; return child; } + { var _type = Component.type; var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -13084,14 +13256,17 @@ function updateMemoComponent( ); } } + var currentChild = current$$1.child; // This is always exactly one child + if (updateExpirationTime < renderExpirationTime) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; - // Default to shallow comparison + var prevProps = currentChild.memoizedProps; // Default to shallow comparison + var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; + if ( compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref @@ -13102,8 +13277,8 @@ function updateMemoComponent( renderExpirationTime ); } - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; var newChild = createWorkInProgress( currentChild, @@ -13127,19 +13302,21 @@ function updateSimpleMemoComponent( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. outerMemoType = refineResolvedLazyComponent(outerMemoType); } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13148,19 +13325,20 @@ function updateSimpleMemoComponent( getComponentName(outerMemoType), getCurrentFiberStackInDev ); - } - // Inner propTypes will be validated in the function component path. + } // Inner propTypes will be validated in the function component path. } } + if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; + if ( shallowEqual(prevProps, nextProps) && - current$$1.ref === workInProgress.ref && - // Prevent bailout if the implementation changed due to hot reload: + current$$1.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload: workInProgress.type === current$$1.type ) { didReceiveUpdate = false; + if (updateExpirationTime < renderExpirationTime) { return bailoutOnAlreadyFinishedWork( current$$1, @@ -13170,6 +13348,7 @@ function updateSimpleMemoComponent( } } } + return updateFunctionComponent( current$$1, workInProgress, @@ -13205,6 +13384,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren( @@ -13218,6 +13398,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { function markRef(current$$1, workInProgress) { var ref = workInProgress.ref; + if ( (current$$1 === null && ref !== null) || (current$$1 !== null && current$$1.ref !== ref) @@ -13239,6 +13420,7 @@ function updateFunctionComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -13251,14 +13433,16 @@ function updateFunctionComponent( } } - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -13270,6 +13454,7 @@ function updateFunctionComponent( context, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13287,6 +13472,7 @@ function updateFunctionComponent( ); } } + setCurrentPhase(null); } @@ -13297,9 +13483,8 @@ function updateFunctionComponent( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -13322,6 +13507,7 @@ function updateClassComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -13332,22 +13518,23 @@ function updateClassComponent( ); } } - } - - // Push context providers early to prevent context stack mismatches. + } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); var instance = workInProgress.stateNode; - var shouldUpdate = void 0; + var shouldUpdate; + if (instance === null) { if (current$$1 !== null) { // An class component without an instance only mounts if it suspended @@ -13355,11 +13542,11 @@ function updateClassComponent( // tree it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current$$1.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; - } - // In the initial pass we might need to construct the instance. + } // In the initial pass we might need to construct the instance. + constructClassInstance( workInProgress, Component, @@ -13390,6 +13577,7 @@ function updateClassComponent( renderExpirationTime ); } + var nextUnitOfWork = finishClassComponent( current$$1, workInProgress, @@ -13398,8 +13586,10 @@ function updateClassComponent( hasContext, renderExpirationTime ); + { var inst = workInProgress.stateNode; + if (inst.props !== nextProps) { !didWarnAboutReassigningProps ? warning$1( @@ -13412,6 +13602,7 @@ function updateClassComponent( didWarnAboutReassigningProps = true; } } + return nextUnitOfWork; } @@ -13425,7 +13616,6 @@ function finishClassComponent( ) { // Refs should update even if shouldComponentUpdate returns false markRef(current$$1, workInProgress); - var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect; if (!shouldUpdate && !didCaptureError) { @@ -13441,11 +13631,11 @@ function finishClassComponent( ); } - var instance = workInProgress.stateNode; + var instance = workInProgress.stateNode; // Rerender - // Rerender ReactCurrentOwner$3.current = workInProgress; - var nextChildren = void 0; + var nextChildren; + if ( didCaptureError && typeof Component.getDerivedStateFromError !== "function" @@ -13464,6 +13654,7 @@ function finishClassComponent( { setCurrentPhase("render"); nextChildren = instance.render(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13471,12 +13662,13 @@ function finishClassComponent( ) { instance.render(); } + setCurrentPhase(null); } - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; + if (current$$1 !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children @@ -13495,13 +13687,11 @@ function finishClassComponent( nextChildren, renderExpirationTime ); - } - - // Memoize state using the values we just used to render. + } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. - workInProgress.memoizedState = instance.state; - // The context might have changed so we need to recalculate it. + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } @@ -13511,6 +13701,7 @@ function finishClassComponent( function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; + if (root.pendingContext) { pushTopLevelContextObject( workInProgress, @@ -13521,21 +13712,20 @@ function pushHostRootContext(workInProgress) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } + pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - (function() { - if (!(updateQueue !== null)) { - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(updateQueue !== null)) { + 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." + ); + } + var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState !== null ? prevState.element : null; @@ -13546,10 +13736,11 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { null, renderExpirationTime ); - var nextState = workInProgress.memoizedState; - // Caution: React DevTools currently depends on this property + var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property // being called "element". + var nextChildren = nextState.element; + if (nextChildren === prevChildren) { // If the state is the same as before, that's a bailout because we had // no work that expires at this time. @@ -13560,32 +13751,33 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + var root = workInProgress.stateNode; - if ( - (current$$1 === null || current$$1.child === null) && - root.hydrate && - enterHydrationState(workInProgress) - ) { + + if (root.hydrate && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. - - // This is a bit of a hack. We track the host root as a placement to - // know that we're currently in a mounting state. That way isMounted - // works as expected. We must reset this before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag |= Placement; - - // Ensure that children mount into this root without tracking - // side-effects. This ensures that we don't store Placement effects on - // nodes that will be hydrated. - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + workInProgress.child = child; + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag = (node.effectTag & ~Placement) | Hydrating; + node = node.sibling; + } } else { // Otherwise reset hydration state in case we aborted and resumed another // root. @@ -13597,6 +13789,7 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { ); resetHydrationState(); } + return workInProgress.child; } @@ -13610,7 +13803,6 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current$$1 !== null ? current$$1.memoizedProps : null; - var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); @@ -13626,9 +13818,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { workInProgress.effectTag |= ContentReset; } - markRef(current$$1, workInProgress); + markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden. - // Check the host config to see if the children are offscreen/hidden. if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -13636,8 +13827,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } @@ -13654,9 +13845,9 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { function updateHostText(current$$1, workInProgress) { if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); - } - // Nothing to do here. This is terminal. We'll do the completion step + } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. + return null; } @@ -13673,22 +13864,23 @@ function mountLazyComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } - var props = workInProgress.pendingProps; - // We can't start a User Timing measurement with correct label yet. + var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet. // Cancel and resume right after we know the tag. + cancelWorkTimer(workInProgress); - var Component = readLazyComponentType(elementType); - // Store the unwrapped component in the type. + var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type. + workInProgress.type = Component; var resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); startWorkTimer(workInProgress); var resolvedProps = resolveDefaultProps(Component, props); - var child = void 0; + var child; + switch (resolvedTag) { case FunctionComponent: { { @@ -13697,6 +13889,7 @@ function mountLazyComponent( Component ); } + child = updateFunctionComponent( null, workInProgress, @@ -13706,12 +13899,14 @@ function mountLazyComponent( ); break; } + case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading( Component ); } + child = updateClassComponent( null, workInProgress, @@ -13721,12 +13916,14 @@ function mountLazyComponent( ); break; } + case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading( Component ); } + child = updateForwardRef( null, workInProgress, @@ -13736,10 +13933,12 @@ function mountLazyComponent( ); break; } + case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13751,6 +13950,7 @@ function mountLazyComponent( } } } + child = updateMemoComponent( null, workInProgress, @@ -13761,8 +13961,10 @@ function mountLazyComponent( ); break; } + default: { var hint = ""; + { if ( Component !== null && @@ -13771,24 +13973,21 @@ function mountLazyComponent( ) { hint = " Did you wrap a component in React.lazy() more than once?"; } - } - // This message intentionally doesn't mention ForwardRef or MemoComponent + } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - (function() { - { - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." + - hint - ) - ); - } - })(); + + { + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } } } + return child; } @@ -13805,28 +14004,26 @@ function mountIncompleteClassComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect - workInProgress.effectTag |= Placement; - } + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - // Promote the fiber to a class and try rendering again. - workInProgress.tag = ClassComponent; - - // The rest of this function is a fork of `updateClassComponent` + workInProgress.effectTag |= Placement; + } // Promote the fiber to a class and try rendering again. + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); constructClassInstance( workInProgress, Component, @@ -13839,7 +14036,6 @@ function mountIncompleteClassComponent( nextProps, renderExpirationTime ); - return finishClassComponent( null, workInProgress, @@ -13862,20 +14058,21 @@ function mountIndeterminateComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderExpirationTime); - var value = void 0; + var value; { if ( @@ -13909,8 +14106,8 @@ function mountIndeterminateComponent( context, renderExpirationTime ); - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; if ( @@ -13921,6 +14118,7 @@ function mountIndeterminateComponent( ) { { var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { warningWithoutStack$1( false, @@ -13935,18 +14133,16 @@ function mountIndeterminateComponent( ); didWarnAboutModulePatternComponent[_componentName] = true; } - } - - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; + } // Proceed under the assumption that this is a class instance - // Throw out any hooks that were used. - resetHooks(); + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - // Push context providers early to prevent context stack mismatches. + resetHooks(); // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. + var hasContext = false; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); @@ -13956,8 +14152,8 @@ function mountIndeterminateComponent( workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - var getDerivedStateFromProps = Component.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -13980,6 +14176,7 @@ function mountIndeterminateComponent( } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { if (disableLegacyContext && Component.contextTypes) { warningWithoutStack$1( @@ -14008,10 +14205,13 @@ function mountIndeterminateComponent( } } } + reconcileChildren(null, workInProgress, value, renderExpirationTime); + { validateFunctionComponentInDev(workInProgress, Component); } + return workInProgress.child; } } @@ -14026,18 +14226,22 @@ function validateFunctionComponentInDev(workInProgress, Component) { ) : void 0; } + if (workInProgress.ref !== null) { var info = ""; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } var warningKey = ownerName || workInProgress._debugID || ""; var debugSource = workInProgress._debugSource; + if (debugSource) { warningKey = debugSource.fileName + ":" + debugSource.lineNumber; } + if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; warning$1( @@ -14097,8 +14301,10 @@ function validateFunctionComponentInDev(workInProgress, Component) { } } -// TODO: This is now an empty object. Should we just make it a boolean? -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { + dehydrated: null, + retryTime: NoWork +}; function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) { // If the context is telling us that we should show a fallback, and we're not @@ -14115,9 +14321,8 @@ function updateSuspenseComponent( renderExpirationTime ) { var mode = workInProgress.mode; - var nextProps = workInProgress.pendingProps; + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.effectTag |= DidCapture; @@ -14125,17 +14330,15 @@ function updateSuspenseComponent( } var suspenseContext = suspenseStackCursor.current; - - var nextState = null; var nextDidTimeout = false; + var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect; if ( - (workInProgress.effectTag & DidCapture) !== NoEffect || + didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) ) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. - nextState = SUSPENDED_MARKER; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } else { @@ -14159,7 +14362,6 @@ function updateSuspenseComponent( } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); { @@ -14173,9 +14375,7 @@ function updateSuspenseComponent( ); } } - } - - // This next part is a bit confusing. If the children timeout, we switch to + } // This next part is a bit confusing. If the children timeout, we switch to // showing the fallback children in place of the "primary" children. // However, we don't want to delete the primary children because then their // state will be lost (both the React state and the host state, e.g. @@ -14197,35 +14397,30 @@ function updateSuspenseComponent( // custom reconciliation logic to preserve the state of the primary // children. It's essentially a very basic form of re-parenting. - // `child` points to the child fiber. In the normal case, this is the first - // fiber of the primary children set. In the timed-out case, it's a - // a fragment fiber containing the primary children. - var child = void 0; - // `next` points to the next fiber React should render. In the normal case, - // it's the same as `child`: the first fiber of the primary children set. - // In the timed-out case, it's a fragment fiber containing the *fallback* - // children -- we skip over the primary children entirely. - var next = void 0; if (current$$1 === null) { - if (enableSuspenseServerRenderer) { - // If we're currently hydrating, try to hydrate this boundary. - // But only if this has a fallback. - if (nextProps.fallback !== undefined) { - tryToClaimNextHydratableInstance(workInProgress); - // This could've changed the tag if this was a dehydrated suspense component. - if (workInProgress.tag === DehydratedSuspenseComponent) { - popSuspenseContext(workInProgress); - return updateDehydratedSuspenseComponent( - null, - workInProgress, - renderExpirationTime - ); + // If we're currently hydrating, try to hydrate this boundary. + // But only if this has a fallback. + if (nextProps.fallback !== undefined) { + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. + + if (enableSuspenseServerRenderer) { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent( + workInProgress, + dehydrated, + renderExpirationTime + ); + } } } - } - - // This is the initial mount. This branch is pretty simple because there's + } // This is the initial mount. This branch is pretty simple because there's // no previous state that needs to be preserved. + if (nextDidTimeout) { // Mount separate fragments for primary and fallback children. var nextFallbackChildren = nextProps.fallback; @@ -14239,6 +14434,7 @@ function updateSuspenseComponent( if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var progressedState = workInProgress.memoizedState; var progressedPrimaryChild = progressedState !== null @@ -14246,6 +14442,7 @@ function updateSuspenseComponent( : workInProgress.child; primaryChildFragment.child = progressedPrimaryChild; var progressedChild = progressedPrimaryChild; + while (progressedChild !== null) { progressedChild.return = primaryChildFragment; progressedChild = progressedChild.sibling; @@ -14259,85 +14456,192 @@ function updateSuspenseComponent( null ); fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - child = primaryChildFragment; - // Skip the primary children, and continue working on the + primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the // fallback children. - next = fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; } else { // Mount the primary children without an intermediate fragment fiber. var nextPrimaryChildren = nextProps.children; - child = next = mountChildFibers( + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( workInProgress, null, nextPrimaryChildren, renderExpirationTime - ); + )); } } else { // This is an update. This branch is more complicated because we need to // ensure the state of the primary children is preserved. var prevState = current$$1.memoizedState; - var prevDidTimeout = prevState !== null; - if (prevDidTimeout) { - // The current tree already timed out. That means each child set is + + if (prevState !== null) { + if (enableSuspenseServerRenderer) { + var _dehydrated = prevState.dehydrated; + + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent( + current$$1, + workInProgress, + _dehydrated, + prevState, + renderExpirationTime + ); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. + + workInProgress.effectTag |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. Wrap the children + // in a fragment fiber to keep them separate from the fallback + // children. + var _nextFallbackChildren = nextProps.fallback; + + var _primaryChildFragment = createFiberFromFragment( + // It shouldn't matter what the pending props are because we aren't + // going to render this fragment. + null, + mode, + NoWork, + null + ); + + _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child + // that we're not going to hydrate. + + _primaryChildFragment.child = null; + + if ((workInProgress.mode & BatchedMode) === NoMode) { + // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. + var _progressedChild = (_primaryChildFragment.child = + workInProgress.child); + + while (_progressedChild !== null) { + _progressedChild.return = _primaryChildFragment; + _progressedChild = _progressedChild.sibling; + } + } else { + // We will have dropped the effect list which contains the deletion. + // We need to reconcile to delete the current child. + reconcileChildFibers( + workInProgress, + current$$1.child, + null, + renderExpirationTime + ); + } // Because primaryChildFragment is a new fiber that we're inserting as the + // parent of a new tree, we need to set its treeBaseDuration. + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // treeBaseDuration is the sum of all the child tree base durations. + var treeBaseDuration = 0; + var hiddenChild = _primaryChildFragment.child; + + while (hiddenChild !== null) { + treeBaseDuration += hiddenChild.treeBaseDuration; + hiddenChild = hiddenChild.sibling; + } + + _primaryChildFragment.treeBaseDuration = treeBaseDuration; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment = createFiberFromFragment( + _nextFallbackChildren, + mode, + renderExpirationTime, + null + ); + + _fallbackChildFragment.return = workInProgress; + _primaryChildFragment.sibling = _fallbackChildFragment; + _fallbackChildFragment.effectTag |= Placement; + _primaryChildFragment.childExpirationTime = NoWork; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the + // fallback children. + + return _fallbackChildFragment; + } + } + } // The current tree already timed out. That means each child set is + // wrapped in a fragment fiber. + var currentPrimaryChildFragment = current$$1.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + if (nextDidTimeout) { // Still timed out. Reuse the current primary children by cloning // its fragment. We're going to skip over these entirely. - var _nextFallbackChildren = nextProps.fallback; - var _primaryChildFragment = createWorkInProgress( + var _nextFallbackChildren2 = nextProps.fallback; + + var _primaryChildFragment2 = createWorkInProgress( currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork ); - _primaryChildFragment.return = workInProgress; + + _primaryChildFragment2.return = workInProgress; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState = workInProgress.memoizedState; + var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child; + if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) { - _primaryChildFragment.child = _progressedPrimaryChild; - var _progressedChild = _progressedPrimaryChild; - while (_progressedChild !== null) { - _progressedChild.return = _primaryChildFragment; - _progressedChild = _progressedChild.sibling; + _primaryChildFragment2.child = _progressedPrimaryChild; + var _progressedChild2 = _progressedPrimaryChild; + + while (_progressedChild2 !== null) { + _progressedChild2.return = _primaryChildFragment2; + _progressedChild2 = _progressedChild2.sibling; } } - } - - // Because primaryChildFragment is a new fiber that we're inserting as the + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var treeBaseDuration = 0; - var hiddenChild = _primaryChildFragment.child; - while (hiddenChild !== null) { - treeBaseDuration += hiddenChild.treeBaseDuration; - hiddenChild = hiddenChild.sibling; + var _treeBaseDuration = 0; + var _hiddenChild = _primaryChildFragment2.child; + + while (_hiddenChild !== null) { + _treeBaseDuration += _hiddenChild.treeBaseDuration; + _hiddenChild = _hiddenChild.sibling; } - _primaryChildFragment.treeBaseDuration = treeBaseDuration; - } - // Clone the fallback child fragment, too. These we'll continue + _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; + } // Clone the fallback child fragment, too. These we'll continue // working on. - var _fallbackChildFragment = createWorkInProgress( + + var _fallbackChildFragment2 = createWorkInProgress( currentFallbackChildFragment, - _nextFallbackChildren, + _nextFallbackChildren2, currentFallbackChildFragment.expirationTime ); - _fallbackChildFragment.return = workInProgress; - _primaryChildFragment.sibling = _fallbackChildFragment; - child = _primaryChildFragment; - _primaryChildFragment.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment2.return = workInProgress; + _primaryChildFragment2.sibling = _fallbackChildFragment2; + _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment2; + return _fallbackChildFragment2; } else { // No longer suspended. Switch back to showing the primary children, // and remove the intermediate fragment fiber. @@ -14348,26 +14652,27 @@ function updateSuspenseComponent( currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime - ); - - // If this render doesn't suspend, we need to delete the fallback + ); // If this render doesn't suspend, we need to delete the fallback // children. Wait until the complete phase, after we've confirmed the // fallback is no longer needed. // TODO: Would it be better to store the fallback fragment on // the stateNode? - // Continue rendering the children, like we normally do. - child = next = primaryChild; + + workInProgress.memoizedState = null; + return (workInProgress.child = primaryChild); } } else { // The current tree has not already timed out. That means the primary // children are not wrapped in a fragment fiber. var _currentPrimaryChild = current$$1.child; + if (nextDidTimeout) { // Timed out. Wrap the children in a fragment fiber to keep them // separate from the fallback children. - var _nextFallbackChildren2 = nextProps.fallback; - var _primaryChildFragment2 = createFiberFromFragment( + var _nextFallbackChildren3 = nextProps.fallback; + + var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't // going to render this fragment. null, @@ -14375,78 +14680,80 @@ function updateSuspenseComponent( NoWork, null ); - _primaryChildFragment2.return = workInProgress; - _primaryChildFragment2.child = _currentPrimaryChild; - if (_currentPrimaryChild !== null) { - _currentPrimaryChild.return = _primaryChildFragment2; - } - // Even though we're creating a new fiber, there are no new children, + _primaryChildFragment3.return = workInProgress; + _primaryChildFragment3.child = _currentPrimaryChild; + + if (_currentPrimaryChild !== null) { + _currentPrimaryChild.return = _primaryChildFragment3; + } // Even though we're creating a new fiber, there are no new children, // because we're reusing an already mounted tree. So we don't need to // schedule a placement. // primaryChildFragment.effectTag |= Placement; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState2 = workInProgress.memoizedState; + var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child; - _primaryChildFragment2.child = _progressedPrimaryChild2; - var _progressedChild2 = _progressedPrimaryChild2; - while (_progressedChild2 !== null) { - _progressedChild2.return = _primaryChildFragment2; - _progressedChild2 = _progressedChild2.sibling; - } - } - // Because primaryChildFragment is a new fiber that we're inserting as the + _primaryChildFragment3.child = _progressedPrimaryChild2; + var _progressedChild3 = _progressedPrimaryChild2; + + while (_progressedChild3 !== null) { + _progressedChild3.return = _primaryChildFragment3; + _progressedChild3 = _progressedChild3.sibling; + } + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var _treeBaseDuration = 0; - var _hiddenChild = _primaryChildFragment2.child; - while (_hiddenChild !== null) { - _treeBaseDuration += _hiddenChild.treeBaseDuration; - _hiddenChild = _hiddenChild.sibling; + var _treeBaseDuration2 = 0; + var _hiddenChild2 = _primaryChildFragment3.child; + + while (_hiddenChild2 !== null) { + _treeBaseDuration2 += _hiddenChild2.treeBaseDuration; + _hiddenChild2 = _hiddenChild2.sibling; } - _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; - } - // Create a fragment from the fallback children, too. - var _fallbackChildFragment2 = createFiberFromFragment( - _nextFallbackChildren2, + _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment3 = createFiberFromFragment( + _nextFallbackChildren3, mode, renderExpirationTime, null ); - _fallbackChildFragment2.return = workInProgress; - _primaryChildFragment2.sibling = _fallbackChildFragment2; - _fallbackChildFragment2.effectTag |= Placement; - child = _primaryChildFragment2; - _primaryChildFragment2.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment3.return = workInProgress; + _primaryChildFragment3.sibling = _fallbackChildFragment3; + _fallbackChildFragment3.effectTag |= Placement; + _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment2; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment3; + return _fallbackChildFragment3; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. + workInProgress.memoizedState = null; var _nextPrimaryChildren2 = nextProps.children; - next = child = reconcileChildFibers( + return (workInProgress.child = reconcileChildFibers( workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime - ); + )); } } - workInProgress.stateNode = current$$1.stateNode; } - - workInProgress.memoizedState = nextState; - workInProgress.child = child; - return next; } function retrySuspenseComponentWithoutHydrating( @@ -14454,111 +14761,136 @@ function retrySuspenseComponentWithoutHydrating( workInProgress, renderExpirationTime ) { - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; + // We're now not suspended nor dehydrated. + workInProgress.memoizedState = null; // Retry with the full children. - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - (function() { - if (!(returnFiber !== null)) { - throw ReactError( - Error( - "Suspense boundaries are never on the root. This is probably a bug in React." - ) + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and + // that the old child gets a Deletion effect. + // We could also call forceUnmountCurrentAndReconcile. + + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} + +function mountDehydratedSuspenseComponent( + workInProgress, + suspenseInstance, + renderExpirationTime +) { + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & BatchedMode) === NoMode) { + { + warning$1( + false, + "Cannot hydrate Suspense in legacy mode. Switch from " + + "ReactDOM.hydrate(element, container) to " + + "ReactDOM.unstable_createSyncRoot(container, { hydrate: true })" + + ".render(element) or remove the Suspense components from " + + "the server rendered components." ); } - })(); - var last = returnFiber.lastEffect; - if (last !== null) { - last.nextEffect = current$$1; - returnFiber.lastEffect = current$$1; + + workInProgress.expirationTime = Sync; + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content. + + var newExpirationTime = computeAsyncExpiration(serverDisplayTime); + + if (enableSchedulerTracing) { + markSpawnedWork(newExpirationTime); + } + + workInProgress.expirationTime = newExpirationTime; } else { - returnFiber.firstEffect = returnFiber.lastEffect = current$$1; - } - current$$1.nextEffect = null; - current$$1.effectTag = Deletion; + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.expirationTime = Never; - popSuspenseContext(workInProgress); + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + } - // Upgrade this work in progress to a real Suspense component. - workInProgress.tag = SuspenseComponent; - workInProgress.stateNode = null; - workInProgress.memoizedState = null; - // This is now an insertion. - workInProgress.effectTag |= Placement; - // Retry as a real Suspense component. - return updateSuspenseComponent(null, workInProgress, renderExpirationTime); + return null; } function updateDehydratedSuspenseComponent( current$$1, workInProgress, + suspenseInstance, + suspenseState, renderExpirationTime ) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - var suspenseInstance = workInProgress.stateNode; - if (current$$1 === null) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - var serverDisplayTime = requestCurrentTime(); - // Schedule a normal pri update to render this content. - workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.expirationTime = Never; - } - return null; - } - - if ((workInProgress.effectTag & DidCapture) !== NoEffect) { - // Something suspended. Leave the existing children in place. - // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far? - workInProgress.child = null; - return null; - } - // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This boundary is in a permanent fallback state. In this case, we'll never - // get an update and we'll never be able to hydrate the final content. Let's just try the - // client side render instead. + if ((workInProgress.mode & BatchedMode) === NoMode) { return retrySuspenseComponentWithoutHydrating( current$$1, workInProgress, renderExpirationTime ); } - // We use childExpirationTime to indicate that a child might depend on context, so if + + if (isSuspenseInstanceFallback(suspenseInstance)) { + // This boundary is in a permanent fallback state. In this case, we'll never + // get an update and we'll never be able to hydrate the final content. Let's just try the + // client side render instead. + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime + ); + } // We use childExpirationTime to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. + var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime; + if (didReceiveUpdate || hasContextChanged$$1) { // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using an earlier expiration time but - // during this render we can't. Instead, we're going to delete the whole subtree and - // instead inject a new real Suspense boundary to take its place, which may render content - // or fallback. The real Suspense boundary will suspend for a while so we have some time - // to ensure it can produce real content, but all state and pending events will be lost. + // hydrate it. We might still be able to hydrate it using an earlier expiration time, if + // we are rendering at lower expiration than sync. + if (renderExpirationTime < Sync) { + if (suspenseState.retryTime <= renderExpirationTime) { + // This render is even higher pri than we've seen before, let's try again + // at even higher pri. + var attemptHydrationAtExpirationTime = renderExpirationTime + 1; + suspenseState.retryTime = attemptHydrationAtExpirationTime; + scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render. + } else { + // We have already tried to ping at a higher priority than we're rendering with + // so if we got here, we must have failed to hydrate at those levels. We must + // now give up. Instead, we're going to delete the whole subtree and instead inject + // a new real Suspense boundary to take its place, which may render content + // or fallback. This might suspend for a while and if it does we might still have + // an opportunity to hydrate before this pass commits. + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. + + renderDidSuspendDelayIfPossible(); return retrySuspenseComponentWithoutHydrating( current$$1, workInProgress, @@ -14574,30 +14906,61 @@ function updateDehydratedSuspenseComponent( // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). - workInProgress.effectTag |= DidCapture; - // Leave the children in place. I.e. empty. - workInProgress.child = null; - // Register a callback to retry this boundary once the server has sent the result. + workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. + + workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result. + registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryDehydratedSuspenseBoundary.bind(null, current$$1) ); return null; } else { // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress); + reenterHydrationStateFromDehydratedSuspenseInstance( + workInProgress, + suspenseInstance + ); var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag |= Hydrating; + node = node.sibling; + } + + workInProgress.child = child; return workInProgress.child; } } +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + if (fiber.expirationTime < renderExpirationTime) { + fiber.expirationTime = renderExpirationTime; + } + + var alternate = fiber.alternate; + + if (alternate !== null && alternate.expirationTime < renderExpirationTime) { + alternate.expirationTime = renderExpirationTime; + } + + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); +} + function propagateSuspenseContextChange( workInProgress, firstChild, @@ -14607,36 +14970,39 @@ function propagateSuspenseContextChange( // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - if (node.expirationTime < renderExpirationTime) { - node.expirationTime = renderExpirationTime; - } - var alternate = node.alternate; - if ( - alternate !== null && - alternate.expirationTime < renderExpirationTime - ) { - alternate.expirationTime = renderExpirationTime; - } - scheduleWorkOnParentPath(node.return, renderExpirationTime); - } + scheduleWorkOnFiber(node, renderExpirationTime); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleWorkOnFiber(node, renderExpirationTime); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -14652,14 +15018,17 @@ function findLastContentRow(firstChild) { // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } + row = row.sibling; } + return lastContentRow; } @@ -14673,6 +15042,7 @@ function validateRevealOrder(revealOrder) { !didWarnAboutRevealOrder[revealOrder] ) { didWarnAboutRevealOrder[revealOrder] = true; + if (typeof revealOrder === "string") { switch (revealOrder.toLowerCase()) { case "together": @@ -14687,6 +15057,7 @@ function validateRevealOrder(revealOrder) { ); break; } + case "forward": case "backward": { warning$1( @@ -14698,6 +15069,7 @@ function validateRevealOrder(revealOrder) { ); break; } + default: warning$1( false, @@ -14748,6 +15120,7 @@ function validateSuspenseListNestedChild(childSlot, index) { { var isArray = Array.isArray(childSlot); var isIterable = !isArray && typeof getIteratorFn(childSlot) === "function"; + if (isArray || isIterable) { var type = isArray ? "array" : "iterable"; warning$1( @@ -14764,6 +15137,7 @@ function validateSuspenseListNestedChild(childSlot, index) { return false; } } + return true; } @@ -14783,15 +15157,19 @@ function validateSuspenseListChildren(children, revealOrder) { } } else { var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { var childrenIterator = iteratorFn.call(children); + if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; + for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } + _i++; } } @@ -14814,9 +15192,11 @@ function initSuspenseListRenderState( isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; + if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, @@ -14824,7 +15204,8 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }; } else { // We can reuse the existing object from previous renders. @@ -14834,16 +15215,16 @@ function initSuspenseListRenderState( renderState.tail = tail; renderState.tailExpiration = 0; renderState.tailMode = tailMode; + renderState.lastEffect = lastEffectBeforeRendering; } -} - -// This can end up rendering this component multiple passes. +} // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. + function updateSuspenseListComponent( current$$1, workInProgress, @@ -14853,24 +15234,21 @@ function updateSuspenseListComponent( var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; - validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren( current$$1, workInProgress, newChildren, renderExpirationTime ); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext( suspenseContext, ForceSuspenseFallback ); + if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -14880,6 +15258,7 @@ function updateSuspenseListComponent( } else { var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect; + if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render @@ -14890,8 +15269,10 @@ function updateSuspenseListComponent( renderExpirationTime ); } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } + pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & BatchedMode) === NoMode) { @@ -14902,7 +15283,8 @@ function updateSuspenseListComponent( switch (revealOrder) { case "forwards": { var lastContentRow = findLastContentRow(workInProgress.child); - var tail = void 0; + var tail; + if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. @@ -14914,15 +15296,18 @@ function updateSuspenseListComponent( tail = lastContentRow.sibling; lastContentRow.sibling = null; } + initSuspenseListRenderState( workInProgress, false, // isBackwards tail, lastContentRow, - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "backwards": { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything @@ -14931,39 +15316,45 @@ function updateSuspenseListComponent( var _tail = null; var row = workInProgress.child; workInProgress.child = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } + var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; - } - // TODO: If workInProgress.child is null, we can continue on the tail immediately. + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. + initSuspenseListRenderState( workInProgress, true, // isBackwards _tail, null, // last - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "together": { initSuspenseListRenderState( workInProgress, false, // isBackwards null, // tail null, // last - undefined + undefined, + workInProgress.lastEffect ); break; } + default: { // The default reveal order is the same as not having // a boundary. @@ -14971,6 +15362,7 @@ function updateSuspenseListComponent( } } } + return workInProgress.child; } @@ -14981,6 +15373,7 @@ function updatePortalComponent( ) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; + if (current$$1 === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal @@ -15001,6 +15394,7 @@ function updatePortalComponent( renderExpirationTime ); } + return workInProgress.child; } @@ -15011,10 +15405,8 @@ function updateContextProvider( ) { var providerType = workInProgress.type; var context = providerType._context; - var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; { @@ -15036,6 +15428,7 @@ function updateContextProvider( if (oldProps !== null) { var oldValue = oldProps.value; var changedBits = calculateChangedBits(context, newValue, oldValue); + if (changedBits === 0) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { @@ -15074,14 +15467,14 @@ function updateContextConsumer( workInProgress, renderExpirationTime ) { - var context = workInProgress.type; - // The logic below for Context differs depending on PROD or DEV mode. In + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. + { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). @@ -15101,6 +15494,7 @@ function updateContextConsumer( context = context._context; } } + var newProps = workInProgress.pendingProps; var render = newProps.children; @@ -15118,15 +15512,15 @@ function updateContextConsumer( prepareToReadContext(workInProgress, renderExpirationTime); var newValue = readContext(context, newProps.unstable_observedBits); - var newChildren = void 0; + var newChildren; + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); newChildren = render(newValue); setCurrentPhase(null); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -15143,12 +15537,29 @@ function updateFundamentalComponent$1( renderExpirationTime ) { var fundamentalImpl = workInProgress.type.impl; + if (fundamentalImpl.reconcileChildren === false) { return null; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} +function updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; reconcileChildren( current$$1, workInProgress, @@ -15179,8 +15590,14 @@ function bailoutOnAlreadyFinishedWork( stopProfilerTimerIfRunning(workInProgress); } - // Check if the children have any pending work. + var updateExpirationTime = workInProgress.expirationTime; + + if (updateExpirationTime !== NoWork) { + markUnprocessedUpdateTime(updateExpirationTime); + } // Check if the children have any pending work. + var childExpirationTime = workInProgress.childExpirationTime; + if (childExpirationTime < renderExpirationTime) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are @@ -15197,53 +15614,54 @@ function bailoutOnAlreadyFinishedWork( function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { throw new Error("Cannot swap the root fiber."); - } - - // Disconnect from the old current. + } // Disconnect from the old current. // It will get deleted. + current$$1.alternate = null; - oldWorkInProgress.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; + if (prevSibling === null) { throw new Error("Expected parent to have a child."); } + while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; + if (prevSibling === null) { throw new Error("Expected to find the previous sibling."); } } - prevSibling.sibling = newWorkInProgress; - } - // Delete the old fiber and place the new one. + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = current$$1; returnFiber.lastEffect = current$$1; } else { returnFiber.firstEffect = returnFiber.lastEffect = current$$1; } + current$$1.nextEffect = null; current$$1.effectTag = Deletion; + newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber. - newWorkInProgress.effectTag |= Placement; - - // Restart work from the new fiber. return newWorkInProgress; } } @@ -15275,25 +15693,26 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { if ( oldProps !== newProps || - hasContextChanged() || - // Force a re-render if the implementation changed due to hot reload: + hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current$$1.type ) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else if (updateExpirationTime < renderExpirationTime) { - didReceiveUpdate = false; - // This fiber does not have any pending work. Bailout without entering + didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); resetHydrationState(); break; + case HostComponent: pushHostContext(workInProgress); + if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -15301,45 +15720,69 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } + break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { pushContextProvider(workInProgress); } + break; } + case HostPortal: pushHostContainer( workInProgress, workInProgress.stateNode.containerInfo ); break; + case ContextProvider: { var newValue = workInProgress.memoizedProps.value; pushProvider(workInProgress, newValue); break; } + case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + break; + case SuspenseComponent: { var state = workInProgress.memoizedState; - var didTimeout = state !== null; - if (didTimeout) { - // If this boundary is currently timed out, we need to decide + + if (state !== null) { + if (enableSuspenseServerRenderer) { + if (state.dehydrated !== null) { + pushSuspenseContext( + workInProgress, + setDefaultShallowSuspenseContext(suspenseStackCursor.current) + ); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. + + workInProgress.effectTag |= DidCapture; + break; + } + } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary + // child fragment. + var primaryChildFragment = workInProgress.child; var primaryChildExpirationTime = primaryChildFragment.childExpirationTime; + if ( primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime @@ -15355,14 +15798,15 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // The primary children do not have pending work with sufficient + ); // The primary children do not have pending work with sufficient // priority. Bailout. + var child = bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. @@ -15377,25 +15821,13 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { setDefaultShallowSuspenseContext(suspenseStackCursor.current) ); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // We know that this component will suspend again because if it has - // been unsuspended it has committed as a regular Suspense component. - // If it needs to be retried, it should have work scheduled on it. - workInProgress.effectTag |= DidCapture; - } - break; - } + case SuspenseListComponent: { var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect; - var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime; @@ -15411,23 +15843,24 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { workInProgress, renderExpirationTime ); - } - // If none of the children had any work, that means that none of + } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. - workInProgress.effectTag |= DidCapture; - } - // If nothing suspended before and we're rendering the same children, + workInProgress.effectTag |= DidCapture; + } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. + var renderState = workInProgress.memoizedState; + if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (hasChildWork) { @@ -15440,17 +15873,23 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + return bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; } } else { didReceiveUpdate = false; - } + } // Before entering the begin phase, clear the expiration time. - // Before entering the begin phase, clear the expiration time. workInProgress.expirationTime = NoWork; switch (workInProgress.tag) { @@ -15462,6 +15901,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent( @@ -15472,6 +15912,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FunctionComponent: { var _Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; @@ -15487,13 +15928,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case ClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; + var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps); + return updateClassComponent( current$$1, workInProgress, @@ -15502,35 +15946,43 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case HostRoot: return updateHostRoot(current$$1, workInProgress, renderExpirationTime); + case HostComponent: return updateHostComponent( current$$1, workInProgress, renderExpirationTime ); + case HostText: return updateHostText(current$$1, workInProgress); + case SuspenseComponent: return updateSuspenseComponent( current$$1, workInProgress, renderExpirationTime ); + case HostPortal: return updatePortalComponent( current$$1, workInProgress, renderExpirationTime ); + case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef( current$$1, workInProgress, @@ -15539,32 +15991,40 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case Fragment: return updateFragment(current$$1, workInProgress, renderExpirationTime); + case Mode: return updateMode(current$$1, workInProgress, renderExpirationTime); + case Profiler: return updateProfiler(current$$1, workInProgress, renderExpirationTime); + case ContextProvider: return updateContextProvider( current$$1, workInProgress, renderExpirationTime ); + case ContextConsumer: return updateContextConsumer( current$$1, workInProgress, renderExpirationTime ); + case MemoComponent: { var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; - // Resolve outer props first, then resolve inner props. + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -15576,6 +16036,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent( current$$1, @@ -15586,6 +16047,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case SimpleMemoComponent: { return updateSimpleMemoComponent( current$$1, @@ -15596,13 +16058,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case IncompleteClassComponent: { var _Component3 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; + var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4); + return mountIncompleteClassComponent( current$$1, workInProgress, @@ -15611,16 +16076,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - return updateDehydratedSuspenseComponent( - current$$1, - workInProgress, - renderExpirationTime - ); - } - break; - } + case SuspenseListComponent: { return updateSuspenseListComponent( current$$1, @@ -15628,6 +16084,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FundamentalComponent: { if (enableFundamentalAPI) { return updateFundamentalComponent$1( @@ -15636,18 +16093,30 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + break; } - } - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + return updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime + ); + } + + break; } - })(); + } + + { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); + } } function createFundamentalStateInstance(currentFiber, props, impl, state) { @@ -15661,35 +16130,240 @@ function createFundamentalStateInstance(currentFiber, props, impl, state) { }; } -var emptyObject$1 = {}; -var isArray$2 = Array.isArray; +function isFiberSuspenseAndTimedOut(fiber) { + return fiber.tag === SuspenseComponent && fiber.memoizedState !== null; +} -function markUpdate(workInProgress) { - // Tag the fiber with an update effect. This turns a Placement into - // a PlacementAndUpdate. - workInProgress.effectTag |= Update; +function getSuspenseFallbackChild(fiber) { + return fiber.child.sibling.child; } -function markRef$1(workInProgress) { - workInProgress.effectTag |= Ref; +function collectScopedNodes(node, fn, scopedNodes) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type, memoizedProps) === true) { + scopedNodes.push(getPublicInstance(node.stateNode)); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + } } -var appendAllChildren = void 0; -var updateHostContainer = void 0; -var updateHostComponent$1 = void 0; -var updateHostText$1 = void 0; -if (supportsMutation) { - // Mutation mode +function collectFirstScopedNode(node, fn) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type2 = node.type, + memoizedProps = node.memoizedProps; - appendAllChildren = function( - parent, - workInProgress, - needsVisibilityToggle, - isHidden + if (fn(_type2, memoizedProps) === true) { + return getPublicInstance(node.stateNode); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + } + + return null; +} + +function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) { + var child = startingChild; + + while (child !== null) { + collectScopedNodes(child, fn, scopedNodes); + child = child.sibling; + } +} + +function collectFirstScopedNodeFromChildren(startingChild, fn) { + var child = startingChild; + + while (child !== null) { + var scopedNode = collectFirstScopedNode(child, fn); + + if (scopedNode !== null) { + return scopedNode; + } + + child = child.sibling; + } + + return null; +} + +function collectNearestScopeMethods(node, scope, childrenScopes) { + if (isValidScopeNode(node, scope)) { + childrenScopes.push(node.stateNode.methods); + } else { + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + } +} + +function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) { + var child = startingChild; + + while (child !== null) { + collectNearestScopeMethods(child, scope, childrenScopes); + child = child.sibling; + } +} + +function isValidScopeNode(node, scope) { + return ( + node.tag === ScopeComponent && + node.type === scope && + node.stateNode !== null + ); +} + +function createScopeMethods(scope, instance) { + return { + getChildren: function() { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var childrenScopes = []; + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getChildrenFromRoot: function() { + var currentFiber = instance.fiber; + var node = currentFiber; + + while (node !== null) { + var parent = node.return; + + if (parent === null) { + break; + } + + node = parent; + + if (node.tag === ScopeComponent && node.type === scope) { + break; + } + } + + var childrenScopes = []; + collectNearestChildScopeMethods(node.child, scope, childrenScopes); + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getParent: function() { + var node = instance.fiber.return; + + while (node !== null) { + if (node.tag === ScopeComponent && node.type === scope) { + return node.stateNode.methods; + } + + node = node.return; + } + + return null; + }, + getProps: function() { + var currentFiber = instance.fiber; + return currentFiber.memoizedProps; + }, + queryAllNodes: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var scopedNodes = []; + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + + return scopedNodes.length === 0 ? null : scopedNodes; + }, + queryFirstNode: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + + return null; + }, + containsNode: function(node) { + var fiber = getInstanceFromNode$1(node); + + while (fiber !== null) { + if ( + fiber.tag === ScopeComponent && + fiber.type === scope && + fiber.stateNode === instance + ) { + return true; + } + + fiber = fiber.return; + } + + return false; + } + }; +} + +function markUpdate(workInProgress) { + // Tag the fiber with an update effect. This turns a Placement into + // a PlacementAndUpdate. + workInProgress.effectTag |= Update; +} + +function markRef$1(workInProgress) { + workInProgress.effectTag |= Ref; +} + +var appendAllChildren; +var updateHostContainer; +var updateHostComponent$1; +var updateHostText$1; + +if (supportsMutation) { + // Mutation mode + appendAllChildren = function( + parent, + workInProgress, + needsVisibilityToggle, + isHidden ) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); @@ -15704,15 +16378,19 @@ if (supportsMutation) { node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -15721,6 +16399,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15731,21 +16410,21 @@ if (supportsMutation) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; + if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; - } - - // If we get updated because one of our children updated, we don't + } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. + var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. + var updatePayload = prepareUpdate( instance, type, @@ -15753,15 +16432,16 @@ if (supportsMutation) { newProps, rootContainerInstance, currentHostContext - ); - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. + if (updatePayload) { markUpdate(workInProgress); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { @@ -15770,7 +16450,6 @@ if (supportsMutation) { }; } else if (supportsPersistence) { // Persistent host tree mode - appendAllChildren = function( parent, workInProgress, @@ -15780,33 +16459,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance = cloneHiddenTextInstance(_instance, text, node); } + appendInitialChild(parent, _instance); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance2 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props = node.memoizedProps; var _type = node.type; _instance2 = cloneHiddenInstance(_instance2, _type, _props, node); } + appendInitialChild(parent, _instance2); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15816,8 +16502,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15828,7 +16516,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15837,6 +16527,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15847,24 +16538,27 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - }; + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - // An unfortunate fork of appendAllChildren because we have two different parent types. var appendAllChildrenToContainer = function( containerChildSet, workInProgress, @@ -15874,33 +16568,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance3 = cloneHiddenTextInstance(_instance3, text, node); } + appendChildToContainerChildSet(containerChildSet, _instance3); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance4 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props2 = node.memoizedProps; var _type2 = node.type; _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node); } + appendChildToContainerChildSet(containerChildSet, _instance4); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15910,8 +16611,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15922,7 +16625,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15931,6 +16636,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15941,38 +16647,45 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } }; + updateHostContainer = function(workInProgress) { var portalOrRoot = workInProgress.stateNode; var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged) { // No changes, just reuse the existing instance. } else { var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. + markUpdate(workInProgress); finalizeContainerChildren(container, newChildSet); } }; + updateHostComponent$1 = function( current, workInProgress, @@ -15981,19 +16694,22 @@ if (supportsMutation) { rootContainerInstance ) { var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; - // If there are no effects associated with this node, then none of our children had any updates. + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. // This guarantees that we can reuse all of them. + var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged && oldProps === newProps) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var recyclableInstance = workInProgress.stateNode; var currentHostContext = getHostContext(); var updatePayload = null; + if (oldProps !== newProps) { updatePayload = prepareUpdate( recyclableInstance, @@ -16004,12 +16720,14 @@ if (supportsMutation) { currentHostContext ); } + if (childrenUnchanged && updatePayload === null) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var newInstance = cloneInstance( currentInstance, updatePayload, @@ -16020,6 +16738,7 @@ if (supportsMutation) { childrenUnchanged, recyclableInstance ); + if ( finalizeInitialChildren( newInstance, @@ -16031,7 +16750,9 @@ if (supportsMutation) { ) { markUpdate(workInProgress); } + workInProgress.stateNode = newInstance; + if (childrenUnchanged) { // If there are no other effects in this tree, we need to flag this node as having one. // Even though we're not going to use it for anything. @@ -16042,6 +16763,7 @@ if (supportsMutation) { appendAllChildren(newInstance, workInProgress, false, false); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { if (oldText !== newText) { // If the text content differs, we'll create a new text instance for it. @@ -16052,9 +16774,9 @@ if (supportsMutation) { rootContainerInstance, currentHostContext, workInProgress - ); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. + ); // We'll have to mark it as having an effect, even though we won't use the effect for anything. // This lets the parents know that at least one of their children has changed. + markUpdate(workInProgress); } }; @@ -16063,6 +16785,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -16072,6 +16795,7 @@ if (supportsMutation) { ) { // Noop }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // Noop }; @@ -16087,14 +16811,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var tailNode = renderState.tail; var lastTailNode = null; + while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } + tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; @@ -16103,8 +16829,10 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. lastTailNode.sibling = null; } + break; } + case "collapsed": { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries @@ -16113,14 +16841,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; + while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } + _tailNode = _tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { @@ -16135,6 +16865,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. _lastTailNode.sibling = null; } + break; } } @@ -16146,41 +16877,55 @@ function completeWork(current, workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case IndeterminateComponent: break; + case LazyComponent: break; + case SimpleMemoComponent: case FunctionComponent: break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + break; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var fiberRoot = workInProgress.stateNode; + if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } + if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. - popHydrationState(workInProgress); - // This resets the hacky state to fix isMounted before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag &= ~Placement; + var wasHydrated = popHydrationState(workInProgress); + + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } } + updateHostContainer(workInProgress); break; } + case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; + if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1( current, @@ -16193,14 +16938,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableFlareAPI) { var prevListeners = current.memoizedProps.listeners; var nextListeners = newProps.listeners; - var instance = workInProgress.stateNode; + if (prevListeners !== nextListeners) { - updateEventListeners( - nextListeners, - instance, - rootContainerInstance, - workInProgress - ); + markUpdate(workInProgress); } } @@ -16209,26 +16949,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. + break; } - var currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on we want to add then top->down or // bottom->up. Top->down is faster in IE11. - var wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { + + var _wasHydrated = popHydrationState(workInProgress); + + if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if ( @@ -16242,47 +16979,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { // commit-phase we mark this as such. markUpdate(workInProgress); } + if (enableFlareAPI) { - var _instance5 = workInProgress.stateNode; var listeners = newProps.listeners; + if (listeners != null) { updateEventListeners( listeners, - _instance5, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } } } else { - var _instance6 = createInstance( + var instance = createInstance( type, newProps, rootContainerInstance, currentHostContext, workInProgress ); + appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners - appendAllChildren(_instance6, workInProgress, false, false); + workInProgress.stateNode = instance; if (enableFlareAPI) { var _listeners = newProps.listeners; + if (_listeners != null) { updateEventListeners( _listeners, - _instance6, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } - } - - // Certain renderers require commit-time effects for initial mount. + } // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. + if ( finalizeInitialChildren( - _instance6, + instance, type, newProps, rootContainerInstance, @@ -16291,7 +17028,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { ) { markUpdate(workInProgress); } - workInProgress.stateNode = _instance6; } if (workInProgress.ref !== null) { @@ -16299,32 +17035,34 @@ function completeWork(current, workInProgress, renderExpirationTime) { markRef$1(workInProgress); } } + break; } + case HostText: { var newText = newProps; + if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. + updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress); - if (_wasHydrated) { + + var _wasHydrated2 = popHydrationState(workInProgress); + + if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } @@ -16337,38 +17075,86 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); } } + break; } + case ForwardRef: break; + case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; + + if (enableSuspenseServerRenderer) { + if (nextState !== null && nextState.dehydrated !== null) { + if (current === null) { + var _wasHydrated3 = popHydrationState(workInProgress); + + if (!_wasHydrated3) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + + prepareToHydrateHostSuspenseInstance(workInProgress); + + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + + return null; + } else { + // We should never have been in a hydration state if we didn't have a current. + // However, in some of those paths, we might have reentered a hydration state + // and then we might be inside a hydration state. In that case, we'll need to + // exit out of it. + resetHydrationState(); + + if ((workInProgress.effectTag & DidCapture) === NoEffect) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. + + workInProgress.effectTag |= Update; + return null; + } + } + } + if ((workInProgress.effectTag & DidCapture) !== NoEffect) { // Something suspended. Re-render with the fallback children. - workInProgress.expirationTime = renderExpirationTime; - // Do not reset the effect list. + workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list. + return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = false; + if (current === null) { - // In cases where we didn't find a suitable hydration boundary we never - // downgraded this to a DehydratedSuspenseComponent, but we still need to - // pop the hydration state since we might be inside the insertion tree. - popHydrationState(workInProgress); + if (workInProgress.memoizedProps.fallback !== undefined) { + popHydrationState(workInProgress); + } } else { var prevState = current.memoizedState; prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { // We just switched from the fallback to the normal children. // Delete the fallback. // TODO: Would it be better to store the fallback fragment on + // the stateNode during the begin phase? var currentFallbackChild = current.child.sibling; + if (currentFallbackChild !== null) { // Deletions go at the beginning of the return fiber's effect list var first = workInProgress.firstEffect; + if (first !== null) { workInProgress.firstEffect = currentFallbackChild; currentFallbackChild.nextEffect = first; @@ -16376,6 +17162,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; currentFallbackChild.nextEffect = null; } + currentFallbackChild.effectTag = Deletion; } } @@ -16398,6 +17185,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true; + if ( hasInvisibleChildContext || hasSuspenseContext( @@ -16425,6 +17213,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if (supportsMutation) { // TODO: Only schedule updates if these values are non equal, i.e. it changed. if (nextDidTimeout || prevDidTimeout) { @@ -16436,6 +17225,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if ( enableSuspenseCallback && workInProgress.updateQueue !== null && @@ -16444,76 +17234,49 @@ function completeWork(current, workInProgress, renderExpirationTime) { // Always notify the callback workInProgress.effectTag |= Update; } + break; } + case Fragment: break; + case Mode: break; + case Profiler: break; + case HostPortal: popHostContainer(workInProgress); updateHostContainer(workInProgress); break; + case ContextProvider: // Pop provider fiber popProvider(workInProgress); break; + case ContextConsumer: break; + case MemoComponent: break; + case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; + if (isContextProvider(_Component)) { popContext(workInProgress); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (current === null) { - var _wasHydrated2 = popHydrationState(workInProgress); - (function() { - if (!_wasHydrated2) { - throw ReactError( - Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ) - ); - } - })(); - if (enableSchedulerTracing) { - markSpawnedWork(Never); - } - skipPastDehydratedSuspenseInstance(workInProgress); - } else { - // We should never have been in a hydration state if we didn't have a current. - // However, in some of those paths, we might have reentered a hydration state - // and then we might be inside a hydration state. In that case, we'll need to - // exit out of it. - resetHydrationState(); - if ((workInProgress.effectTag & DidCapture) === NoEffect) { - // This boundary did not suspend so it's now hydrated. - // To handle any future suspense cases, we're going to now upgrade it - // to a Suspense component. We detach it from the existing current fiber. - current.alternate = null; - workInProgress.alternate = null; - workInProgress.tag = SuspenseComponent; - workInProgress.memoizedState = null; - workInProgress.stateNode = null; - } - } - } - break; - } + case SuspenseListComponent: { popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; if (renderState === null) { @@ -16524,18 +17287,16 @@ function completeWork(current, workInProgress, renderExpirationTime) { var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect; - var renderedTail = renderState.rendering; + if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. - // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to @@ -16543,16 +17304,17 @@ function completeWork(current, workInProgress, renderExpirationTime) { var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect); + if (!cannotBeSuspended) { var row = workInProgress.child; + while (row !== null) { var suspended = findFirstSuspended(row); + if (suspended !== null) { didSuspendAlready = true; workInProgress.effectTag |= DidCapture; - cutOffTailIfNeeded(renderState, false); - - // If this is a newly suspended tree, it might not get committed as + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thennables. Instead, we'll transfer its thennables to the // SuspenseList so that it can retry if they resolve. @@ -16564,21 +17326,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. + var newThennables = suspended.updateQueue; + if (newThennables !== null) { workInProgress.updateQueue = newThennables; workInProgress.effectTag |= Update; - } - - // Rerender the whole list, but this time, we'll force fallbacks + } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect list before doing the second pass since that's now invalid. - workInProgress.firstEffect = workInProgress.lastEffect = null; - // Reset the child fibers to their original state. - resetChildFibers(workInProgress, renderExpirationTime); - // Set up the Suspense Context to force suspense and immediately + if (renderState.lastEffect === null) { + workInProgress.firstEffect = null; + } + + workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state. + + resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately // rerender the children. + pushSuspenseContext( workInProgress, setShallowSuspenseContext( @@ -16588,42 +17354,46 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); return workInProgress.child; } + row = row.sibling; } } } else { cutOffTailIfNeeded(renderState, false); - } - // Next we're going to render the tail. + } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { workInProgress.effectTag |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, true); - // This might have been modified. + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. + + var _newThennables = _suspended.updateQueue; + + if (_newThennables !== null) { + workInProgress.updateQueue = _newThennables; + workInProgress.effectTag |= Update; + } + + cutOffTailIfNeeded(renderState, true); // This might have been modified. + if ( renderState.tail === null && renderState.tailMode === "hidden" ) { // We need to delete the row we just rendered. - // Ensure we transfer the update queue to the parent. - var _newThennables = _suspended.updateQueue; - if (_newThennables !== null) { - workInProgress.updateQueue = _newThennables; - workInProgress.effectTag |= Update; - } // Reset the effect list to what it w as before we rendered this // child. The nested children have already appended themselves. var lastEffect = (workInProgress.lastEffect = - renderState.lastEffect); - // Remove any effects that were appended after this point. + renderState.lastEffect); // Remove any effects that were appended after this point. + if (lastEffect !== null) { lastEffect.nextEffect = null; - } - // We're done. + } // We're done. + return null; } } else if ( @@ -16635,10 +17405,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { // The assumption is that this is usually faster. workInProgress.effectTag |= DidCapture; didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. If we can show // them, then they really have the same priority as this render. // So we'll pick it back up the very next render pass once we've had @@ -16646,11 +17413,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { var nextPriority = renderExpirationTime - 1; workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority; + if (enableSchedulerTracing) { markSpawnedWork(nextPriority); } } } + if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in @@ -16661,11 +17430,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; + if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } + renderState.last = renderedTail; } } @@ -16677,18 +17448,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { // until we just give up and show what we have so far. var TAIL_EXPIRATION_TIMEOUT_MS = 500; renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; - } - // Pop a row. + } // Pop a row. + var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.lastEffect = workInProgress.lastEffect; - next.sibling = null; - - // Restore the context. + next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -16697,12 +17468,15 @@ function completeWork(current, workInProgress, renderExpirationTime) { } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } - pushSuspenseContext(workInProgress, suspenseContext); - // Do a pass over the next row. + + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + return next; } + break; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalImpl = workInProgress.type.impl; @@ -16710,22 +17484,28 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (fundamentalInstance === null) { var getInitialState = fundamentalImpl.getInitialState; - var fundamentalState = void 0; + var fundamentalState; + if (getInitialState !== undefined) { fundamentalState = getInitialState(newProps); } + fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( workInProgress, newProps, fundamentalImpl, fundamentalState || {} ); - var _instance7 = getFundamentalComponentInstance(fundamentalInstance); - fundamentalInstance.instance = _instance7; + + var _instance5 = getFundamentalComponentInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance5; + if (fundamentalImpl.reconcileChildren === false) { return null; } - appendAllChildren(_instance7, workInProgress, false, false); + + appendAllChildren(_instance5, workInProgress, false, false); mountFundamentalComponent(fundamentalInstance); } else { // We fire update in commit phase @@ -16733,259 +17513,177 @@ function completeWork(current, workInProgress, renderExpirationTime) { fundamentalInstance.prevProps = prevProps; fundamentalInstance.props = newProps; fundamentalInstance.currentFiber = workInProgress; + if (supportsPersistence) { - var _instance8 = cloneFundamentalInstance(fundamentalInstance); - fundamentalInstance.instance = _instance8; - appendAllChildren(_instance8, workInProgress, false, false); + var _instance6 = cloneFundamentalInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance6; + appendAllChildren(_instance6, workInProgress, false, false); } + var shouldUpdate = shouldUpdateFundamentalComponent( fundamentalInstance ); + if (shouldUpdate) { markUpdate(workInProgress); } } } + break; } - default: - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - return null; -} + case ScopeComponent: { + if (enableScopeAPI) { + if (current === null) { + var _type3 = workInProgress.type; + var scopeInstance = { + fiber: workInProgress, + methods: null + }; + workInProgress.stateNode = scopeInstance; + scopeInstance.methods = createScopeMethods(_type3, scopeInstance); -function mountEventResponder$1( - responder, - responderProps, - instance, - rootContainerInstance, - fiber, - respondersMap -) { - var responderState = emptyObject$1; - var getInitialState = responder.getInitialState; - if (getInitialState !== null) { - responderState = getInitialState(responderProps); - } - var responderInstance = createResponderInstance( - responder, - responderProps, - responderState, - instance, - fiber - ); - mountResponderInstance( - responder, - responderInstance, - responderProps, - responderState, - instance, - rootContainerInstance - ); - respondersMap.set(responder, responderInstance); -} + if (enableFlareAPI) { + var _listeners2 = newProps.listeners; -function updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance -) { - var responder = void 0; - var props = void 0; + if (_listeners2 != null) { + var _rootContainerInstance2 = getRootHostContainer(); - if (listener) { - responder = listener.responder; - props = listener.props; - } - (function() { - if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { - throw ReactError( - Error( - "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponer()." - ) - ); + updateEventListeners( + _listeners2, + workInProgress, + _rootContainerInstance2 + ); + } + } + + if (workInProgress.ref !== null) { + markRef$1(workInProgress); + markUpdate(workInProgress); + } + } else { + if (enableFlareAPI) { + var _prevListeners = current.memoizedProps.listeners; + var _nextListeners = newProps.listeners; + + if ( + _prevListeners !== _nextListeners || + workInProgress.ref !== null + ) { + markUpdate(workInProgress); + } + } else { + if (workInProgress.ref !== null) { + markUpdate(workInProgress); + } + } + + if (current.ref !== workInProgress.ref) { + markRef$1(workInProgress); + } + } + } + + break; } - })(); - var listenerProps = props; - if (visistedResponders.has(responder)) { - // show warning - { - 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 + + default: { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } - return; } - visistedResponders.add(responder); - var responderInstance = respondersMap.get(responder); - if (responderInstance === undefined) { - // Mount - mountEventResponder$1( - responder, - listenerProps, - instance, - rootContainerInstance, - fiber, - respondersMap - ); - } else { - // Update - responderInstance.props = listenerProps; - responderInstance.fiber = fiber; - } + return null; } -function updateEventListeners( - listeners, - instance, - rootContainerInstance, - fiber -) { - var visistedResponders = new Set(); - var dependencies = fiber.dependencies; - if (listeners != null) { - if (dependencies === null) { - dependencies = fiber.dependencies = { - expirationTime: NoWork, - firstContext: null, - responders: new Map() - }; - } - var respondersMap = dependencies.responders; - if (respondersMap === null) { - respondersMap = new Map(); +function unwindWork(workInProgress, renderExpirationTime) { + switch (workInProgress.tag) { + case ClassComponent: { + var Component = workInProgress.type; + + if (isContextProvider(Component)) { + popContext(workInProgress); + } + + var effectTag = workInProgress.effectTag; + + if (effectTag & ShouldCapture) { + workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; + return workInProgress; + } + + return null; } - if (isArray$2(listeners)) { - for (var i = 0, length = listeners.length; i < length; i++) { - var listener = listeners[i]; - updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } else { - updateEventListener( - listeners, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } - if (dependencies !== null) { - var _respondersMap = dependencies.responders; - if (_respondersMap !== null) { - // Unmount - var mountedResponders = Array.from(_respondersMap.keys()); - for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { - var mountedResponder = mountedResponders[_i]; - if (!visistedResponders.has(mountedResponder)) { - var responderInstance = _respondersMap.get(mountedResponder); - unmountResponderInstance(responderInstance); - _respondersMap.delete(mountedResponder); - } - } - } - } -} -function unwindWork(workInProgress, renderExpirationTime) { - switch (workInProgress.tag) { - case ClassComponent: { - var Component = workInProgress.type; - if (isContextProvider(Component)) { - popContext(workInProgress); - } - var effectTag = workInProgress.effectTag; - if (effectTag & ShouldCapture) { - workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; - return workInProgress; - } - return null; - } case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - (function() { - if (!((_effectTag & DidCapture) === NoEffect)) { - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!((_effectTag & DidCapture) === NoEffect)) { + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." + ); + } + workInProgress.effectTag = (_effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } + case SuspenseComponent: { popSuspenseContext(workInProgress); - var _effectTag2 = workInProgress.effectTag; - if (_effectTag2 & ShouldCapture) { - workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } - return null; - } - case DehydratedSuspenseComponent: { + if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (workInProgress.alternate === null) { - // TODO: popHydrationState - } else { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (!(workInProgress.alternate !== null)) { + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + } + resetHydrationState(); } - var _effectTag3 = workInProgress.effectTag; - if (_effectTag3 & ShouldCapture) { - workInProgress.effectTag = - (_effectTag3 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } } + + var _effectTag2 = workInProgress.effectTag; + + if (_effectTag2 & ShouldCapture) { + workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; // Captured a suspense effect. Re-render the boundary. + + return workInProgress; + } + return null; } + case SuspenseListComponent: { - popSuspenseContext(workInProgress); - // SuspenseList doesn't actually catch anything. It should've been + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. + return null; } + case HostPortal: popHostContainer(workInProgress); return null; + case ContextProvider: popProvider(workInProgress); return null; + default: return null; } @@ -16995,37 +17693,41 @@ function unwindInterruptedWork(interruptedWork) { switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } + break; } + case HostRoot: { popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); break; } + case HostComponent: { popHostContext(interruptedWork); break; } + case HostPortal: popHostContainer(interruptedWork); break; + case SuspenseComponent: popSuspenseContext(interruptedWork); break; - case DehydratedSuspenseComponent: - if (enableSuspenseServerRenderer) { - popSuspenseContext(interruptedWork); - } - break; + case SuspenseListComponent: popSuspenseContext(interruptedWork); break; + case ContextProvider: popProvider(interruptedWork); break; + default: break; } @@ -17042,18 +17744,16 @@ function createCapturedValue(value, source) { } // Module provided by RN: -(function() { - if ( - !( - typeof ReactNativePrivateInterface.ReactFiberErrorDialog - .showErrorDialog === "function" - ) - ) { - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") - ); - } -})(); +if ( + !( + typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog === + "function" + ) +) { + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." + ); +} function showErrorDialog(capturedError) { return ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog( @@ -17062,23 +17762,21 @@ function showErrorDialog(capturedError) { } function logCapturedError(capturedError) { - var logError = showErrorDialog(capturedError); - - // Allow injected showErrorDialog() to prevent default console.error logging. + var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. + if (logError === false) { return; } var error = capturedError.error; + { var componentName = capturedError.componentName, componentStack = capturedError.componentStack, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, - willRetry = capturedError.willRetry; - - // Browsers support silencing uncaught errors by calling + willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. @@ -17088,22 +17786,20 @@ function logCapturedError(capturedError) { // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; - } - // The error is fatal. Since the silencing might have + } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. - console.error(error); - // For a more detailed description of this block, see: + + console.error(error); // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; + var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - var errorBoundaryMessage = void 0; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. if (errorBoundaryFound && errorBoundaryName) { if (willRetry) { errorBoundaryMessage = @@ -17121,31 +17817,32 @@ function logCapturedError(capturedError) { "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."; } + var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + - ("" + errorBoundaryMessage); - - // In development, we provide our own message with just the component stack. + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. + console.error(combinedMessage); } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } -var PossiblyWeakSet$1 = typeof WeakSet === "function" ? WeakSet : Set; - +var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source; var stack = errorInfo.stack; + if (stack === null && source !== null) { stack = getStackByFiberInDevAndProd(source); } @@ -17186,9 +17883,8 @@ var callComponentWillUnmountWithTimer = function(current$$1, instance) { instance.state = current$$1.memoizedState; instance.componentWillUnmount(); stopPhaseTimer(); -}; +}; // Capture errors so they don't interrupt unmounting. -// Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback( @@ -17198,6 +17894,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { current$$1, instance ); + if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); @@ -17207,10 +17904,12 @@ function safelyCallComponentWillUnmount(current$$1, instance) { function safelyDetachRef(current$$1) { var ref = current$$1.ref; + if (ref !== null) { if (typeof ref === "function") { { invokeGuardedCallback(null, ref, null, null); + if (hasCaughtError()) { var refError = clearCaughtError(); captureCommitPhaseError(current$$1, refError); @@ -17225,6 +17924,7 @@ function safelyDetachRef(current$$1) { function safelyCallDestroy(current$$1, destroy) { { invokeGuardedCallback(null, destroy, null); + if (hasCaughtError()) { var error = clearCaughtError(); captureCommitPhaseError(current$$1, error); @@ -17240,16 +17940,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); return; } + case ClassComponent: { if (finishedWork.effectTag & Snapshot) { if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, "getSnapshotBeforeUpdate"); - var instance = finishedWork.stateNode; - // We could update instance props and state here, + var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17279,14 +17980,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { : void 0; } } + var snapshot = instance.getSnapshotBeforeUpdate( finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState ); + { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); warningWithoutStack$1( @@ -17297,12 +18001,15 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { ); } } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; stopPhaseTimer(); } } + return; } + case HostRoot: case HostComponent: case HostText: @@ -17310,16 +18017,13 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case IncompleteClassComponent: // Nothing to do for these component types return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17327,18 +18031,22 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { function commitHookEffectList(unmountTag, mountTag, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; + do { if ((effect.tag & unmountTag) !== NoEffect$1) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; + if (destroy !== undefined) { destroy(); } } + if ((effect.tag & mountTag) !== NoEffect$1) { // Mount var create = effect.create; @@ -17346,8 +18054,10 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { { var _destroy = effect.destroy; + if (_destroy !== undefined && typeof _destroy !== "function") { var addendum = void 0; + if (_destroy === null) { addendum = " You returned null. If your effect does not require clean " + @@ -17369,6 +18079,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else { addendum = " You returned: " + _destroy; } + warningWithoutStack$1( false, "An effect function must not return anything besides a function, " + @@ -17379,6 +18090,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } } } + effect = effect.next; } while (effect !== firstEffect); } @@ -17394,6 +18106,7 @@ function commitPassiveHookEffects(finishedWork) { commitHookEffectList(NoEffect$1, MountPassive, finishedWork); break; } + default: break; } @@ -17413,14 +18126,16 @@ function commitLifeCycles( commitHookEffectList(UnmountLayout, MountLayout, finishedWork); break; } + case ClassComponent: { var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update) { if (current$$1 === null) { - startPhaseTimer(finishedWork, "componentDidMount"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidMount"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17450,6 +18165,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidMount(); stopPhaseTimer(); } else { @@ -17461,10 +18177,10 @@ function commitLifeCycles( current$$1.memoizedProps ); var prevState = current$$1.memoizedState; - startPhaseTimer(finishedWork, "componentDidUpdate"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidUpdate"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17494,6 +18210,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidUpdate( prevProps, prevState, @@ -17502,7 +18219,9 @@ function commitLifeCycles( stopPhaseTimer(); } } + var updateQueue = finishedWork.updateQueue; + if (updateQueue !== null) { { if ( @@ -17532,10 +18251,10 @@ function commitLifeCycles( ) : void 0; } - } - // We could update instance props and state here, + } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + commitUpdateQueue( finishedWork, updateQueue, @@ -17543,22 +18262,28 @@ function commitLifeCycles( committedExpirationTime ); } + return; } + case HostRoot: { var _updateQueue = finishedWork.updateQueue; + if (_updateQueue !== null) { var _instance = null; + if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; + case ClassComponent: _instance = finishedWork.child.stateNode; break; } } + commitUpdateQueue( finishedWork, _updateQueue, @@ -17566,15 +18291,16 @@ function commitLifeCycles( committedExpirationTime ); } + return; } - case HostComponent: { - var _instance2 = finishedWork.stateNode; - // Renderers may schedule work to be done after host components are mounted + case HostComponent: { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. + if (current$$1 === null && finishedWork.effectTag & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; @@ -17583,14 +18309,17 @@ function commitLifeCycles( return; } + case HostText: { // We have no life-cycles associated with text. return; } + case HostPortal: { // We have no life-cycles associated with portals. return; } + case Profiler: { if (enableProfilerTimer) { var onRender = finishedWork.memoizedProps.onRender; @@ -17618,23 +18347,27 @@ function commitLifeCycles( } } } + return; } - case SuspenseComponent: + + case SuspenseComponent: { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + return; + } + case SuspenseListComponent: case IncompleteClassComponent: case FundamentalComponent: + case ScopeComponent: return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17642,10 +18375,13 @@ function commitLifeCycles( function hideOrUnhideAllChildren(finishedWork, isHidden) { if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. var node = finishedWork; + while (true) { if (node.tag === HostComponent) { var instance = node.stateNode; + if (isHidden) { hideInstance(instance); } else { @@ -17653,6 +18389,7 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (isHidden) { hideTextInstance(_instance3); } else { @@ -17660,9 +18397,11 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if ( node.tag === SuspenseComponent && - node.memoizedState !== null + node.memoizedState !== null && + node.memoizedState.dehydrated === null ) { // Found a nested Suspense component that timed out. Skip over the + // primary child fragment, which should remain hidden. var fallbackChildFragment = node.child.sibling; fallbackChildFragment.return = node; node = fallbackChildFragment; @@ -17672,15 +18411,19 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -17689,16 +18432,24 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { function commitAttachRef(finishedWork) { var ref = finishedWork.ref; + if (ref !== null) { var instance = finishedWork.stateNode; - var instanceToUse = void 0; + var instanceToUse; + switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; + default: instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag + + if (enableScopeAPI && finishedWork.tag === ScopeComponent) { + instanceToUse = instance.methods; } + if (typeof ref === "function") { ref(instanceToUse); } else { @@ -17721,6 +18472,7 @@ function commitAttachRef(finishedWork) { function commitDetachRef(current$$1) { var currentRef = current$$1.ref; + if (currentRef !== null) { if (typeof currentRef === "function") { currentRef(null); @@ -17728,12 +18480,11 @@ function commitDetachRef(current$$1) { currentRef.current = null; } } -} - -// User-originating errors (lifecycles and refs) should not interrupt +} // User-originating errors (lifecycles and refs) should not interrupt // deletion, so don't let them throw. Host-originating errors should // interrupt deletion, so it's okay -function commitUnmount(current$$1, renderPriorityLevel) { + +function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) { onCommitUnmount(current$$1); switch (current$$1.tag) { @@ -17742,12 +18493,12 @@ function commitUnmount(current$$1, renderPriorityLevel) { case MemoComponent: case SimpleMemoComponent: { var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - // When the owner fiber is deleted, the destroy function of a passive + if (lastEffect !== null) { + var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive // effect hook is called during the synchronous commit phase. This is // a concession to implementation complexity. Calling it in the // passive effect phase (like they usually are, when dependencies @@ -17759,40 +18510,51 @@ function commitUnmount(current$$1, renderPriorityLevel) { // the priority. // // TODO: Reconsider this implementation trade off. + var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; runWithPriority$1(priorityLevel, function() { var effect = firstEffect; + do { var destroy = effect.destroy; + if (destroy !== undefined) { safelyCallDestroy(current$$1, destroy); } + effect = effect.next; } while (effect !== firstEffect); }); } } + break; } + case ClassComponent: { safelyDetachRef(current$$1); var instance = current$$1.stateNode; + if (typeof instance.componentWillUnmount === "function") { safelyCallComponentWillUnmount(current$$1, instance); } + return; } + case HostComponent: { if (enableFlareAPI) { var dependencies = current$$1.dependencies; if (dependencies !== null) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for ( var i = 0, length = responderInstances.length; i < length; @@ -17801,49 +18563,80 @@ function commitUnmount(current$$1, renderPriorityLevel) { var responderInstance = responderInstances[i]; unmountResponderInstance(responderInstance); } + dependencies.responders = null; } } } + safelyDetachRef(current$$1); return; } + case HostPortal: { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if (supportsMutation) { - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else if (supportsPersistence) { emptyPortalContainer(current$$1); } + return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = current$$1.stateNode; + if (fundamentalInstance !== null) { unmountFundamentalComponent(fundamentalInstance); current$$1.stateNode = null; } } + + return; + } + + case DehydratedFragment: { + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(current$$1.stateNode); + } + } + } + + return; + } + + case ScopeComponent: { + if (enableScopeAPI) { + safelyDetachRef(current$$1); + } } } } -function commitNestedUnmounts(root, renderPriorityLevel) { +function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) { // While we're inside a removed host node we don't want to call // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. var node = root; + while (true) { - commitUnmount(node, renderPriorityLevel); - // Visit children because they may contain more composite or host nodes. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes. // Skip portals because commitUnmount() currently visits them recursively. + if ( - node.child !== null && - // If we use mutation we drill down into portals using commitUnmount above. + node.child !== null && // If we use mutation we drill down into portals using commitUnmount above. // If we don't use mutation we drill down into portals here instead. (!supportsMutation || node.tag !== HostPortal) ) { @@ -17851,27 +18644,31 @@ function commitNestedUnmounts(root, renderPriorityLevel) { node = node.child; continue; } + if (node === root) { return; } + while (node.sibling === null) { if (node.return === null || node.return === root) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } function detachFiber(current$$1) { - var alternate = current$$1.alternate; - // Cut off the return pointers to disconnect it from the tree. Ideally, we + var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. This child // itself will be GC:ed when the parent updates the next time. + current$$1.return = null; current$$1.child = null; current$$1.memoizedState = null; @@ -17882,6 +18679,7 @@ function detachFiber(current$$1) { current$$1.lastEffect = null; current$$1.pendingProps = null; current$$1.memoizedProps = null; + if (alternate !== null) { detachFiber(alternate); } @@ -17894,7 +18692,6 @@ function emptyPortalContainer(current$$1) { var portal = current$$1.stateNode; var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); } @@ -17910,45 +18707,41 @@ function commitContainer(finishedWork) { case FundamentalComponent: { return; } + case HostRoot: case HostPortal: { var portalOrRoot = finishedWork.stateNode; var containerInfo = portalOrRoot.containerInfo, - _pendingChildren = portalOrRoot.pendingChildren; - + pendingChildren = portalOrRoot.pendingChildren; return; } + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } function getHostParentFiber(fiber) { var parent = fiber.return; + while (parent !== null) { if (isHostParent(parent)) { return parent; } + parent = parent.return; } - (function() { - { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } function isHostParent(fiber) { @@ -17963,7 +18756,9 @@ function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. var node = fiber; + siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { @@ -17972,31 +18767,34 @@ function getHostSibling(fiber) { // last sibling. return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; + while ( node.tag !== HostComponent && node.tag !== HostText && - node.tag !== DehydratedSuspenseComponent + node.tag !== DehydratedFragment ) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.effectTag & Placement) { // If we don't have a child, try the siblings instead. continue siblings; - } - // If we don't have a child, try the siblings instead. + } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. + if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } - } - // Check if this host node is stable or about to be placed. + } // Check if this host node is stable or about to be placed. + if (!(node.effectTag & Placement)) { // Found it! return node.stateNode; @@ -18007,60 +18805,63 @@ function getHostSibling(fiber) { function commitPlacement(finishedWork) { if (!supportsMutation) { return; - } + } // Recursively insert all host nodes into the parent. - // Recursively insert all host nodes into the parent. - var parentFiber = getHostParentFiber(finishedWork); + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - // Note: these two variables *must* always be updated together. - var parent = void 0; - var isContainer = void 0; + var parent; + var isContainer; var parentStateNode = parentFiber.stateNode; + switch (parentFiber.tag) { case HostComponent: parent = parentStateNode; isContainer = false; break; + case HostRoot: parent = parentStateNode.containerInfo; isContainer = true; break; + case HostPortal: parent = parentStateNode.containerInfo; isContainer = true; break; + case FundamentalComponent: if (enableFundamentalAPI) { parent = parentStateNode.instance; isContainer = false; } + // eslint-disable-next-line-no-fallthrough - default: - (function() { - { - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + default: { + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } } + if (parentFiber.effectTag & ContentReset) { // Reset the text content of the parent before doing any insertions - resetTextContent(parent); - // Clear ContentReset from the effect tag + resetTextContent(parent); // Clear ContentReset from the effect tag + parentFiber.effectTag &= ~ContentReset; } - var before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. + var node = finishedWork; + while (true) { var isHost = node.tag === HostComponent || node.tag === HostText; + if (isHost || (enableFundamentalAPI && node.tag === FundamentalComponent)) { var stateNode = isHost ? node.stateNode : node.stateNode.instance; + if (before) { if (isContainer) { insertInContainerBefore(parent, stateNode, before); @@ -18083,85 +18884,91 @@ function commitPlacement(finishedWork) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel) { +function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) { // We only have the top Fiber that was deleted but we need to recurse down its - var node = current$$1; - - // Each iteration, currentParent is populated with node's host parent if not + // children to find all the terminal nodes. + var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not // currentParentIsValid. - var currentParentIsValid = false; - // Note: these two variables *must* always be updated together. - var currentParent = void 0; - var currentParentIsContainer = void 0; + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. + + var currentParent; + var currentParentIsContainer; while (true) { if (!currentParentIsValid) { var parent = node.return; + findParent: while (true) { - (function() { - if (!(parent !== null)) { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(parent !== null)) { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + var parentStateNode = parent.stateNode; + switch (parent.tag) { case HostComponent: currentParent = parentStateNode; currentParentIsContainer = false; break findParent; + case HostRoot: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case HostPortal: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case FundamentalComponent: if (enableFundamentalAPI) { currentParent = parentStateNode.instance; currentParentIsContainer = false; } } + parent = parent.return; } + currentParentIsValid = true; } if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, node.stateNode); } else { removeChild(currentParent, node.stateNode); - } - // Don't visit children because we already visited them. + } // Don't visit children because we already visited them. } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var fundamentalNode = node.stateNode.instance; - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, fundamentalNode); } else { @@ -18169,9 +18976,20 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { } } else if ( enableSuspenseServerRenderer && - node.tag === DehydratedSuspenseComponent + node.tag === DehydratedFragment ) { - // Delete the dehydrated suspense boundary and all of its content. + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(node.stateNode); + } + } + } // Delete the dehydrated suspense boundary and all of its content. + if (currentParentIsContainer) { clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); } else { @@ -18182,49 +19000,55 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { // When we go into a portal, it becomes the parent to remove from. // We will reassign it back when we pop the portal on the way up. currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; - // Visit children because portals might contain host components. + currentParentIsContainer = true; // Visit children because portals might contain host components. + node.child.return = node; node = node.child; continue; } } else { - commitUnmount(node, renderPriorityLevel); - // Visit children because we may find more host components below. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below. + if (node.child !== null) { node.child.return = node; node = node.child; continue; } } + if (node === current$$1) { return; } + while (node.sibling === null) { if (node.return === null || node.return === current$$1) { return; } + node = node.return; + if (node.tag === HostPortal) { // When we go out of the portal, we need to restore the parent. // Since we don't keep a stack of them, we will search for it. currentParentIsValid = false; } } + node.sibling.return = node.return; node = node.sibling; } } -function commitDeletion(current$$1, renderPriorityLevel) { +function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) { if (supportsMutation) { // Recursively delete all host nodes from the parent. // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else { // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(current$$1, renderPriorityLevel); + commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel); } + detachFiber(current$$1); } @@ -18240,18 +19064,35 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + + case HostRoot: { + if (supportsHydration) { + var root = finishedWork.stateNode; + + if (root.hydrate) { + // We've just hydrated. No need to hydrate again. + root.hydrate = false; + commitHydratedContainer(root.containerInfo); + } + } + + break; + } } commitContainer(finishedWork); @@ -18268,23 +19109,27 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case ClassComponent: { return; } + case HostComponent: { var instance = finishedWork.stateNode; + if (instance != null) { // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps; - var type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; + if (updatePayload !== null) { commitUpdate( instance, @@ -18295,72 +19140,117 @@ function commitWork(current$$1, finishedWork) { finishedWork ); } + + if (enableFlareAPI) { + var prevListeners = oldProps.listeners; + var nextListeners = newProps.listeners; + + if (prevListeners !== nextListeners) { + updateEventListeners(nextListeners, finishedWork, null); + } + } } + return; } + case HostText: { - (function() { - if (!(finishedWork.stateNode !== null)) { - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(finishedWork.stateNode !== null)) { + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldText = current$$1 !== null ? current$$1.memoizedProps : newText; commitTextUpdate(textInstance, oldText, newText); return; } + case HostRoot: { + if (supportsHydration) { + var _root = finishedWork.stateNode; + + if (_root.hydrate) { + // We've just hydrated. No need to hydrate again. + _root.hydrate = false; + commitHydratedContainer(_root.containerInfo); + } + } + return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + case IncompleteClassComponent: { return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = finishedWork.stateNode; updateFundamentalComponent(fundamentalInstance); } + return; } - default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + var scopeInstance = finishedWork.stateNode; + scopeInstance.fiber = finishedWork; + + if (enableFlareAPI) { + var _newProps = finishedWork.memoizedProps; + + var _oldProps = + current$$1 !== null ? current$$1.memoizedProps : _newProps; + + var _prevListeners = _oldProps.listeners; + var _nextListeners = _newProps.listeners; + + if (_prevListeners !== _nextListeners) { + updateEventListeners(_nextListeners, finishedWork, null); + } } - })(); + } + + return; + } + + default: { + { + 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." + ); + } } } } function commitSuspenseComponent(finishedWork) { var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; + var newDidTimeout; var primaryChildParent = finishedWork; + if (newState === null) { newDidTimeout = false; } else { @@ -18375,8 +19265,10 @@ function commitSuspenseComponent(finishedWork) { if (enableSuspenseCallback && newState !== null) { var suspenseCallback = finishedWork.memoizedProps.suspenseCallback; + if (typeof suspenseCallback === "function") { var thenables = finishedWork.updateQueue; + if (thenables !== null) { suspenseCallback(new Set(thenables)); } @@ -18388,23 +19280,67 @@ function commitSuspenseComponent(finishedWork) { } } +function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } + + var newState = finishedWork.memoizedState; + + if (newState === null) { + var current$$1 = finishedWork.alternate; + + if (current$$1 !== null) { + var prevState = current$$1.memoizedState; + + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onHydrated = hydrationCallbacks.onHydrated; + + if (onHydrated) { + onHydrated(suspenseInstance); + } + } + } + } + } + } + } +} + function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of thenables. // For each thenable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. var thenables = finishedWork.updateQueue; + if (thenables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; + if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet$1(); + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } + thenables.forEach(function(thenable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryThenable.bind(null, finishedWork, thenable); + if (!retryCache.has(thenable)) { if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); + if (thenable.__reactDoNotTraceInteractions !== true) { + retry = tracing.unstable_wrap(retry); + } } + retryCache.add(thenable); thenable.then(retry, retry); } @@ -18416,24 +19352,28 @@ function commitResetTextContent(current$$1) { if (!supportsMutation) { return; } + resetTextContent(current$$1.stateNode); } -var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { - var update = createUpdate(expirationTime, null); - // Unmount the root by rendering null. - update.tag = CaptureUpdate; - // Caution: React DevTools currently depends on this property + var update = createUpdate(expirationTime, null); // Unmount the root by rendering null. + + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". - update.payload = { element: null }; + + update.payload = { + element: null + }; var error = errorInfo.value; + update.callback = function() { onUncaughtError(error); logError(fiber, errorInfo); }; + return update; } @@ -18441,8 +19381,10 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime, null); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; + if (typeof getDerivedStateFromError === "function") { var error = errorInfo.value; + update.payload = function() { logError(fiber, errorInfo); return getDerivedStateFromError(error); @@ -18450,27 +19392,30 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { } var inst = fiber.stateNode; + if (inst !== null && typeof inst.componentDidCatch === "function") { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } + if (typeof getDerivedStateFromError !== "function") { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined - // Only log here if componentDidCatch is the only error boundary method defined logError(fiber, errorInfo); } + var error = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error, { componentStack: stack !== null ? stack : "" }); + { if (typeof getDerivedStateFromError !== "function") { // If componentDidCatch is the only error boundary method defined, @@ -18492,6 +19437,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { markFailedErrorBoundaryForHotReloading(fiber); }; } + return update; } @@ -18500,18 +19446,21 @@ function attachPingListener(root, renderExpirationTime, thenable) { // only if one does not already exist for the current render expiration // time (which acts like a "thread ID" here). var pingCache = root.pingCache; - var threadIDs = void 0; + var threadIDs; + if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); threadIDs = new Set(); pingCache.set(thenable, threadIDs); } else { threadIDs = pingCache.get(thenable); + if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(thenable, threadIDs); } } + if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); @@ -18521,9 +19470,6 @@ function attachPingListener(root, renderExpirationTime, thenable) { thenable, renderExpirationTime ); - if (enableSchedulerTracing) { - ping = tracing.unstable_wrap(ping); - } thenable.then(ping, ping); } } @@ -18536,8 +19482,8 @@ function throwException( renderExpirationTime ) { // The source fiber did not complete. - sourceFiber.effectTag |= Incomplete; - // Its effect list is no longer valid. + sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid. + sourceFiber.firstEffect = sourceFiber.lastEffect = null; if ( @@ -18547,34 +19493,31 @@ function throwException( ) { // This is a thenable. var thenable = value; - checkForWrongSuspensePriorityInDEV(sourceFiber); - var hasInvisibleParentBoundary = hasSuspenseContext( suspenseStackCursor.current, InvisibleParentSuspenseContext - ); + ); // Schedule the nearest Suspense to re-render the timed out view. - // Schedule the nearest Suspense to re-render the timed out view. var _workInProgress = returnFiber; + do { if ( _workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary) ) { // Found the nearest boundary. - // Stash the promise on the boundary fiber. If the boundary times out, we'll + // attach another listener to flip the boundary back to its normal state. var thenables = _workInProgress.updateQueue; + if (thenables === null) { var updateQueue = new Set(); updateQueue.add(thenable); _workInProgress.updateQueue = updateQueue; } else { thenables.add(thenable); - } - - // If the boundary is outside of batched mode, we should *not* + } // If the boundary is outside of batched mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. In the commit phase, we'll schedule a // subsequent synchronous update to re-render the Suspense. @@ -18582,16 +19525,17 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a batched mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & BatchedMode) === NoMode) { - _workInProgress.effectTag |= DidCapture; - // We're going to commit this fiber even though it didn't complete. + if ((_workInProgress.mode & BatchedMode) === NoMode) { + _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. + sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call @@ -18605,17 +19549,13 @@ function throwException( update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update); } - } - - // The source fiber did not complete. Mark it with Sync priority to + } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. - sourceFiber.expirationTime = Sync; - // Exit without suspending. - return; - } + sourceFiber.expirationTime = Sync; // Exit without suspending. - // Confirmed that the boundary is in a concurrent mode tree. Continue + return; + } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this @@ -18630,7 +19570,6 @@ function throwException( // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, @@ -18658,56 +19597,16 @@ function throwException( // ensure that new initial loading states can commit as soon as possible. attachPingListener(root, renderExpirationTime, thenable); - - _workInProgress.effectTag |= ShouldCapture; - _workInProgress.expirationTime = renderExpirationTime; - - return; - } else if ( - enableSuspenseServerRenderer && - _workInProgress.tag === DehydratedSuspenseComponent - ) { - attachPingListener(root, renderExpirationTime, thenable); - - // Since we already have a current fiber, we can eagerly add a retry listener. - var retryCache = _workInProgress.memoizedState; - if (retryCache === null) { - retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var current$$1 = _workInProgress.alternate; - (function() { - if (!current$$1) { - throw ReactError( - Error( - "A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React." - ) - ); - } - })(); - current$$1.memoizedState = retryCache; - } - // Memoize using the boundary fiber to prevent redundant listeners. - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - var retry = resolveRetryThenable.bind( - null, - _workInProgress, - thenable - ); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - thenable.then(retry, retry); - } _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; - } - // This boundary already captured during this render. Continue to the next + } // This boundary already captured during this render. Continue to the next // boundary. + _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // No boundary was found. Fallthrough to error mode. + } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode. // TODO: Use invariant so the message is stripped in prod? + value = new Error( (getComponentName(sourceFiber.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n" + @@ -18716,33 +19615,37 @@ function throwException( "provide a loading indicator or placeholder to display." + getStackByFiberInDevAndProd(sourceFiber) ); - } - - // We didn't find a boundary that could handle this type of exception. Start + } // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. + renderDidError(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; + do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; + var _update = createRootErrorUpdate( workInProgress, _errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update); return; } + case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; + if ( (workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === "function" || @@ -18751,142 +19654,153 @@ function throwException( !isAlreadyFailedLegacyErrorBoundary(instance))) ) { workInProgress.effectTag |= ShouldCapture; - workInProgress.expirationTime = renderExpirationTime; - // Schedule the error boundary to re-render using updated state + workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state + var _update2 = createClassErrorUpdate( workInProgress, errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update2); return; } + break; + default: break; } + workInProgress = workInProgress.return; } while (workInProgress !== null); } -// The scheduler is imported here *only* to detect whether it's been mocked -// DEV stuff var ceil = Math.ceil; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; +var NoContext = + /* */ + 0; +var BatchedContext = + /* */ + 1; +var EventContext = + /* */ + 2; +var DiscreteEventContext = + /* */ + 4; +var LegacyUnbatchedContext = + /* */ + 8; +var RenderContext = + /* */ + 16; +var CommitContext = + /* */ + 32; +var RootIncomplete = 0; +var RootFatalErrored = 1; +var RootErrored = 2; +var RootSuspended = 3; +var RootSuspendedWithDelay = 4; +var RootCompleted = 5; +// Describes where we are in the React execution stack +var executionContext = NoContext; // The root we're working on -var NoContext = /* */ 0; -var BatchedContext = /* */ 1; -var EventContext = /* */ 2; -var DiscreteEventContext = /* */ 4; -var LegacyUnbatchedContext = /* */ 8; -var RenderContext = /* */ 16; -var CommitContext = /* */ 32; +var workInProgressRoot = null; // The fiber we're working on -var RootIncomplete = 0; -var RootErrored = 1; -var RootSuspended = 2; -var RootSuspendedWithDelay = 3; -var RootCompleted = 4; +var workInProgress = null; // The expiration time we're rendering -// Describes where we are in the React execution stack -var executionContext = NoContext; -// The root we're working on -var workInProgressRoot = null; -// The fiber we're working on -var workInProgress = null; -// The expiration time we're rendering -var renderExpirationTime = NoWork; -// Whether to root completed, errored, suspended, etc. -var workInProgressRootExitStatus = RootIncomplete; -// Most recent event time among processed updates during this render. +var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc. + +var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown + +var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render. // This is conceptually a time stamp but expressed in terms of an ExpirationTime // because we deal mostly with expiration times in the hot path, so this avoids // the conversion happening in the hot path. + var workInProgressRootLatestProcessedExpirationTime = Sync; var workInProgressRootLatestSuspenseTimeout = Sync; -var workInProgressRootCanSuspendUsingConfig = null; -// If we're pinged while rendering we don't always restart immediately. +var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only +// includes unprocessed updates, not work in bailed out children. + +var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately. // This flag determines if it might be worthwhile to restart if an opportunity // happens latere. -var workInProgressRootHasPendingPing = false; -// The most recent time we committed a fallback. This lets us ensure a train + +var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. + var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; - var nextEffect = null; var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; - var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsRenderPriority = NoPriority; var pendingPassiveEffectsExpirationTime = NoWork; +var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates -var rootsWithPendingDiscreteUpdates = null; - -// Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; - -var interruptedBy = null; - -// Marks the need to reschedule pending interactions at these expiration times +var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times // during the commit phase. This enables them to be traced across components // that spawn new work during render. E.g. hidden boundaries, suspended SSR // hydration or SuspenseList. -var spawnedWorkDuringRender = null; -// Expiration times are computed by adding to the current time (the start +var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start // time). However, if two updates are scheduled within the same event, we // should treat their start times as simultaneous, even if the actual clock // time has advanced between the first and second call. - // In other words, because expiration times determine how updates are batched, // we want all updates of like priority that occur within the same event to // receive the same expiration time. Otherwise we get tearing. -var currentEventTime = NoWork; +var currentEventTime = NoWork; function requestCurrentTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return msToExpirationTime(now()); - } - // We're not inside React, so we may be in the middle of a browser event. + } // We're not inside React, so we may be in the middle of a browser event. + if (currentEventTime !== NoWork) { // Use the same start time for all updates until we enter React again. return currentEventTime; - } - // This is the first update since React yielded. Compute a new start time. + } // This is the first update since React yielded. Compute a new start time. + currentEventTime = msToExpirationTime(now()); return currentEventTime; } - function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { var mode = fiber.mode; + if ((mode & BatchedMode) === NoMode) { return Sync; } var priorityLevel = getCurrentPriorityLevel(); + if ((mode & ConcurrentMode) === NoMode) { return priorityLevel === ImmediatePriority ? Sync : Batched; } if ((executionContext & RenderContext) !== NoContext) { // Use whatever time we're already rendering + // TODO: Should there be a way to opt out, like with `runWithPriority`? return renderExpirationTime; } - var expirationTime = void 0; + var expirationTime; + if (suspenseConfig !== null) { // Compute an expiration time based on the Suspense timeout. expirationTime = computeSuspenseExpiration( @@ -18899,33 +19813,33 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { case ImmediatePriority: expirationTime = Sync; break; + case UserBlockingPriority$1: // TODO: Rename this to computeUserBlockingExpiration expirationTime = computeInteractiveExpiration(currentTime); break; + case NormalPriority: case LowPriority: // TODO: Handle LowPriority // TODO: Rename this to... something better. expirationTime = computeAsyncExpiration(currentTime); break; + case IdlePriority: - expirationTime = Never; + expirationTime = Idle; break; - default: - (function() { - { - throw ReactError(Error("Expected a valid priority level")); - } - })(); - } - } - // If we're in the middle of rendering a tree, do not update at the same + default: { + throw Error("Expected a valid priority level"); + } + } + } // If we're in the middle of rendering a tree, do not update at the same // expiration time that is already rendering. // TODO: We shouldn't have to do this if the update is on a different root. // Refactor computeExpirationForFiber + scheduleUpdate so we have access to // the root when we check for this condition. + if (workInProgressRoot !== null && expirationTime === renderExpirationTime) { // This is a trick to move this update into a separate batch expirationTime -= 1; @@ -18933,47 +19847,40 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { return expirationTime; } - function scheduleUpdateOnFiber(fiber, expirationTime) { checkForNestedUpdates(); warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber); - var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime); + if (root === null) { warnAboutUpdateOnUnmountedFiberInDEV(fiber); return; } - root.pingTime = NoWork; - checkForInterruption(fiber, expirationTime); - recordScheduleUpdate(); - - // TODO: computeExpirationForFiber also reads the priority. Pass the + recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); if (expirationTime === Sync) { if ( // Check if we're inside unbatchedUpdates - (executionContext & LegacyUnbatchedContext) !== NoContext && - // Check if we're not already rendering + (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering (executionContext & (RenderContext | CommitContext)) === NoContext ) { // Register pending interactions on the root to avoid losing traced interaction data. - schedulePendingInteractions(root, expirationTime); - - // This is a legacy edge case. The initial mount of a ReactDOM.render-ed + schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed // root inside of batchedUpdates should be synchronous, but layout updates // should be deferred until the end of the batch. - var callback = renderRoot(root, Sync, true); - while (callback !== null) { - callback = callback(true); - } + + performSyncWorkOnRoot(root); } else { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); + if (executionContext === NoContext) { - // Flush the synchronous work now, wnless we're already working or inside + // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated @@ -18982,12 +19889,12 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { } } } else { - scheduleCallbackForRoot(root, priorityLevel, expirationTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); } if ( - (executionContext & DiscreteEventContext) !== NoContext && - // Only updates at user-blocking priority or greater are considered + (executionContext & DiscreteEventContext) !== NoContext && // Only updates at user-blocking priority or greater are considered // discrete, even inside a discrete event. (priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority) @@ -18998,37 +19905,42 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); } else { var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) { rootsWithPendingDiscreteUpdates.set(root, expirationTime); } } } } -var scheduleWork = scheduleUpdateOnFiber; - -// This is split into a separate function so we can mark a fiber with pending +var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending // work without treating it as a typical update that originates from an event; // e.g. retrying a Suspense boundary isn't an update, but it does schedule work // on a fiber. + function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { // Update the source fiber's expiration time if (fiber.expirationTime < expirationTime) { fiber.expirationTime = expirationTime; } + var alternate = fiber.alternate; + if (alternate !== null && alternate.expirationTime < expirationTime) { alternate.expirationTime = expirationTime; - } - // Walk the parent path to the root and update the child expiration time. + } // Walk the parent path to the root and update the child expiration time. + var node = fiber.return; var root = null; + if (node === null && fiber.tag === HostRoot) { root = fiber.stateNode; } else { while (node !== null) { alternate = node.alternate; + if (node.childExpirationTime < expirationTime) { node.childExpirationTime = expirationTime; + if ( alternate !== null && alternate.childExpirationTime < expirationTime @@ -19041,580 +19953,430 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { ) { alternate.childExpirationTime = expirationTime; } + if (node.return === null && node.tag === HostRoot) { root = node.stateNode; break; } + node = node.return; } } if (root !== null) { - // Update the first and last pending expiration times in this root - var firstPendingTime = root.firstPendingTime; - if (expirationTime > firstPendingTime) { - root.firstPendingTime = expirationTime; - } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime === NoWork || expirationTime < lastPendingTime) { - root.lastPendingTime = expirationTime; - } + if (workInProgressRoot === root) { + // Received an update to a tree that's in the middle of rendering. Mark + // that's unprocessed work on this root. + markUnprocessedUpdateTime(expirationTime); + + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: This happens to work when receiving an update during the render + // phase, because of the trick inside computeExpirationForFiber to + // subtract 1 from `renderExpirationTime` to move it into a + // separate bucket. But we should probably model it with an exception, + // using the same mechanism we use to force hydration of a subtree. + // TODO: This does not account for low pri updates that were already + // scheduled before the root started rendering. Need to track the next + // pending expiration time (perhaps by backtracking the return path) and + // then trigger a restart in the `renderDidSuspendDelayIfPossible` path. + markRootSuspendedAtTime(root, renderExpirationTime); + } + } // Mark that the root has a pending update. + + markRootUpdatedAtTime(root, expirationTime); } return root; } -// Use this function, along with runRootCallback, to ensure that only a single -// callback per root is scheduled. It's still possible to call renderRoot -// directly, but scheduling via this function helps avoid excessive callbacks. -// It works by storing the callback node and expiration time on the root. When a -// new callback comes in, it compares the expiration time to determine if it -// should cancel the previous one. It also relies on commitRoot scheduling a -// callback to render the next level, because that means we don't need a -// separate callback per expiration time. -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - var existingCallbackExpirationTime = root.callbackExpirationTime; - if (existingCallbackExpirationTime < expirationTime) { - // New callback has higher priority than the existing one. - var existingCallbackNode = root.callbackNode; - if (existingCallbackNode !== null) { - cancelCallback(existingCallbackNode); - } - root.callbackExpirationTime = expirationTime; - - if (expirationTime === Sync) { - // Sync React callbacks are scheduled on a special internal queue - root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - ); - } else { - var options = null; - if ( - !disableSchedulerTimeoutBasedOnReactExpirationTime && - expirationTime !== Never - ) { - var timeout = expirationTimeToMs(expirationTime) - now(); - options = { timeout: timeout }; - } - - root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - options - ); - if ( - enableUserTimingAPI && - expirationTime !== Sync && - (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - // Scheduled an async callback, and we're not already working. Add an - // entry to the flamegraph that shows we're waiting for a callback - // to fire. - startRequestCallbackTimer(); - } - } +function getNextRootExpirationTimeToWorkOn(root) { + // Determines the next expiration time that the root should render, taking + // into account levels that may be suspended, or levels that may have + // received a ping. + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + return lastExpiredTime; + } // "Pending" refers to any update that hasn't committed yet, including if it + // suspended. The "suspended" range is therefore a subset. + + var firstPendingTime = root.firstPendingTime; + + if (!isRootSuspendedAtTime(root, firstPendingTime)) { + // The highest priority pending time is not suspended. Let's work on that. + return firstPendingTime; + } // If the first pending time is suspended, check if there's a lower priority + // pending level that we know about. Or check if we received a ping. Work + // on whichever is higher priority. + + var lastPingedTime = root.lastPingedTime; + var nextKnownPendingLevel = root.nextKnownPendingLevel; + return lastPingedTime > nextKnownPendingLevel + ? lastPingedTime + : nextKnownPendingLevel; +} // Use this function to schedule a task for a root. There's only one task per +// root; if a task was already scheduled, we'll check to make sure the +// expiration time of the existing task is the same as the expiration time of +// the next level that the root has work on. This function is called on every +// update, and right before exiting a task. + +function ensureRootIsScheduled(root) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + // Special case: Expired work should flush synchronously. + root.callbackExpirationTime = Sync; + root.callbackPriority = ImmediatePriority; + root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + ); + return; } - // Associate the current interactions with this new root+priority. - schedulePendingInteractions(root, expirationTime); -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + var existingCallbackNode = root.callbackNode; -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode; - var continuation = null; - try { - continuation = callback(isSync); - if (continuation !== null) { - return runRootCallback.bind(null, root, continuation); - } else { - return null; - } - } finally { - // If the callback exits without returning a continuation, remove the - // corresponding callback node from the root. Unless the callback node - // has changed, which implies that it was already cancelled by a high - // priority update. - if (continuation === null && prevCallbackNode === root.callbackNode) { + if (expirationTime === NoWork) { + // There's nothing to work on. + if (existingCallbackNode !== null) { root.callbackNode = null; root.callbackExpirationTime = NoWork; + root.callbackPriority = NoPriority; } - } -} -function flushDiscreteUpdates() { - // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. - // However, `act` uses `batchedUpdates`, so there's no way to distinguish - // those two cases. Need to fix this before exposing flushDiscreteUpdates - // as a public API. - if ( - (executionContext & (BatchedContext | RenderContext | CommitContext)) !== - NoContext - ) { - if (true && (executionContext & RenderContext) !== NoContext) { - warning$1( - false, - "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + - "already rendering." - ); - } - // We're already rendering, so we can't synchronously flush pending work. - // This is probably a nested event dispatch triggered by a lifecycle/effect, - // like `el.focus()`. Exit. return; - } - flushPendingDiscreteUpdates(); - if (!revertPassiveEffectsChange) { - // If the discrete updates scheduled passive effects, flush them now so that - // they fire before the next serial event. - flushPassiveEffects(); - } -} + } // TODO: If this is an update, we already read the current time. Pass the + // time as an argument. -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - if ( - firstBatch !== null && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ) { - scheduleCallback(NormalPriority, function() { - firstBatch._onComplete(); - return null; - }); - return true; - } else { - return false; - } -} + var currentTime = requestCurrentTime(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); // If there's an existing render task, confirm it has the correct priority and + // expiration time. Otherwise, we'll cancel it and schedule a new one. -function flushPendingDiscreteUpdates() { - if (rootsWithPendingDiscreteUpdates !== null) { - // For each root with pending discrete updates, schedule a callback to - // immediately flush them. - var roots = rootsWithPendingDiscreteUpdates; - rootsWithPendingDiscreteUpdates = null; - roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - }); - // Now flush the immediate queue. - flushSyncCallbackQueue(); - } -} + if (existingCallbackNode !== null) { + var existingCallbackPriority = root.callbackPriority; + var existingCallbackExpirationTime = root.callbackExpirationTime; -function batchedUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + if ( + // Callback must have the exact same expiration time. + existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority. + existingCallbackPriority >= priorityLevel + ) { + // Existing callback is sufficient. + return; + } // Need to schedule a new task. + // TODO: Instead of scheduling a new task, we should be able to change the + // priority of the existing one. -function batchedEventUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= EventContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } + cancelCallback(existingCallbackNode); } -} -function discreteUpdates$1(fn, a, b, c) { - var prevExecutionContext = executionContext; - executionContext |= DiscreteEventContext; - try { - // Should this - return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c)); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + var callbackNode; -function flushSync(fn, a) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - (function() { + if (expirationTime === Sync) { + // Sync React callbacks are scheduled on a special internal queue + callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root) + ); + } else { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects + // ordering because tasks are processed in timeout order. { - throw ReactError( - Error( - "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." - ) - ); + timeout: expirationTimeToMs(expirationTime) - now() } - })(); - } - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return runWithPriority$1(ImmediatePriority, fn.bind(null, a)); - } finally { - executionContext = prevExecutionContext; - // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - flushSyncCallbackQueue(); + ); } -} -function prepareFreshStack(root, expirationTime) { - root.finishedWork = null; - root.finishedExpirationTime = NoWork; + root.callbackNode = callbackNode; +} // This is the entry point for every concurrent task, i.e. anything that +// goes through Scheduler. - var timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; - // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - cancelTimeout(timeoutHandle); - } +function performConcurrentWorkOnRoot(root, didTimeout) { + // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. + currentEventTime = NoWork; - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - while (interruptedWork !== null) { - unwindInterruptedWork(interruptedWork); - interruptedWork = interruptedWork.return; - } - } - workInProgressRoot = root; - workInProgress = createWorkInProgress(root.current, null, expirationTime); - renderExpirationTime = expirationTime; - workInProgressRootExitStatus = RootIncomplete; - workInProgressRootLatestProcessedExpirationTime = Sync; - workInProgressRootLatestSuspenseTimeout = Sync; - workInProgressRootCanSuspendUsingConfig = null; - workInProgressRootHasPendingPing = false; + if (didTimeout) { + // The render task took too long to complete. Mark the current time as + // expired to synchronously render all expired work in a single batch. + var currentTime = requestCurrentTime(); + markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback. - if (enableSchedulerTracing) { - spawnedWorkDuringRender = null; - } + ensureRootIsScheduled(root); + return null; + } // Determine the next expiration time to work on, using the fields stored + // on the root. - { - ReactStrictModeWarnings.discardPendingWarnings(); - componentsThatTriggeredHighPriSuspend = null; - } -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + + if (expirationTime !== NoWork) { + var originalCallbackNode = root.callbackNode; -function renderRoot(root, expirationTime, isSync) { - (function() { if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); + throw Error("Should not already be working."); } - })(); - if (enableUserTimingAPI && expirationTime !== Sync) { - var didExpire = isSync; - stopRequestCallbackTimer(didExpire); - } + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root.firstPendingTime < expirationTime) { - // If there's no work left at this expiration time, exit immediately. This - // happens when multiple callbacks are scheduled for a single root, but an - // earlier callback flushes the work of a later one. - return null; - } + if ( + root !== workInProgressRoot || + expirationTime !== renderExpirationTime + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. - if (isSync && root.finishedExpirationTime === expirationTime) { - // There's already a pending commit at this expiration time. - // TODO: This is poorly factored. This case only exists for the - // batch.commit() API. - return commitRoot.bind(null, root); - } + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); - flushPassiveEffects(); + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - // If the root or expiration time have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) { - prepareFreshStack(root, expirationTime); - startWorkOnPendingInteractions(root, expirationTime); - } else if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // We could've received an update at a lower priority while we yielded. - // We're suspended in a delayed state. Once we complete this render we're - // just going to try to recover at the last pending time anyway so we might - // as well start doing that eagerly. - // Ideally we should be able to do this even for retries but we don't yet - // know if we're going to process an update which wants to commit earlier, - // and this path happens very early so it would happen too often. Instead, - // for that case, we'll wait until we complete. - if (workInProgressRootHasPendingPing) { - // We have a ping at this expiration. Let's restart to see if we get unblocked. - prepareFreshStack(root, expirationTime); - } else { - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately, while preserving the position in the queue. - return renderRoot.bind(null, root, lastPendingTime); - } - } - } + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); - // If we have a work-in-progress fiber, it means there's still work to do - // in this root. - if (workInProgress !== null) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - prevDispatcher = ContextOnlyDispatcher; - } - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - startWorkLoopTimer(workInProgress); - - // TODO: Fork renderRoot into renderRootSync and renderRootAsync - if (isSync) { - if (expirationTime !== Sync) { - // An async update expired. There may be other expired updates on - // this root. We should render all the expired work in a - // single batch. - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) { - // Restart at the current time. - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } - return renderRoot.bind(null, root, currentTime); - } + if (enableSchedulerTracing) { + popInteractions(prevInteractions); } - } else { - // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - currentEventTime = NoWork; - } - - do { - try { - if (isSync) { - workLoopSync(); - } else { - workLoop(); - } - break; - } catch (thrownValue) { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooks(); - - var sourceFiber = workInProgress; - if (sourceFiber === null || sourceFiber.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - prepareFreshStack(root, expirationTime); - executionContext = prevExecutionContext; - throw thrownValue; - } - if (enableProfilerTimer && sourceFiber.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true); - } + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; + } - var returnFiber = sourceFiber.return; - throwException( + if (workInProgress !== null) { + // There's still work left over. Exit without committing. + stopInterruptedWorkLoopTimer(); + } else { + // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. + stopFinishedWorkLoopTimer(); + var finishedWork = (root.finishedWork = root.current.alternate); + root.finishedExpirationTime = expirationTime; + finishConcurrentRender( root, - returnFiber, - sourceFiber, - thrownValue, - renderExpirationTime + finishedWork, + workInProgressRootExitStatus, + expirationTime ); - workInProgress = completeUnitOfWork(sourceFiber); } - } while (true); - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } + ensureRootIsScheduled(root); - if (workInProgress !== null) { - // There's still work left over. Return a continuation. - stopInterruptedWorkLoopTimer(); - if (expirationTime !== Sync) { - startRequestCallbackTimer(); + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); } - return renderRoot.bind(null, root, expirationTime); } } - // We now have a consistent tree. The next step is either to commit it, or, if - // something suspended, wait to commit it after a timeout. - stopFinishedWorkLoopTimer(); - - root.finishedWork = root.current.alternate; - root.finishedExpirationTime = expirationTime; - - var isLocked = resolveLocksOnRoot(root, expirationTime); - if (isLocked) { - // This root has a lock that prevents it from committing. Exit. If we begin - // work on the root again, without any intervening updates, it will finish - // without doing additional work. - return null; - } + return null; +} +function finishConcurrentRender( + root, + finishedWork, + exitStatus, + expirationTime +) { // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: { - (function() { - { - throw ReactError(Error("Should have a work-in-progress.")); - } - })(); + switch (exitStatus) { + case RootIncomplete: + case RootFatalErrored: { + { + throw Error("Root did not complete. This is a bug in React."); + } } - // Flow knows about invariant, so it complains if I add a break statement, - // but eslint doesn't know about invariant, so it complains if I do. - // eslint-disable-next-line no-fallthrough + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + case RootErrored: { - // An error was thrown. First check if there is lower priority work - // scheduled on this root. - var _lastPendingTime = root.lastPendingTime; - if (_lastPendingTime < expirationTime) { - // There's lower priority work. Before raising the error, try rendering - // at the lower priority to see if it fixes it. Use a continuation to - // maintain the existing priority and position in the queue. - return renderRoot.bind(null, root, _lastPendingTime); - } - if (!isSync) { - // If we're rendering asynchronously, it's possible the error was - // caused by tearing due to a mutation during an event. Try rendering - // one more time without yiedling to events. - prepareFreshStack(root, expirationTime); - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - return null; - } - // If we're already rendering synchronously, commit the root in its - // errored state. - return commitRoot.bind(null, root); + // If this was an async render, the error may have happened due to + // a mutation in a concurrent event. Try rendering one more time, + // synchronously, to see if the error goes away. If there are + // lower priority updates, let's include those, too, in case they + // fix the inconsistency. Render at Idle to include all updates. + // If it was Idle or Never or some not-yet-invented time, render + // at that time. + markRootExpiredAtTime( + root, + expirationTime > Idle ? Idle : expirationTime + ); // We assume that this second render pass will be synchronous + // and therefore not hit this path again. + + break; } + case RootSuspended: { - flushSuspensePriorityWarningInDEV(); + markRootSuspendedAtTime(root, expirationTime); + var lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } - // We have an acceptable loading state. We need to figure out if we should - // immediately commit it or wait a bit. + flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. + // If we have processed new updates during this render, we may now + // have a new loading state ready. We want to ensure that we commit + // that as soon as possible. - // If we have processed new updates during this render, we may now have a - // new loading state ready. We want to ensure that we commit that as soon as - // possible. var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync; + if ( - hasNotProcessedNewUpdates && - !isSync && - // do not delay if we're inside an act() scope + hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // If we have not processed any new updates during this pass, then this is - // either a retry of an existing fallback state or a hidden tree. - // Hidden trees shouldn't be batched with other work and after that's - // fixed it can only be a retry. - // We're going to throttle committing retries so that we don't show too - // many loading states too quickly. + // If we have not processed any new updates during this pass, then + // this is either a retry of an existing fallback state or a + // hidden tree. Hidden trees shouldn't be batched with other work + // and after that's fixed it can only be a retry. We're going to + // throttle committing retries so that we don't show too many + // loading states too quickly. var msUntilTimeout = - globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - // Don't bother with a very short suspense time. + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. + if (msUntilTimeout > 10) { if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart + // earlier so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } } - var _lastPendingTime2 = root.lastPendingTime; - if (_lastPendingTime2 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level. - return renderRoot.bind(null, root, _lastPendingTime2); + + var nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (nextTime !== NoWork && nextTime !== expirationTime) { + // There's additional work on this root. + break; } - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + + if ( + lastSuspendedTime !== NoWork && + lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = lastSuspendedTime; + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. + root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootSuspendedWithDelay: { + markRootSuspendedAtTime(root, expirationTime); + var _lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === _lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } + flushSuspensePriorityWarningInDEV(); if ( - !isSync && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // We're suspended in a state that should be avoided. We'll try to avoid committing - // it for as long as the timeouts let us. + // We're suspended in a state that should be avoided. We'll try to + // avoid committing it for as long as the timeouts let us. if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var _lastPingedTime = root.lastPingedTime; + + if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart earlier + // so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + + var _nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (_nextTime !== NoWork && _nextTime !== expirationTime) { + // There's additional work on this root. + break; } - var _lastPendingTime3 = root.lastPendingTime; - if (_lastPendingTime3 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately. - return renderRoot.bind(null, root, _lastPendingTime3); + + if ( + _lastSuspendedTime !== NoWork && + _lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = _lastSuspendedTime; + break; } - var _msUntilTimeout = void 0; + var _msUntilTimeout; + if (workInProgressRootLatestSuspenseTimeout !== Sync) { - // We have processed a suspense config whose expiration time we can use as - // the timeout. + // We have processed a suspense config whose expiration time we + // can use as the timeout. _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now(); } else if (workInProgressRootLatestProcessedExpirationTime === Sync) { - // This should never normally happen because only new updates cause - // delayed states, so we should have processed something. However, - // this could also happen in an offscreen tree. + // This should never normally happen because only new updates + // cause delayed states, so we should have processed something. + // However, this could also happen in an offscreen tree. _msUntilTimeout = 0; } else { - // If we don't have a suspense config, we're going to use a heuristic to + // If we don't have a suspense config, we're going to use a + // heuristic to determine how long we can suspend. var eventTimeMs = inferTimeFromExpirationTime( workInProgressRootLatestProcessedExpirationTime ); @@ -19622,40 +20384,40 @@ function renderRoot(root, expirationTime, isSync) { var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs; var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed < 0) { // We get this wrong some time since we estimate the time. timeElapsed = 0; } - _msUntilTimeout = jnd(timeElapsed) - timeElapsed; - - // Clamp the timeout to the expiration time. - // TODO: Once the event time is exact instead of inferred from expiration time + _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the + // event time is exact instead of inferred from expiration time // we don't need this. + if (timeUntilExpirationMs < _msUntilTimeout) { _msUntilTimeout = timeUntilExpirationMs; } - } + } // Don't bother with a very short suspense time. - // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootCompleted: { // The work completed. Ready to commit. if ( - !isSync && // do not delay if we're inside an act() scope !( true && @@ -19667,139 +20429,497 @@ function renderRoot(root, expirationTime, isSync) { ) { // If we have exceeded the minimum loading delay, which probably // means we have shown a spinner already, we might have to suspend - // a bit longer to ensure that the spinner is shown for enough time. + // a bit longer to ensure that the spinner is shown for + // enough time. var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay( workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig ); + if (_msUntilTimeout2 > 10) { + markRootSuspendedAtTime(root, expirationTime); root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout2 ); - return null; + break; } } - return commitRoot.bind(null, root); + + commitRoot(root); + break; } + default: { - (function() { - { - throw ReactError(Error("Unknown root exit status.")); - } - })(); + { + throw Error("Unknown root exit status."); + } } } -} +} // This is the entry point for synchronous tasks that don't go +// through Scheduler -function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); -} +function performSyncWorkOnRoot(root) { + // Check if there's expired work on this root. Otherwise, render at Sync. + var lastExpiredTime = root.lastExpiredTime; + var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync; + + if (root.finishedExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + // TODO: This is poorly factored. This case only exists for the + // batch.commit() API. + commitRoot(root); + } else { + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } + + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. -function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { - if ( - expirationTime < workInProgressRootLatestProcessedExpirationTime && - expirationTime > Never - ) { - workInProgressRootLatestProcessedExpirationTime = expirationTime; - } - if (suspenseConfig !== null) { if ( - expirationTime < workInProgressRootLatestSuspenseTimeout && - expirationTime > Never + root !== workInProgressRoot || + expirationTime !== renderExpirationTime ) { - workInProgressRootLatestSuspenseTimeout = expirationTime; - // Most of the time we only have one config and getting wrong is not bad. - workInProgressRootCanSuspendUsingConfig = suspenseConfig; + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. + + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); + + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (enableSchedulerTracing) { + popInteractions(prevInteractions); + } + + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; + } + + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + { + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + } else { + // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. + stopFinishedWorkLoopTimer(); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = expirationTime; + finishSyncRender(root, workInProgressRootExitStatus, expirationTime); + } // Before exiting, make sure there's a callback scheduled for the next + // pending level. + + ensureRootIsScheduled(root); } } + + return null; } -function renderDidSuspend() { - if (workInProgressRootExitStatus === RootIncomplete) { - workInProgressRootExitStatus = RootSuspended; +function finishSyncRender(root, exitStatus, expirationTime) { + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + { + if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) { + flushSuspensePriorityWarningInDEV(); + } } + + commitRoot(root); } -function renderDidSuspendDelayIfPossible() { +function flushDiscreteUpdates() { + // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. + // However, `act` uses `batchedUpdates`, so there's no way to distinguish + // those two cases. Need to fix this before exposing flushDiscreteUpdates + // as a public API. if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended + (executionContext & (BatchedContext | RenderContext | CommitContext)) !== + NoContext ) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } -} + if (true && (executionContext & RenderContext) !== NoContext) { + warning$1( + false, + "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + + "already rendering." + ); + } // We're already rendering, so we can't synchronously flush pending work. + // This is probably a nested event dispatch triggered by a lifecycle/effect, + // like `el.focus()`. Exit. -function renderDidError() { - if (workInProgressRootExitStatus !== RootCompleted) { - workInProgressRootExitStatus = RootErrored; + return; } -} -// Called during render to determine if anything has suspended. -// Returns false if we're not sure. -function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootIncomplete; -} + flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that + // they fire before the next serial event. -function inferTimeFromExpirationTime(expirationTime) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; + flushPassiveEffects(); } -function inferTimeFromExpirationTimeWithSuspenseConfig( - expirationTime, - suspenseConfig -) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time by subtracting the timeout - // that was added to the event time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return ( - earliestExpirationTimeMs - - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) - ); +function syncUpdates(fn, a, b, c) { + return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c)); } -function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. - while (workInProgress !== null) { - workInProgress = performUnitOfWork(workInProgress); - } -} +function flushPendingDiscreteUpdates() { + if (rootsWithPendingDiscreteUpdates !== null) { + // For each root with pending discrete updates, schedule a callback to + // immediately flush them. + var roots = rootsWithPendingDiscreteUpdates; + rootsWithPendingDiscreteUpdates = null; + roots.forEach(function(expirationTime, root) { + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); + }); // Now flush the immediate queue. -function workLoop() { - // Perform work until Scheduler asks us to yield - while (workInProgress !== null && !shouldYield()) { - workInProgress = performUnitOfWork(workInProgress); + flushSyncCallbackQueue(); } } -function performUnitOfWork(unitOfWork) { - // The current, flushed, state of this fiber is the alternate. Ideally - // nothing should rely on this, but relying on it here means that we don't - // need an additional field on the work in progress. - var current$$1 = unitOfWork.alternate; +function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; - startWorkTimer(unitOfWork); - setCurrentFiber(unitOfWork); + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; - var next = void 0; - if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { - startProfilerTimer(unitOfWork); - next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); - stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); - } else { - next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); - } + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function batchedEventUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= EventContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function discreteUpdates$1(fn, a, b, c) { + var prevExecutionContext = executionContext; + executionContext |= DiscreteEventContext; + + try { + // Should this + return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c)); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} + +function flushSync(fn, a) { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + { + throw Error( + "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." + ); + } + } + + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return runWithPriority$1(ImmediatePriority, fn.bind(null, a)); + } finally { + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. + + flushSyncCallbackQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.finishedWork = null; + root.finishedExpirationTime = NoWork; + var timeoutHandle = root.timeoutHandle; + + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above + + cancelTimeout(timeoutHandle); + } + + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + + while (interruptedWork !== null) { + unwindInterruptedWork(interruptedWork); + interruptedWork = interruptedWork.return; + } + } + + workInProgressRoot = root; + workInProgress = createWorkInProgress(root.current, null, expirationTime); + renderExpirationTime = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; + workInProgressRootLatestProcessedExpirationTime = Sync; + workInProgressRootLatestSuspenseTimeout = Sync; + workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = NoWork; + workInProgressRootHasPendingPing = false; + + if (enableSchedulerTracing) { + spawnedWorkDuringRender = null; + } + + { + ReactStrictModeWarnings.discardPendingWarnings(); + componentsThatTriggeredHighPriSuspend = null; + } +} + +function handleError(root, thrownValue) { + do { + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooks(); + resetCurrentFiber(); + + if (workInProgress === null || workInProgress.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + return null; + } + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true); + } + + throwException( + root, + workInProgress.return, + workInProgress, + thrownValue, + renderExpirationTime + ); + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; + continue; + } // Return to the normal work loop. + + return; + } while (true); +} + +function pushDispatcher(root) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } +} + +function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher.current = prevDispatcher; +} + +function pushInteractions(root) { + if (enableSchedulerTracing) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; + } + + return null; +} + +function popInteractions(prevInteractions) { + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } +} + +function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); +} +function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { + if ( + expirationTime < workInProgressRootLatestProcessedExpirationTime && + expirationTime > Idle + ) { + workInProgressRootLatestProcessedExpirationTime = expirationTime; + } + + if (suspenseConfig !== null) { + if ( + expirationTime < workInProgressRootLatestSuspenseTimeout && + expirationTime > Idle + ) { + workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad. + + workInProgressRootCanSuspendUsingConfig = suspenseConfig; + } + } +} +function markUnprocessedUpdateTime(expirationTime) { + if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) { + workInProgressRootNextUnprocessedUpdateTime = expirationTime; + } +} +function renderDidSuspend() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} +function renderDidSuspendDelayIfPossible() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there's a lower priority update somewhere else in the tree. + + if ( + workInProgressRootNextUnprocessedUpdateTime !== NoWork && + workInProgressRoot !== null + ) { + // Mark the current render as suspended, and then mark that there's a + // pending update. + // TODO: This should immediately interrupt the current render, instead + // of waiting until the next time we yield. + markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime); + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + ); + } +} +function renderDidError() { + if (workInProgressRootExitStatus !== RootCompleted) { + workInProgressRootExitStatus = RootErrored; + } +} // Called during render to determine if anything has suspended. +// Returns false if we're not sure. + +function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootIncomplete; +} + +function inferTimeFromExpirationTime(expirationTime) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; +} + +function inferTimeFromExpirationTimeWithSuspenseConfig( + expirationTime, + suspenseConfig +) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time by subtracting the timeout + // that was added to the event time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return ( + earliestExpirationTimeMs - + (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) + ); +} // The work loop is an extremely hot path. Tell Closure not to inline it. + +/** @noinline */ + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + workInProgress = performUnitOfWork(workInProgress); + } +} +/** @noinline */ + +function workLoopConcurrent() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + workInProgress = performUnitOfWork(workInProgress); + } +} + +function performUnitOfWork(unitOfWork) { + // The current, flushed, state of this fiber is the alternate. Ideally + // nothing should rely on this, but relying on it here means that we don't + // need an additional field on the work in progress. + var current$$1 = unitOfWork.alternate; + startWorkTimer(unitOfWork); + setCurrentFiber(unitOfWork); + var next; + + if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); + } resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { // If this doesn't spawn new work, complete the current work. next = completeUnitOfWork(unitOfWork); @@ -19813,17 +20933,18 @@ function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. workInProgress = unitOfWork; + do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = workInProgress.alternate; - var returnFiber = workInProgress.return; + var returnFiber = workInProgress.return; // Check if the work completed or if something threw. - // Check if the work completed or if something threw. if ((workInProgress.effectTag & Incomplete) === NoEffect) { setCurrentFiber(workInProgress); var next = void 0; + if ( !enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode @@ -19831,10 +20952,11 @@ function completeUnitOfWork(unitOfWork) { next = completeWork(current$$1, workInProgress, renderExpirationTime); } else { startProfilerTimer(workInProgress); - next = completeWork(current$$1, workInProgress, renderExpirationTime); - // Update render duration assuming we didn't error. + next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); } + stopWorkTimer(workInProgress); resetCurrentFiber(); resetChildExpirationTime(workInProgress); @@ -19845,8 +20967,7 @@ function completeUnitOfWork(unitOfWork) { } if ( - returnFiber !== null && - // Do not append effects to parents if a sibling failed to complete + returnFiber !== null && // Do not append effects to parents if a sibling failed to complete (returnFiber.effectTag & Incomplete) === NoEffect ) { // Append all the effects of the subtree and this fiber onto the effect @@ -19855,30 +20976,31 @@ function completeUnitOfWork(unitOfWork) { if (returnFiber.firstEffect === null) { returnFiber.firstEffect = workInProgress.firstEffect; } + if (workInProgress.lastEffect !== null) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; } - returnFiber.lastEffect = workInProgress.lastEffect; - } - // If this fiber had side-effects, we append it AFTER the children's + returnFiber.lastEffect = workInProgress.lastEffect; + } // If this fiber had side-effects, we append it AFTER the children's // side-effects. We can perform certain side-effects earlier if needed, // by doing multiple passes over the effect list. We don't want to // schedule our own side-effect on our own list because if end up // reusing children we'll schedule this effect onto itself since we're // at the end. - var effectTag = workInProgress.effectTag; - // Skip both NoWork and PerformedWork tags when creating the effect + var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect // list. PerformedWork effect is read by React DevTools but shouldn't be // committed. + if (effectTag > PerformedWork) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress; } else { returnFiber.firstEffect = workInProgress; } + returnFiber.lastEffect = workInProgress; } } @@ -19886,24 +21008,23 @@ function completeUnitOfWork(unitOfWork) { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. - var _next = unwindWork(workInProgress, renderExpirationTime); - - // Because this fiber did not complete, don't reset its expiration time. + var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time. if ( enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode ) { // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing. - // Include the time spent working on failed children before continuing. var actualDuration = workInProgress.actualDuration; var child = workInProgress.child; + while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } + workInProgress.actualDuration = actualDuration; } @@ -19918,6 +21039,7 @@ function completeUnitOfWork(unitOfWork) { _next.effectTag &= HostEffectMask; return _next; } + stopWorkTimer(workInProgress); if (returnFiber !== null) { @@ -19928,21 +21050,30 @@ function completeUnitOfWork(unitOfWork) { } var siblingFiber = workInProgress.sibling; + if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; - } - // Otherwise, return to the parent + } // Otherwise, return to the parent + workInProgress = returnFiber; - } while (workInProgress !== null); + } while (workInProgress !== null); // We've reached the root. - // We've reached the root. if (workInProgressRootExitStatus === RootIncomplete) { workInProgressRootExitStatus = RootCompleted; } + return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + var childExpirationTime = fiber.childExpirationTime; + return updateExpirationTime > childExpirationTime + ? updateExpirationTime + : childExpirationTime; +} + function resetChildExpirationTime(completedWork) { if ( renderExpirationTime !== Never && @@ -19953,55 +21084,62 @@ function resetChildExpirationTime(completedWork) { return; } - var newChildExpirationTime = NoWork; + var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time. - // Bubble up the earliest expiration time. if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - - // When a fiber is cloned, its actualDuration is reset to 0. This value will + var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. + var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child; - var child = completedWork.child; + while (child !== null) { var childUpdateExpirationTime = child.expirationTime; var childChildExpirationTime = child.childExpirationTime; + if (childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = childUpdateExpirationTime; } + if (childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = childChildExpirationTime; } + if (shouldBubbleActualDurations) { actualDuration += child.actualDuration; } + treeBaseDuration += child.treeBaseDuration; child = child.sibling; } + completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; + while (_child !== null) { var _childUpdateExpirationTime = _child.expirationTime; var _childChildExpirationTime = _child.childExpirationTime; + if (_childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childUpdateExpirationTime; } + if (_childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childChildExpirationTime; } + _child = _child.sibling; } } @@ -20015,14 +21153,6 @@ function commitRoot(root) { ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel) ); - // If there are passive effects, schedule a callback to flush them. This goes - // outside commitRootImpl so that it inherits the priority of the render. - if (rootWithPendingPassiveEffects !== null) { - scheduleCallback(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } return null; } @@ -20030,51 +21160,42 @@ function commitRootImpl(root, renderPriorityLevel) { flushPassiveEffects(); flushRenderPhaseStrictModeWarningsInDEV(); - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } var finishedWork = root.finishedWork; var expirationTime = root.finishedExpirationTime; + if (finishedWork === null) { return null; } + root.finishedWork = null; root.finishedExpirationTime = NoWork; - (function() { - if (!(finishedWork !== root.current)) { - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - - // commitRoot never returns a continuation; it always finishes synchronously. + if (!(finishedWork !== root.current)) { + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. + root.callbackNode = null; root.callbackExpirationTime = NoWork; - - startCommitTimer(); - - // Update the first and last pending times on this root. The new first + root.callbackPriority = NoPriority; + root.nextKnownPendingLevel = NoWork; + startCommitTimer(); // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime; - var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - var firstPendingTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = firstPendingTimeBeforeCommit; - if (firstPendingTimeBeforeCommit < root.lastPendingTime) { - // This usually means we've finished all the work, but it can also happen - // when something gets downprioritized during render, like a hidden tree. - root.lastPendingTime = firstPendingTimeBeforeCommit; - } + + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + markRootFinishedAtTime( + root, + expirationTime, + remainingExpirationTimeBeforeCommit + ); if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -20082,13 +21203,13 @@ function commitRootImpl(root, renderPriorityLevel) { workInProgress = null; renderExpirationTime = NoWork; } else { - } - // This indicates that the last root we worked on is not the same one that + } // This indicates that the last root we worked on is not the same one that // we're committing now. This most commonly happens when a suspended root // times out. - // Get the list of effects. - var firstEffect = void 0; + + var firstEffect; + if (finishedWork.effectTag > PerformedWork) { // A fiber's effect list consists only of its children, not itself. So if // the root has an effect, we need to add it to the end of the list. The @@ -20108,85 +21229,82 @@ function commitRootImpl(root, renderPriorityLevel) { if (firstEffect !== null) { var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - // Reset this to null before calling lifecycles - ReactCurrentOwner$2.current = null; + var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles - // The commit phase is broken into several sub-phases. We do a separate pass + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. + startCommitSnapshotEffectsTimer(); prepareForCommit(root.containerInfo); nextEffect = firstEffect; + do { { invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); + stopCommitSnapshotEffectsTimer(); if (enableProfilerTimer) { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. - // The next phase is the mutation phase, where we mutate the host tree. startCommitHostEffectsTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( null, commitMutationEffects, null, + root, renderPriorityLevel ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitHostEffectsTimer(); - resetAfterCommit(root.containerInfo); - // The work-in-progress tree is now the current tree. This must come after + stopCommitHostEffectsTimer(); + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. - root.current = finishedWork; - // The next phase is the layout phase, where we call effects that read + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read // the host tree after it's been mutated. The idiomatic use case for this is // layout, but class component lifecycles also fire here for legacy reasons. + startCommitLifeCyclesTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( @@ -20196,41 +21314,44 @@ function commitRootImpl(root, renderPriorityLevel) { root, expirationTime ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error2 = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error2); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitLifeCyclesTimer(); - nextEffect = null; - - // Tell Scheduler to yield at the end of the frame, so the browser has an + stopCommitLifeCyclesTimer(); + nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an // opportunity to paint. + requestPaint(); if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); } + executionContext = prevExecutionContext; } else { // No effects. - root.current = finishedWork; - // Measure these anyway so the flamegraph explicitly shows that there were + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. + startCommitSnapshotEffectsTimer(); stopCommitSnapshotEffectsTimer(); + if (enableProfilerTimer) { recordCommitTime(); } + startCommitHostEffectsTimer(); stopCommitHostEffectsTimer(); startCommitLifeCyclesTimer(); @@ -20238,7 +21359,6 @@ function commitRootImpl(root, renderPriorityLevel) { } stopCommitTimer(); - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { @@ -20253,26 +21373,22 @@ function commitRootImpl(root, renderPriorityLevel) { // nextEffect pointers to assist with GC. If we have passive effects, we'll // clear this in flushPassiveEffects. nextEffect = firstEffect; + while (nextEffect !== null) { var nextNextEffect = nextEffect.nextEffect; nextEffect.nextEffect = null; nextEffect = nextNextEffect; } - } + } // Check if there's remaining work on this root - // Check if there's remaining work on this root var remainingExpirationTime = root.firstPendingTime; - if (remainingExpirationTime !== NoWork) { - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - remainingExpirationTime - ); + if (remainingExpirationTime !== NoWork) { if (enableSchedulerTracing) { if (spawnedWorkDuringRender !== null) { var expirationTimes = spawnedWorkDuringRender; spawnedWorkDuringRender = null; + for (var i = 0; i < expirationTimes.length; i++) { scheduleInteractions( root, @@ -20281,9 +21397,9 @@ function commitRootImpl(root, renderPriorityLevel) { ); } } - } - scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + schedulePendingInteractions(root, remainingExpirationTime); + } } else { // If there's no remaining work, we can clear the set of already failed // error boundaries. @@ -20300,8 +21416,6 @@ function commitRootImpl(root, renderPriorityLevel) { } } - onCommitRoot(finishedWork.stateNode, expirationTime); - if (remainingExpirationTime === Sync) { // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. @@ -20315,6 +21429,11 @@ function commitRootImpl(root, renderPriorityLevel) { nestedUpdateCount = 0; } + onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. + + ensureRootIsScheduled(root); + if (hasUncaughtError) { hasUncaughtError = false; var _error3 = firstUncaughtError; @@ -20328,33 +21447,44 @@ function commitRootImpl(root, renderPriorityLevel) { // synchronously, but layout updates should be deferred until the end // of the batch. return null; - } + } // If layout work was scheduled, flush it now. - // If layout work was scheduled, flush it now. flushSyncCallbackQueue(); return null; } function commitBeforeMutationEffects() { while (nextEffect !== null) { - if ((nextEffect.effectTag & Snapshot) !== NoEffect) { + var effectTag = nextEffect.effectTag; + + if ((effectTag & Snapshot) !== NoEffect) { setCurrentFiber(nextEffect); recordEffect(); - var current$$1 = nextEffect.alternate; commitBeforeMutationLifeCycles(current$$1, nextEffect); - resetCurrentFiber(); } + + if ((effectTag & Passive) !== NoEffect) { + // If there are passive effects, schedule a callback to flush at + // the earliest opportunity. + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + nextEffect = nextEffect.nextEffect; } } -function commitMutationEffects(renderPriorityLevel) { +function commitMutationEffects(root, renderPriorityLevel) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & ContentReset) { @@ -20363,52 +21493,67 @@ function commitMutationEffects(renderPriorityLevel) { if (effectTag & Ref) { var current$$1 = nextEffect.alternate; + if (current$$1 !== null) { commitDetachRef(current$$1); } - } - - // The following switch statement is only concerned about placement, + } // The following switch statement is only concerned about placement, // updates, and deletions. To avoid needing to add a case for every possible // bitmap value, we remove the secondary effects from the effect tag and // switch on that value. - var primaryEffectTag = effectTag & (Placement | Update | Deletion); + + var primaryEffectTag = + effectTag & (Placement | Update | Deletion | Hydrating); + switch (primaryEffectTag) { case Placement: { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. + nextEffect.effectTag &= ~Placement; break; } + case PlacementAndUpdate: { // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - // Update + nextEffect.effectTag &= ~Placement; // Update + var _current = nextEffect.alternate; commitWork(_current, nextEffect); break; } - case Update: { + + case Hydrating: { + nextEffect.effectTag &= ~Hydrating; + break; + } + + case HydratingAndUpdate: { + nextEffect.effectTag &= ~Hydrating; // Update + var _current2 = nextEffect.alternate; commitWork(_current2, nextEffect); break; } + + case Update: { + var _current3 = nextEffect.alternate; + commitWork(_current3, nextEffect); + break; + } + case Deletion: { - commitDeletion(nextEffect, renderPriorityLevel); + commitDeletion(root, nextEffect, renderPriorityLevel); break; } - } + } // TODO: Only record a mutation effect if primaryEffectTag is non-zero. - // TODO: Only record a mutation effect if primaryEffectTag is non-zero. recordEffect(); - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } @@ -20418,7 +21563,6 @@ function commitLayoutEffects(root, committedExpirationTime) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) { @@ -20432,88 +21576,78 @@ function commitLayoutEffects(root, committedExpirationTime) { commitAttachRef(nextEffect); } - if (effectTag & Passive) { - rootDoesHavePassiveEffects = true; - } - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } } function flushPassiveEffects() { + if (pendingPassiveEffectsRenderPriority !== NoPriority) { + var priorityLevel = + pendingPassiveEffectsRenderPriority > NormalPriority + ? NormalPriority + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = NoPriority; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} + +function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } + var root = rootWithPendingPassiveEffects; var expirationTime = pendingPassiveEffectsExpirationTime; - var renderPriorityLevel = pendingPassiveEffectsRenderPriority; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = NoWork; - pendingPassiveEffectsRenderPriority = NoPriority; - var priorityLevel = - renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; - return runWithPriority$1( - priorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Cannot flush passive effects while already rendering."); } - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); - } - })(); var prevExecutionContext = executionContext; executionContext |= CommitContext; - - // Note: This currently assumes there are no passive effects on the root + var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root // fiber, because the root is not part of its own effect list. This could // change in the future. + var effect = root.current.firstEffect; + while (effect !== null) { { setCurrentFiber(effect); invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + if (hasCaughtError()) { - (function() { - if (!(effect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(effect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(effect, error); } + resetCurrentFiber(); } - var nextNextEffect = effect.nextEffect; - // Remove nextEffect pointer to assist GC + + var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC + effect.nextEffect = null; effect = nextNextEffect; } if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); finishPendingInteractions(root, expirationTime); } executionContext = prevExecutionContext; - flushSyncCallbackQueue(); - - // If additional passive effects were scheduled, increment a counter. If this + flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; - return true; } @@ -20523,7 +21657,6 @@ function isAlreadyFailedLegacyErrorBoundary(instance) { legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } - function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); @@ -20538,6 +21671,7 @@ function prepareToThrowUncaughtError(error) { firstUncaughtError = error; } } + var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { @@ -20545,8 +21679,10 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); enqueueUpdate(rootFiber, update); var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } } @@ -20559,6 +21695,7 @@ function captureCommitPhaseError(sourceFiber, error) { } var fiber = sourceFiber.return; + while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); @@ -20566,6 +21703,7 @@ function captureCommitPhaseError(sourceFiber, error) { } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; + if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && @@ -20574,24 +21712,27 @@ function captureCommitPhaseError(sourceFiber, error) { var errorInfo = createCapturedValue(error, sourceFiber); var update = createClassErrorUpdate( fiber, - errorInfo, - // TODO: This is always sync + errorInfo, // TODO: This is always sync Sync ); enqueueUpdate(fiber, update); var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } + return; } } + fiber = fiber.return; } } - function pingSuspendedRoot(root, thenable, suspendedTime) { var pingCache = root.pingCache; + if (pingCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. @@ -20602,10 +21743,8 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. - // If we're suspended with delay, we'll always suspend so we can always // restart. If we're suspended without any updates, it might be a retry. // If it's early in the retry we can restart. We can't know for sure @@ -20626,23 +21765,23 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // opportunity later. So we mark this render as having a ping. workInProgressRootHasPendingPing = true; } + return; } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < suspendedTime) { + if (!isRootSuspendedAtTime(root, suspendedTime)) { // The root is no longer suspended at this time. return; } - var pingTime = root.pingTime; - if (pingTime !== NoWork && pingTime < suspendedTime) { + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) { // There's already a lower priority ping scheduled. return; - } + } // Mark the time at which this ping was scheduled. - // Mark the time at which this ping was scheduled. - root.pingTime = suspendedTime; + root.lastPingedTime = suspendedTime; if (root.finishedExpirationTime === suspendedTime) { // If there's a pending fallback waiting to commit, throw it away. @@ -20650,54 +21789,70 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { root.finishedWork = null; } - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - suspendedTime - ); - scheduleCallbackForRoot(root, priorityLevel, suspendedTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, suspendedTime); } -function retryTimedOutBoundary(boundaryFiber) { +function retryTimedOutBoundary(boundaryFiber, retryTime) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new expiration time. - var currentTime = requestCurrentTime(); - var suspenseConfig = null; // Retries don't carry over the already committed update. - var retryTime = computeExpirationForFiber( - currentTime, - boundaryFiber, - suspenseConfig - ); - // TODO: Special case idle priority? - var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + if (retryTime === NoWork) { + var suspenseConfig = null; // Retries don't carry over the already committed update. + + var currentTime = requestCurrentTime(); + retryTime = computeExpirationForFiber( + currentTime, + boundaryFiber, + suspenseConfig + ); + } // TODO: Special case idle priority? + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { - scheduleCallbackForRoot(root, priorityLevel, retryTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, retryTime); } } +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryTime = NoWork; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + + retryTimedOutBoundary(boundaryFiber, retryTime); +} function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = void 0; + var retryTime = NoWork; // Default + + var retryCache; + if (enableSuspenseServerRenderer) { switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + break; - case DehydratedSuspenseComponent: - retryCache = boundaryFiber.memoizedState; + + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; break; - default: - (function() { - { - throw ReactError( - Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ) - ); - } - })(); + + default: { + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } } } else { retryCache = boundaryFiber.stateNode; @@ -20709,10 +21864,8 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); -} - -// Computes the next Just Noticeable Difference (JND) boundary. + retryTimedOutBoundary(boundaryFiber, retryTime); +} // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid @@ -20721,6 +21874,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. + function jnd(timeElapsed) { return timeElapsed < 120 ? 120 @@ -20743,25 +21897,28 @@ function computeMsUntilSuspenseLoadingDelay( suspenseConfig ) { var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0; + if (busyMinDurationMs <= 0) { return 0; } - var busyDelayMs = suspenseConfig.busyDelayMs | 0; - // Compute the time until this render pass would expire. + var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire. + var currentTimeMs = now(); var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig( mostRecentEventTime, suspenseConfig ); var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed <= busyDelayMs) { // If we haven't yet waited longer than the initial delay, we don't // have to wait any additional time. return 0; } - var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; - // This is the value that is passed to `setTimeout`. + + var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`. + return msUntilTimeout; } @@ -20769,15 +21926,12 @@ function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; - (function() { - { - throw ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) - ); - } - })(); + + { + 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." + ); + } } { @@ -20828,9 +21982,11 @@ function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { } var didWarnStateUpdateForUnmountedComponent = null; + function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { { var tag = fiber.tag; + if ( tag !== HostRoot && tag !== ClassComponent && @@ -20841,18 +21997,21 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { ) { // Only warn for user-defined components, not internal ones like Suspense. return; - } - // We show the whole stack but dedupe on the top component's name because + } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent !== null) { if (didWarnStateUpdateForUnmountedComponent.has(componentName)) { return; } + didWarnStateUpdateForUnmountedComponent.add(componentName); } else { didWarnStateUpdateForUnmountedComponent = new Set([componentName]); } + warningWithoutStack$1( false, "Can't perform a React state update on an unmounted component. This " + @@ -20866,20 +22025,22 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { } } -var beginWork$$1 = void 0; +var beginWork$$1; + if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var dummyFiber = null; + beginWork$$1 = function(current$$1, unitOfWork, expirationTime) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV( dummyFiber, unitOfWork ); + try { return beginWork$1(current$$1, unitOfWork, expirationTime); } catch (originalError) { @@ -20890,25 +22051,23 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ) { // Don't replay promises. Treat everything else like an error. throw originalError; - } - - // Keep this code in sync with renderRoot; any changes here must have + } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. - resetContextDependencies(); - resetHooks(); + resetContextDependencies(); + resetHooks(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. // Unwind the failed stack frame - unwindInterruptedWork(unitOfWork); - // Restore the original properties of the fiber. + unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber. + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if (enableProfilerTimer && unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); - } + } // Run beginWork again. - // Run beginWork again. invokeGuardedCallback( null, beginWork$1, @@ -20919,9 +22078,9 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ); if (hasCaughtError()) { - var replayError = clearCaughtError(); - // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. + var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. // Rethrow this error instead of the original one. + throw replayError; } else { // This branch is reachable if the render phase is impure. @@ -20935,6 +22094,7 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInGetChildContext = false; + function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { { if (fiber.tag === ClassComponent) { @@ -20943,16 +22103,19 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { if (didWarnAboutUpdateInGetChildContext) { return; } + warningWithoutStack$1( false, "setState(...): Cannot call setState() inside getChildContext()" ); didWarnAboutUpdateInGetChildContext = true; break; + case "render": if (didWarnAboutUpdateInRender) { return; } + warningWithoutStack$1( false, "Cannot update during an existing state transition (such as " + @@ -20964,11 +22127,11 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { } } } -} - -// a 'shared' variable that changes when act() opens/closes in tests. -var IsThisRendererActing = { current: false }; +} // a 'shared' variable that changes when act() opens/closes in tests. +var IsThisRendererActing = { + current: false +}; function warnIfNotScopedWithMatchingAct(fiber) { { if ( @@ -20995,7 +22158,6 @@ function warnIfNotScopedWithMatchingAct(fiber) { } } } - function warnIfNotCurrentlyActingEffectsInDEV(fiber) { { if ( @@ -21052,11 +22214,9 @@ function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { } } -var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; +var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler. -// In tests, we want to enforce a mocked scheduler. -var didWarnAboutUnmockedScheduler = false; -// TODO Before we release concurrent mode, revisit this and decide whether a mocked +var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked // scheduler is the actual recommendation. The alternative could be a testing build, // a new lib, or whatever; we dunno just yet. This message is for early adopters // to get their tests right. @@ -21091,20 +22251,22 @@ function warnIfUnmockedScheduler(fiber) { } } } - var componentsThatTriggeredHighPriSuspend = null; function checkForWrongSuspensePriorityInDEV(sourceFiber) { { var currentPriorityLevel = getCurrentPriorityLevel(); + if ( (sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority$1 || currentPriorityLevel === ImmediatePriority) ) { var workInProgressNode = sourceFiber; + while (workInProgressNode !== null) { // Add the component that triggered the suspense var current$$1 = workInProgressNode.alternate; + if (current$$1 !== null) { // TODO: warn component that triggers the high priority // suspend is the HostRoot @@ -21113,10 +22275,13 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { // Loop through the component's update queue and see whether the component // has triggered any high priority updates var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var update = updateQueue.firstUpdate; + while (update !== null) { var priorityLevel = update.priority; + if ( priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority @@ -21130,12 +22295,16 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + update = update.next; } } + break; + case FunctionComponent: case ForwardRef: case SimpleMemoComponent: @@ -21143,11 +22312,12 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null ) { - var _update = workInProgressNode.memoizedState.baseUpdate; - // Loop through the functional component's memoized state to see whether + var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether // the component has triggered any high pri updates + while (_update !== null) { var priority = _update.priority; + if ( priority === UserBlockingPriority$1 || priority === ImmediatePriority @@ -21161,21 +22331,27 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + if ( _update.next === workInProgressNode.memoizedState.baseUpdate ) { break; } + _update = _update.next; } } + break; + default: break; } } + workInProgressNode = workInProgressNode.return; } } @@ -21201,8 +22377,7 @@ function flushSuspensePriorityWarningInDEV() { "triggers the bulk of the changes." + "\n\n" + "Refer to the documentation for useSuspenseTransition to learn how " + - "to implement this pattern.", - // TODO: Add link to React docs with more information, once it exists + "to implement this pattern.", // TODO: Add link to React docs with more information, once it exists componentNames.sort().join(", ") ); } @@ -21219,6 +22394,7 @@ function markSpawnedWork(expirationTime) { if (!enableSchedulerTracing) { return; } + if (spawnedWorkDuringRender === null) { spawnedWorkDuringRender = [expirationTime]; } else { @@ -21234,6 +22410,7 @@ function scheduleInteractions(root, expirationTime, interactions) { if (interactions.size > 0) { var pendingInteractionMap = root.pendingInteractionMap; var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { interactions.forEach(function(interaction) { if (!pendingInteractions.has(interaction)) { @@ -21244,15 +22421,15 @@ function scheduleInteractions(root, expirationTime, interactions) { pendingInteractions.add(interaction); }); } else { - pendingInteractionMap.set(expirationTime, new Set(interactions)); + pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions. - // Update the pending async work count for the current interactions. interactions.forEach(function(interaction) { interaction.__count++; }); } var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); subscriber.onWorkScheduled(interactions, threadID); @@ -21275,11 +22452,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { // This is called when new work is started on a root. if (!enableSchedulerTracing) { return; - } - - // Determine which interactions this batch of work currently includes, So that + } // Determine which interactions this batch of work currently includes, So that // we can accurately attribute time spent working on it, And so that cascading // work triggered during the render phase will be associated with it. + var interactions = new Set(); root.pendingInteractionMap.forEach(function( scheduledInteractions, @@ -21290,19 +22466,20 @@ function startWorkOnPendingInteractions(root, expirationTime) { return interactions.add(interaction); }); } - }); + }); // Store the current set of interactions on the FiberRoot for a few reasons: + // We can re-use it in hot functions like performConcurrentWorkOnRoot() + // without having to recalculate it. We will also use it in commitWork() to + // pass to any Profiler onRender() hooks. This also provides DevTools with a + // way to access it when the onCommitRoot() hook is called. - // Store the current set of interactions on the FiberRoot for a few reasons: - // We can re-use it in hot functions like renderRoot() without having to - // recalculate it. We will also use it in commitWork() to pass to any Profiler - // onRender() hooks. This also provides DevTools with a way to access it when - // the onCommitRoot() hook is called. root.memoizedInteractions = interactions; if (interactions.size > 0) { var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); + try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { @@ -21321,11 +22498,11 @@ function finishPendingInteractions(root, committedExpirationTime) { } var earliestRemainingTimeAfterCommit = root.firstPendingTime; - - var subscriber = void 0; + var subscriber; try { subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { var threadID = computeThreadID(root, committedExpirationTime); subscriber.onWorkStopped(root.memoizedInteractions, threadID); @@ -21349,7 +22526,6 @@ function finishPendingInteractions(root, committedExpirationTime) { // That indicates that we are waiting for suspense data. if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { pendingInteractionMap.delete(scheduledExpirationTime); - scheduledInteractions.forEach(function(interaction) { interaction.__count--; @@ -21372,21 +22548,22 @@ function finishPendingInteractions(root, committedExpirationTime) { var onCommitFiberRoot = null; var onCommitFiberUnmount = null; var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; - function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { // No DevTools return false; } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } + if (!hook.supportsFiber) { { warningWithoutStack$1( @@ -21395,16 +22572,18 @@ function injectInternals(internals) { "with the current version of React. Please update React DevTools. " + "https://fb.me/react-devtools" ); - } - // DevTools exists, even though it doesn't support Fiber. + } // DevTools exists, even though it doesn't support Fiber. + return true; } + try { - var rendererID = hook.inject(internals); - // We have successfully injected, so now it is safe to set up hooks. + var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. + onCommitFiberRoot = function(root, expirationTime) { try { var didError = (root.current.effectTag & DidCapture) === DidCapture; + if (enableProfilerTimer) { var currentTime = requestCurrentTime(); var priorityLevel = inferPriorityFromExpirationTime( @@ -21426,6 +22605,7 @@ function injectInternals(internals) { } } }; + onCommitFiberUnmount = function(fiber) { try { hook.onCommitFiberUnmount(rendererID, fiber); @@ -21449,34 +22629,33 @@ function injectInternals(internals) { err ); } - } - // DevTools exists + } // DevTools exists + return true; } - function onCommitRoot(root, expirationTime) { if (typeof onCommitFiberRoot === "function") { onCommitFiberRoot(root, expirationTime); } } - function onCommitUnmount(fiber) { if (typeof onCommitFiberUnmount === "function") { onCommitFiberUnmount(fiber); } } -var hasBadMapPolyfill = void 0; +var hasBadMapPolyfill; { hasBadMapPolyfill = false; + try { var nonExtensibleObject = Object.preventExtensions({}); var testMap = new Map([[nonExtensibleObject, null]]); - var testSet = new Set([nonExtensibleObject]); - // This is necessary for Rollup to not consider these unused. + var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. + testMap.set(0, 0); testSet.add(0); } catch (e) { @@ -21485,14 +22664,7 @@ var hasBadMapPolyfill = void 0; } } -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. - -var debugCounter = void 0; - -{ - debugCounter = 1; -} +var debugCounter = 1; function FiberNode(tag, pendingProps, key, mode) { // Instance @@ -21500,34 +22672,26 @@ function FiberNode(tag, pendingProps, key, mode) { this.key = key; this.elementType = null; this.type = null; - this.stateNode = null; + this.stateNode = null; // Fiber - // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; + this.mode = mode; // Effects - this.mode = mode; - - // Effects this.effectTag = NoEffect; this.nextEffect = null; - this.firstEffect = null; this.lastEffect = null; - this.expirationTime = NoWork; this.childExpirationTime = NoWork; - this.alternate = null; if (enableProfilerTimer) { @@ -21546,31 +22710,33 @@ function FiberNode(tag, pendingProps, key, mode) { this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - - // It's okay to replace the initial doubles with smis after initialization. + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). + this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; + } // This is normally DEV-only except www when it adds listeners. + // TODO: remove the User Timing integration in favor of Root Events. + + if (enableUserTimingAPI) { + this._debugID = debugCounter++; + this._debugIsCurrentlyTiming = false; } { - this._debugID = debugCounter++; this._debugSource = null; this._debugOwner = null; - this._debugIsCurrentlyTiming = false; this._debugNeedsRemount = false; this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } } -} - -// This is a constructor function, rather than a POJO constructor, still +} // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost @@ -21583,6 +22749,7 @@ function FiberNode(tag, pendingProps, key, mode) { // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. + var createFiber = function(tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); @@ -21600,25 +22767,27 @@ function isSimpleFunctionComponent(type) { type.defaultProps === undefined ); } - function resolveLazyComponentTag(Component) { if (typeof Component === "function") { return shouldConstruct(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; + if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } + if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } + return IndeterminateComponent; -} +} // This is used to create an alternate fiber to do work on. -// This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps, expirationTime) { var workInProgress = current.alternate; + if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused @@ -21646,13 +22815,11 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.alternate = current; current.alternate = workInProgress; } else { - workInProgress.pendingProps = pendingProps; - - // We already have an alternate. + workInProgress.pendingProps = pendingProps; // We already have an alternate. // Reset the effect tag. - workInProgress.effectTag = NoEffect; - // The effect list is no longer valid. + workInProgress.effectTag = NoEffect; // The effect list is no longer valid. + workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; @@ -21669,14 +22836,12 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21685,9 +22850,8 @@ function createWorkInProgress(current, pendingProps, expirationTime) { expirationTime: currentDependencies.expirationTime, firstContext: currentDependencies.firstContext, responders: currentDependencies.responders - }; + }; // These will be overridden during the parent's reconciliation - // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; @@ -21699,56 +22863,54 @@ function createWorkInProgress(current, pendingProps, expirationTime) { { workInProgress._debugNeedsRemount = current._debugNeedsRemount; + switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; + case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; + case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; + default: break; } } return workInProgress; -} +} // Used to reuse a Fiber for a second pass. -// Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderExpirationTime) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. - // Reset the effect tag but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. - workInProgress.effectTag &= Placement; + workInProgress.effectTag &= Placement; // The effect list is no longer valid. - // The effect list is no longer valid. workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; - var current = workInProgress.alternate; + if (current === null) { // Reset to createFiber's initial values. workInProgress.childExpirationTime = NoWork; workInProgress.expirationTime = renderExpirationTime; - workInProgress.child = null; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; - workInProgress.dependencies = null; if (enableProfilerTimer) { @@ -21761,14 +22923,12 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21789,9 +22949,9 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { return workInProgress; } - function createHostRootFiber(tag) { - var mode = void 0; + var mode; + if (tag === ConcurrentRoot) { mode = ConcurrentMode | BatchedMode | StrictMode; } else if (tag === BatchedRoot) { @@ -21809,7 +22969,6 @@ function createHostRootFiber(tag) { return createFiber(HostRoot, null, null, mode); } - function createFiberFromTypeAndProps( type, // React$ElementType key, @@ -21818,14 +22977,15 @@ function createFiberFromTypeAndProps( mode, expirationTime ) { - var fiber = void 0; + var fiber; + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - var fiberTag = IndeterminateComponent; - // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; + if (typeof type === "function") { if (shouldConstruct(type)) { fiberTag = ClassComponent; + { resolvedType = resolveClassForHotReloading(resolvedType); } @@ -21845,18 +23005,23 @@ function createFiberFromTypeAndProps( expirationTime, key ); + case REACT_CONCURRENT_MODE_TYPE: fiberTag = Mode; mode |= ConcurrentMode | BatchedMode | StrictMode; break; + case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictMode; break; + case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList( pendingProps, @@ -21864,29 +23029,37 @@ function createFiberFromTypeAndProps( expirationTime, key ); + default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; + case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; + case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; + { resolvedType = resolveForwardRefForHotReloading(resolvedType); } + break getTag; + case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; + case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_FUNDAMENTAL_TYPE: if (enableFundamentalAPI) { return createFiberFromFundamental( @@ -21897,10 +23070,24 @@ function createFiberFromTypeAndProps( key ); } + break; + + case REACT_SCOPE_TYPE: + if (enableScopeAPI) { + return createFiberFromScope( + type, + pendingProps, + mode, + expirationTime, + key + ); + } } } + var info = ""; + { if ( type === undefined || @@ -21913,23 +23100,22 @@ function createFiberFromTypeAndProps( "it's defined in, or you might have mixed up default and " + "named imports."; } + var ownerName = owner ? getComponentName(owner.type) : null; + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } } - (function() { - { - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (type == null ? type : typeof type) + - "." + - info - ) - ); - } - })(); + + { + 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 + ); + } } } } @@ -21938,15 +23124,15 @@ function createFiberFromTypeAndProps( fiber.elementType = type; fiber.type = resolvedType; fiber.expirationTime = expirationTime; - return fiber; } - function createFiberFromElement(element, mode, expirationTime) { var owner = null; + { owner = element._owner; } + var type = element.type; var key = element.key; var pendingProps = element.props; @@ -21958,19 +23144,19 @@ function createFiberFromElement(element, mode, expirationTime) { mode, expirationTime ); + { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } + return fiber; } - function createFiberFromFragment(elements, mode, expirationTime, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromFundamental( fundamentalComponent, pendingProps, @@ -21985,6 +23171,14 @@ function createFiberFromFundamental( return fiber; } +function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) { + var fiber = createFiber(ScopeComponent, pendingProps, key, mode); + fiber.type = scope; + fiber.elementType = scope; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -21998,76 +23192,74 @@ function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { } } - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - // TODO: The Profiler fiber shouldn't have a type. It has a tag. + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag. + fiber.elementType = REACT_PROFILER_TYPE; fiber.type = REACT_PROFILER_TYPE; fiber.expirationTime = expirationTime; - return fiber; } function createFiberFromSuspense(pendingProps, mode, expirationTime, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - - // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. + fiber.type = REACT_SUSPENSE_TYPE; fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + { // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. fiber.type = REACT_SUSPENSE_LIST_TYPE; } + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromText(content, mode, expirationTime) { var fiber = createFiber(HostText, content, null, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - // TODO: These should not need a type. + var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type. + fiber.elementType = "DELETED"; fiber.type = "DELETED"; return fiber; } - +function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; +} function createFiberFromPortal(portal, mode, expirationTime) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.expirationTime = expirationTime; fiber.stateNode = { containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates + pendingChildren: null, + // Used by persistent updates implementation: portal.implementation }; return fiber; -} +} // Used for stashing WIP properties to replay failed work in DEV. -// Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); - } - - // This is intentionally written as a list of all properties. + } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 @@ -22096,12 +23288,14 @@ function assignFiberPropertiesInDEV(target, source) { target.expirationTime = source.expirationTime; target.childExpirationTime = source.childExpirationTime; target.alternate = source.alternate; + if (enableProfilerTimer) { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } + target._debugID = source._debugID; target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; @@ -22111,19 +23305,6 @@ function assignFiberPropertiesInDEV(target, source) { return target; } -// TODO: This should be lifted into the renderer. - -// The following attributes are only used by interaction tracing builds. -// They enable interactions to be associated with their async work, -// And expose interaction metadata to the React DevTools Profiler plugin. -// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. - -// Exported FiberRoot type includes all properties, -// To avoid requiring potentially error-prone :any casts throughout the project. -// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true). -// The types are defined separately within this file to ensure they stay in sync. -// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.) - function FiberRootNode(containerInfo, tag, hydrate) { this.tag = tag; this.current = null; @@ -22136,31 +23317,129 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.context = null; this.pendingContext = null; this.hydrate = hydrate; - this.firstBatch = null; this.callbackNode = null; - this.callbackExpirationTime = NoWork; + this.callbackPriority = NoPriority; this.firstPendingTime = NoWork; - this.lastPendingTime = NoWork; - this.pingTime = NoWork; + this.firstSuspendedTime = NoWork; + this.lastSuspendedTime = NoWork; + this.nextKnownPendingLevel = NoWork; + this.lastPingedTime = NoWork; + this.lastExpiredTime = NoWork; if (enableSchedulerTracing) { this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } + + if (enableSuspenseCallback) { + this.hydrationCallbacks = null; + } } -function createFiberRoot(containerInfo, tag, hydrate) { +function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate); - // Cyclic construction. This cheats the type system right now because + if (enableSuspenseCallback) { + root.hydrationCallbacks = hydrationCallbacks; + } // Cyclic construction. This cheats the type system right now because // stateNode is any. + var uninitializedFiber = createHostRootFiber(tag); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - return root; } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + return ( + firstSuspendedTime !== NoWork && + firstSuspendedTime >= expirationTime && + lastSuspendedTime <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + + if (firstSuspendedTime < expirationTime) { + root.firstSuspendedTime = expirationTime; + } + + if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) { + root.lastSuspendedTime = expirationTime; + } + + if (expirationTime <= root.lastPingedTime) { + root.lastPingedTime = NoWork; + } + + if (expirationTime <= root.lastExpiredTime) { + root.lastExpiredTime = NoWork; + } +} +function markRootUpdatedAtTime(root, expirationTime) { + // Update the range of pending times + var firstPendingTime = root.firstPendingTime; + + if (expirationTime > firstPendingTime) { + root.firstPendingTime = expirationTime; + } // Update the range of suspended times. Treat everything lower priority or + // equal to this update as unsuspended. + + var firstSuspendedTime = root.firstSuspendedTime; + + if (firstSuspendedTime !== NoWork) { + if (expirationTime >= firstSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (expirationTime >= root.lastSuspendedTime) { + root.lastSuspendedTime = expirationTime + 1; + } // This is a pending level. Check if it's higher priority than the next + // known pending level. + + if (expirationTime > root.nextKnownPendingLevel) { + root.nextKnownPendingLevel = expirationTime; + } + } +} +function markRootFinishedAtTime( + root, + finishedExpirationTime, + remainingExpirationTime +) { + // Update the range of pending times + root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or + // equal to this update as unsuspended. + + if (finishedExpirationTime <= root.lastSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (finishedExpirationTime <= root.firstSuspendedTime) { + // Part of the suspended range is now unsuspended. Narrow the range to + // include everything between the unsuspended time (non-inclusive) and the + // last suspended time. + root.firstSuspendedTime = finishedExpirationTime - 1; + } + + if (finishedExpirationTime <= root.lastPingedTime) { + // Clear the pinged time + root.lastPingedTime = NoWork; + } + + if (finishedExpirationTime <= root.lastExpiredTime) { + // Clear the expired time + root.lastExpiredTime = NoWork; + } +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) { + root.lastExpiredTime = expirationTime; + } +} // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. @@ -22169,14 +23448,10 @@ function createFiberRoot(containerInfo, tag, hydrate) { var ReactFiberInstrumentation = { debugTool: null }; - var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. - -var didWarnAboutNestedUpdates = void 0; -var didWarnAboutFindNodeInStrictMode = void 0; +var didWarnAboutNestedUpdates; +var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; @@ -22193,6 +23468,7 @@ function getContextForSubtree(parentComponent) { if (fiber.tag === ClassComponent) { var Component = fiber.type; + if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } @@ -22201,166 +23477,72 @@ function getContextForSubtree(parentComponent) { return parentContext; } -function scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback -) { - { - if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - 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" - ); +function findHostInstance(component) { + var fiber = get(component); + + if (fiber === undefined) { + if (typeof component.render === "function") { + { + throw Error("Unable to find node on an unmounted component."); + } + } else { + { + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } } } - var update = createUpdate(expirationTime, suspenseConfig); - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = { element: element }; - - callback = callback === undefined ? null : callback; - if (callback !== null) { - !(typeof callback === "function") - ? warningWithoutStack$1( - false, - "render(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callback - ) - : void 0; - update.callback = callback; - } + var hostFiber = findCurrentHostFiber(fiber); - if (revertPassiveEffectsChange) { - flushPassiveEffects(); + if (hostFiber === null) { + return null; } - enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); - return expirationTime; + return hostFiber.stateNode; } -function updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback -) { - // TODO: If this is a nested container, this won't be the root. - var current$$1 = container.current; - +function findHostInstanceWithWarning(component, methodName) { { - if (ReactFiberInstrumentation_1.debugTool) { - if (current$$1.alternate === null) { - ReactFiberInstrumentation_1.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); - } - } - } - - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - return scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback - ); -} + var fiber = get(component); -function findHostInstance(component) { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { + if (fiber === undefined) { + if (typeof component.render === "function") { { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); + throw Error("Unable to find node on an unmounted component."); } - })(); - } else { - (function() { + } else { { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } - })(); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - } else { - (function() { - { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) - ); - } - })(); } } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + if (hostFiber.mode & StrictMode) { var componentName = getComponentName(fiber.type) || "Component"; + if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; + if (fiber.mode & StrictMode) { warningWithoutStack$1( false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which is inside StrictMode. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -22371,10 +23553,9 @@ function findHostInstanceWithWarning(component, methodName) { false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which renders StrictMode children. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -22383,18 +23564,20 @@ function findHostInstanceWithWarning(component, methodName) { } } } + return hostFiber.stateNode; } + return findHostInstance(component); } -function createContainer(containerInfo, tag, hydrate) { - return createFiberRoot(containerInfo, tag, hydrate); +function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) { + return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks); } - function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; var currentTime = requestCurrentTime(); + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -22402,30 +23585,83 @@ function updateContainer(element, container, parentComponent, callback) { warnIfNotScopedWithMatchingAct(current$$1); } } + var suspenseConfig = requestCurrentSuspenseConfig(); var expirationTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - return updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback - ); -} + { + if (ReactFiberInstrumentation_1.debugTool) { + if (current$$1.alternate === null) { + ReactFiberInstrumentation_1.debugTool.onMountContainer(container); + } else if (element === null) { + ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); + } else { + ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); + } + } + } + + var context = getContextForSubtree(parentComponent); + + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + + { + if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + 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" + ); + } + } + + var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property + // being called "element". + + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; + + if (callback !== null) { + !(typeof callback === "function") + ? warningWithoutStack$1( + false, + "render(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callback + ) + : void 0; + update.callback = callback; + } + + enqueueUpdate(current$$1, update); + scheduleWork(current$$1, expirationTime); + return expirationTime; +} function getPublicRootInstance(container) { var containerFiber = container.current; + if (!containerFiber.child) { return null; } + switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); + default: return containerFiber.child.stateNode; } @@ -22438,7 +23674,6 @@ var shouldSuspendImpl = function(fiber) { function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } - var overrideHookState = null; var overrideProps = null; var scheduleUpdate = null; @@ -22449,62 +23684,53 @@ var setSuspenseHandler = null; if (idx >= path.length) { return value; } + var key = path[idx]; - var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); - // $FlowFixMe number or string is fine here + var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); // $FlowFixMe number or string is fine here + updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); return updated; }; var copyWithSet = function(obj, path, value) { return copyWithSetImpl(obj, path, 0, value); - }; + }; // Support DevTools editable values for useState and useReducer. - // Support DevTools editable values for useState and useReducer. overrideHookState = function(fiber, id, path, value) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; + while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } - if (currentHook !== null) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } + if (currentHook !== null) { var newState = copyWithSet(currentHook.memoizedState, path, value); currentHook.memoizedState = newState; - currentHook.baseState = newState; - - // We aren't actually adding an update to the queue, + currentHook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); + fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); scheduleWork(fiber, Sync); } - }; + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } + scheduleWork(fiber, Sync); }; scheduleUpdate = function(fiber) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } scheduleWork(fiber, Sync); }; @@ -22516,7 +23742,6 @@ var setSuspenseHandler = null; function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals( Object.assign({}, devToolsConfig, { overrideHookState: overrideHookState, @@ -22526,9 +23751,11 @@ function injectIntoDevTools(devToolsConfig) { currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + return hostFiber.stateNode; }, findFiberByHostInstance: function(instance) { @@ -22536,9 +23763,9 @@ function injectIntoDevTools(devToolsConfig) { // Might not be implemented by the renderer. return null; } + return findFiberByHostInstance(instance); }, - // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh, scheduleRefresh: scheduleRefresh, @@ -22557,13 +23784,11 @@ function injectIntoDevTools(devToolsConfig) { function createPortal( children, - containerInfo, - // TODO: figure out the API for cross-renderer implementation. + containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation ) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, @@ -22574,404 +23799,31 @@ function createPortal( }; } -// TODO: this is special because it gets imported during build. - -var ReactVersion = "16.8.6"; - -// Modules provided by RN: -var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { - /** - * `NativeMethodsMixin` provides methods to access the underlying native - * component directly. This can be useful in cases when you want to focus - * a view or measure its on-screen dimensions, for example. - * - * The methods described here are available on most of the default components - * provided by React Native. Note, however, that they are *not* available on - * composite components that aren't directly backed by a native view. This will - * generally include most components that you define in your own app. For more - * information, see [Direct - * Manipulation](docs/direct-manipulation.html). - * - * Note the Flow $Exact<> syntax is required to support mixins. - * React createClass mixins can only be used with exact types. - */ - var NativeMethodsMixin = { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measure( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measureInWindow( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeNode`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * - * As always, to obtain a native node handle for a component, you can use - * `findNodeHandle(component)`. - */ - measureLayout: function( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: measureLayout on components using NativeMethodsMixin " + - "or ReactNative.NativeComponent is not currently supported in Fabric. " + - "measureLayout must be called on a native ref. Consider using forwardRef." - ); - return; - } else { - var relativeNode = void 0; - - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } - - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." - ); - - return; - } - - ReactNativePrivateInterface.UIManager.measureLayout( - findNodeHandle(this), - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - } - }, - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](docs/direct-manipulation.html)). - */ - setNativeProps: function(nativeProps) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than findNodeHandle() because - // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - return; - } - - var nativeTag = - maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; - var viewConfig = - maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - - { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = create(nativeProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( - nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } - }, - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus: function() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }, - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur: function() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - } - }; - - { - // hide this from Flow since we can't define these properties outside of - // true without actually implementing them (setting them to undefined - // isn't allowed by ReactClass) - var NativeMethodsMixin_DEV = NativeMethodsMixin; - (function() { - if ( - !( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps - ) - ) { - throw ReactError(Error("Do not override existing functions.")); - } - })(); - // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, - // Once these lifecycles have been remove from the reconciler. - NativeMethodsMixin_DEV.componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { - throwOnStylesProp(this, newProps); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( - newProps - ) { - throwOnStylesProp(this, newProps); - }; - - // React may warn about cWM/cWRP/cWU methods being deprecated. - // Add a flag to suppress these warnings for this special case. - // TODO (bvaughn) Remove this flag once the above methods have been removed. - NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; - NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; - } - - return NativeMethodsMixin; -}; - -function _classCallCheck$2(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn$1(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits$1(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); -} - -// Modules provided by RN: -var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { - /** - * Superclass that provides methods to access the underlying native component. - * This can be useful when you want to focus a view or measure its dimensions. - * - * Methods implemented by this class are available on most default components - * provided by React Native. However, they are *not* available on composite - * components that are not directly backed by a native view. For more - * information, see [Direct Manipulation](docs/direct-manipulation.html). - * - * @abstract - */ - var ReactNativeComponent = (function(_React$Component) { - _inherits$1(ReactNativeComponent, _React$Component); - - function ReactNativeComponent() { - _classCallCheck$2(this, ReactNativeComponent); - - return _possibleConstructorReturn$1( - this, - _React$Component.apply(this, arguments) - ); - } - - /** - * Removes focus. This is the opposite of `focus()`. - */ - - /** - * Due to bugs in Flow's handling of React.createClass, some fields already - * declared in the base class need to be redeclared below. - */ - ReactNativeComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - }; - - /** - * Requests focus. The exact behavior depends on the platform and view. - */ +// TODO: this is special because it gets imported during build. - ReactNativeComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }; +var ReactVersion = "16.10.2"; +var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { + /** + * `NativeMethodsMixin` provides methods to access the underlying native + * component directly. This can be useful in cases when you want to focus + * a view or measure its on-screen dimensions, for example. + * + * The methods described here are available on most of the default components + * provided by React Native. Note, however, that they are *not* available on + * composite components that aren't directly backed by a native view. This will + * generally include most components that you define in your own app. For more + * information, see [Direct + * Manipulation](docs/direct-manipulation.html). + * + * Note the Flow $Exact<> syntax is required to support mixins. + * React createClass mixins can only be used with exact types. + */ + var NativeMethodsMixin = { /** - * Measures the on-screen location and dimensions. If successful, the callback - * will be called asynchronously with the following arguments: + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: * * - x * - y @@ -22980,24 +23832,22 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { * - pageX * - pageY * - * These values are not available until after natives rendering completes. If - * you need the measurements as soon as possible, consider using the - * [`onLayout` prop](docs/view.html#onlayout) instead. + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. */ - - ReactNativeComponent.prototype.measure = function measure(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measure: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23016,37 +23866,34 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Measures the on-screen location and dimensions. Even if the React Native - * root view is embedded within another native view, this method will give you - * the absolute coordinates measured from the window. If successful, the - * callback will be called asynchronously with the following arguments: + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: * * - x * - y * - width * - height * - * These values are not available until after natives rendering completes. + * Note that these measurements are not available until after the rendering + * has been completed in native. */ - - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measureInWindow: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23065,32 +23912,32 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Similar to [`measure()`](#measure), but the resulting location will be - * relative to the supplied ancestor's location. + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeNode`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. * - * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + * As always, to obtain a native node handle for a component, you can use + * `findNodeHandle(component)`. */ - - ReactNativeComponent.prototype.measureLayout = function measureLayout( + measureLayout: function( relativeToNativeNode, onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + onFail + ) /* currently unused */ + { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23104,7 +23951,7 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { ); return; } else { - var relativeNode = void 0; + var relativeNode; if (typeof relativeToNativeNode === "number") { // Already a node handle @@ -23118,7 +23965,6 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { false, "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." ); - return; } @@ -23129,7 +23975,7 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); } - }; + }, /** * This function sends props straight to native. They will not participate in @@ -23137,27 +23983,22 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ - - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + setNativeProps: function(nativeProps) { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // Use findNodeHandle() rather than findNodeHandle() because // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -23175,11 +24016,14 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { var viewConfig = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - var updatePayload = create(nativeProps, viewConfig.validAttributes); + { + warnForStyleProps(nativeProps, viewConfig.validAttributes); + } - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( nativeTag, @@ -23187,12 +24031,322 @@ var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { updatePayload ); } + }, + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus: function() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }, + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur: function() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + } + }; + + { + // hide this from Flow since we can't define these properties outside of + // true without actually implementing them (setting them to undefined + // isn't allowed by ReactClass) + var NativeMethodsMixin_DEV = NativeMethodsMixin; + + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw Error("Do not override existing functions."); + } // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, + // Once these lifecycles have been remove from the reconciler. + + NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp(this, this.props); }; - return ReactNativeComponent; - })(React.Component); + NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp(this, newProps); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { + throwOnStylesProp(this, this.props); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( + newProps + ) { + throwOnStylesProp(this, newProps); + }; // React may warn about cWM/cWRP/cWU methods being deprecated. + // Add a flag to suppress these warnings for this special case. + // TODO (bvaughn) Remove this flag once the above methods have been removed. + + NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; + NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; + } + + return NativeMethodsMixin; +}; + +var ReactNativeComponent$1 = function(findNodeHandle, findHostInstance) { + /** + * Superclass that provides methods to access the underlying native component. + * This can be useful when you want to focus a view or measure its dimensions. + * + * Methods implemented by this class are available on most default components + * provided by React Native. However, they are *not* available on composite + * components that are not directly backed by a native view. For more + * information, see [Direct Manipulation](docs/direct-manipulation.html). + * + * @abstract + */ + var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); + + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } + + var _proto = ReactNativeComponent.prototype; + + /** + * Due to bugs in Flow's handling of React.createClass, some fields already + * declared in the base class need to be redeclared below. + */ + + /** + * Removes focus. This is the opposite of `focus()`. + */ + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + }; + /** + * Requests focus. The exact behavior depends on the platform and view. + */ + + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }; + /** + * Measures the on-screen location and dimensions. If successful, the callback + * will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * These values are not available until after natives rendering completes. If + * you need the measurements as soon as possible, consider using the + * [`onLayout` prop](docs/view.html#onlayout) instead. + */ + + _proto.measure = function measure(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Measures the on-screen location and dimensions. Even if the React Native + * root view is embedded within another native view, this method will give you + * the absolute coordinates measured from the window. If successful, the + * callback will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * + * These values are not available until after natives rendering completes. + */ + + _proto.measureInWindow = function measureInWindow(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Similar to [`measure()`](#measure), but the resulting location will be + * relative to the supplied ancestor's location. + * + * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + */ + + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: measureLayout on components using NativeMethodsMixin " + + "or ReactNative.NativeComponent is not currently supported in Fabric. " + + "measureLayout must be called on a native ref. Consider using forwardRef." + ); + return; + } else { + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } + + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } + + ReactNativePrivateInterface.UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } + }; + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](docs/direct-manipulation.html)). + */ + + _proto.setNativeProps = function setNativeProps(nativeProps) { + // Class components don't have viewConfig -> validateAttributes. + // Nor does it make sense to set native props on a non-native component. + // Instead, find the nearest host component and set props on it. + // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // We want the instance/wrapper (not the native tag). + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. - // eslint-disable-next-line no-unused-expressions + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + var nativeTag = + maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; + var viewConfig = + maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } + }; + + return ReactNativeComponent; + })(React.Component); // eslint-disable-next-line no-unused-expressions return ReactNativeComponent; }; @@ -23203,13 +24357,13 @@ function getInstanceFromTag(tag) { return instanceCache.get(tag) || null; } -// Module provided by RN: var emptyObject$2 = {}; + { Object.freeze(emptyObject$2); } -var getInspectorDataForViewTag = void 0; +var getInspectorDataForViewTag; { var traverseOwnerTreeUp = function(hierarchy, instance) { @@ -23233,30 +24387,36 @@ var getInspectorDataForViewTag = void 0; return instance; } } + return hierarchy[0]; }; var getHostProps = function(fiber) { var host = findCurrentHostFiber(fiber); + if (host) { return host.memoizedProps || emptyObject$2; } + return emptyObject$2; }; var getHostNode = function(fiber, findNodeHandle) { - var hostNode = void 0; - // look for children first for the hostNode + var hostNode; // look for children first for the hostNode // as composite fibers do not have a hostNode + while (fiber) { if (fiber.stateNode !== null && fiber.tag === HostComponent) { hostNode = findNodeHandle(fiber.stateNode); } + if (hostNode) { return hostNode; } + fiber = fiber.child; } + return null; }; @@ -23281,9 +24441,8 @@ var getInspectorDataForViewTag = void 0; }; getInspectorDataForViewTag = function(viewTag) { - var closestInstance = getInstanceFromTag(viewTag); + var closestInstance = getInstanceFromTag(viewTag); // Handle case where user clicks outside of ReactNative - // Handle case where user clicks outside of ReactNative if (!closestInstance) { return { hierarchy: [], @@ -23300,7 +24459,6 @@ var getInspectorDataForViewTag = void 0; var props = getHostProps(instance); var source = instance._debugSource; var selection = fiberHierarchy.indexOf(instance); - return { hierarchy: hierarchy, props: props, @@ -23312,12 +24470,12 @@ var getInspectorDataForViewTag = void 0; var _nativeFabricUIManage = nativeFabricUIManager; var fabricDispatchCommand = _nativeFabricUIManage.dispatchCommand; - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function findNodeHandle(componentOrHandle) { { var owner = ReactCurrentOwner.current; + if (owner !== null && owner.stateNode !== null) { !owner.stateNode._warnedAboutRefsInRender ? warningWithoutStack$1( @@ -23330,24 +24488,29 @@ function findNodeHandle(componentOrHandle) { getComponentName(owner.type) || "A component" ) : void 0; - owner.stateNode._warnedAboutRefsInRender = true; } } + if (componentOrHandle == null) { return null; } + if (typeof componentOrHandle === "number") { // Already a node handle return componentOrHandle; } + if (componentOrHandle._nativeTag) { return componentOrHandle._nativeTag; } + if (componentOrHandle.canonical && componentOrHandle.canonical._nativeTag) { return componentOrHandle.canonical._nativeTag; } - var hostInstance = void 0; + + var hostInstance; + { hostInstance = findHostInstanceWithWarning( componentOrHandle, @@ -23357,13 +24520,14 @@ function findNodeHandle(componentOrHandle) { if (hostInstance == null) { return hostInstance; - } - // TODO: the code is right but the types here are wrong. + } // TODO: the code is right but the types here are wrong. // https://github.com/facebook/react/pull/12863 + if (hostInstance.canonical) { // Fabric return hostInstance.canonical._nativeTag; } + return hostInstance._nativeTag; } @@ -23373,14 +24537,10 @@ setBatchingImplementation( flushDiscreteUpdates, batchedEventUpdates$1 ); - var roots = new Map(); - var ReactFabric = { NativeComponent: ReactNativeComponent$1(findNodeHandle, findHostInstance), - findNodeHandle: findNodeHandle, - dispatchCommand: function(handle, command, args) { var invalid = handle._nativeTag == null || handle._internalInstanceHandle == null; @@ -23408,15 +24568,16 @@ var ReactFabric = { if (!root) { // TODO (bvaughn): If we decide to keep the wrapper component, // We could create a wrapper for containerTag as well to reduce special casing. - root = createContainer(containerTag, LegacyRoot, false); + root = createContainer(containerTag, LegacyRoot, false, null); roots.set(containerTag, root); } - updateContainer(element, root, null, callback); + updateContainer(element, root, null, callback); return getPublicRootInstance(root); }, unmountComponentAtNode: function(containerTag) { var root = roots.get(containerTag); + if (root) { // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? updateContainer(null, root, null, function() { @@ -23427,16 +24588,13 @@ var ReactFabric = { createPortal: function(children, containerTag) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - return createPortal(children, containerTag, null, key); }, - __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // Used as a mixin in many createClass-based components NativeMethodsMixin: NativeMethodsMixin(findNodeHandle, findHostInstance) } }; - injectIntoDevTools({ findFiberByHostInstance: getInstanceFromInstance, getInspectorDataForViewTag: getInspectorDataForViewTag, @@ -23453,6 +24611,7 @@ var ReactFabric$3 = (ReactFabric$2 && ReactFabric) || ReactFabric$2; // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. + var fabric = ReactFabric$3.default || ReactFabric$3; module.exports = fabric; diff --git a/Libraries/Renderer/implementations/ReactFabric-prod.fb.js b/Libraries/Renderer/implementations/ReactFabric-prod.fb.js index 72f3fa07bc2171..7ccf2b0836cb51 100644 --- a/Libraries/Renderer/implementations/ReactFabric-prod.fb.js +++ b/Libraries/Renderer/implementations/ReactFabric-prod.fb.js @@ -14,10 +14,6 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} var eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { @@ -26,21 +22,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -50,12 +42,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -80,14 +70,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -95,12 +83,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -148,10 +134,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -169,7 +153,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -181,10 +165,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -220,10 +202,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -239,12 +219,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -285,14 +263,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -455,10 +431,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -494,8 +468,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -609,8 +582,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -710,7 +683,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -723,7 +696,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -732,9 +705,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -743,194 +716,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -938,7 +919,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -952,9 +933,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -987,10 +971,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1016,7 +998,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - if (!inst) throw ReactError(Error("All native instances should have a tag.")); + if (!inst) throw Error("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1055,6 +1037,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1063,6 +1046,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1103,27 +1106,31 @@ function getComponentName(type) { return null; } require("../shims/ReactFeatureFlags"); -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1143,7 +1150,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1179,22 +1186,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1446,10 +1449,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1480,51 +1481,26 @@ function batchedUpdates(fn, bookkeeping) { restoreStateOfTarget(fn[bookkeeping]); } } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() {}; - ReactNativeComponent.prototype.focus = function() {}; - ReactNativeComponent.prototype.measure = function() {}; - ReactNativeComponent.prototype.measureInWindow = function() {}; - ReactNativeComponent.prototype.measureLayout = function() {}; - ReactNativeComponent.prototype.setNativeProps = function() {}; + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() {}; + _proto.focus = function() {}; + _proto.measure = function() {}; + _proto.measureInWindow = function() {}; + _proto.measureLayout = function() {}; + _proto.setNativeProps = function() {}; return ReactNativeComponent; })(React.Component); new Map(); -new Map(); -new Set(); -new Map(); function dispatchEvent(target, topLevelType, nativeEvent) { batchedUpdates(function() { var events = nativeEvent.target; @@ -1535,7 +1511,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { topLevelType, target, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1546,10 +1523,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1560,10 +1535,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { }); } function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var _nativeFabricUIManage$1 = nativeFabricUIManager, @@ -1592,36 +1565,31 @@ var ReactFabricHostComponent = (function() { props, internalInstanceHandle ) { - if (!(this instanceof ReactFabricHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this.viewConfig = viewConfig; this.currentProps = props; this._internalInstanceHandle = internalInstanceHandle; } - ReactFabricHostComponent.prototype.blur = function() { + var _proto = ReactFabricHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { fabricMeasure( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { fabricMeasureInWindow( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { "number" !== typeof relativeToNativeNode && relativeToNativeNode instanceof ReactFabricHostComponent && fabricMeasureLayout( @@ -1631,7 +1599,7 @@ var ReactFabricHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactFabricHostComponent.prototype.setNativeProps = function() {}; + _proto.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1641,9 +1609,7 @@ function createTextInstance( internalInstanceHandle ) { if (!hostContext.isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") - ); + throw Error("Text strings must be rendered within a component."); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1756,10 +1722,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1771,15 +1735,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1798,10 +1760,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1851,7 +1811,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1867,7 +1827,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority$1(reactPriorityLevel, fn) { @@ -1889,8 +1849,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1919,25 +1882,13 @@ function flushSyncCallbackQueueImpl() { } } } -function inferPriorityFromExpirationTime(currentTime, expirationTime) { - if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; - currentTime = - 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); - return 0 >= currentTime - ? 99 - : 250 >= currentTime - ? 98 - : 5250 >= currentTime - ? 97 - : 95; -} function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1951,7 +1902,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1966,41 +1917,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2056,10 +1972,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2179,7 +2093,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2274,6 +2188,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2290,18 +2205,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2329,7 +2241,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2494,23 +2406,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2529,32 +2436,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2956,14 +2857,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3055,7 +2954,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3080,10 +2979,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3119,7 +3022,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3139,10 +3042,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3197,11 +3101,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3215,10 +3117,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3256,14 +3156,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3284,15 +3187,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3307,16 +3202,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3359,10 +3252,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3398,9 +3289,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3424,10 +3313,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3441,7 +3328,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3469,7 +3356,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3483,7 +3371,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3523,7 +3411,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3551,10 +3439,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3582,28 +3468,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3611,10 +3493,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3646,19 +3528,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3726,19 +3608,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3793,7 +3675,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3813,7 +3695,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4303,7 +4185,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4312,116 +4194,37 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; - if (0 === (workInProgress.mode & 2)) - for ( - nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); - renderExpirationTime = createFiberFromFragment( - nextProps, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime - ); - else { - if (null !== current$$1.memoizedState) - if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { nextDidTimeout = nextProps.fallback; nextProps = createFiberFromFragment(null, mode, 0, null); nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); if (0 === (workInProgress.mode & 2)) for ( - suspenseContext = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + nextProps.child = current$$1; + null !== current$$1; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( nextDidTimeout, mode, @@ -4430,28 +4233,118 @@ function updateSuspenseComponent( ); renderExpirationTime.return = workInProgress; nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - workInProgress.stateNode = current$$1.stateNode; + renderExpirationTime.return = workInProgress; + if ( + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) + for ( + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; + + ) + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4461,14 +4354,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4485,24 +4380,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4519,7 +4407,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4528,9 +4416,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4544,33 +4432,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4584,9 +4481,11 @@ function bailoutOnAlreadyFinishedWork( ) { null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4611,10 +4510,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function( parent, workInProgress, @@ -4826,8 +4725,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -4835,12 +4734,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -4848,13 +4745,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -4876,8 +4771,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -4885,7 +4780,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -4935,24 +4830,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -4960,12 +4888,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority$1( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5022,7 +4950,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); return; case 12: return; @@ -5035,20 +4963,18 @@ function commitWork(current$$1, finishedWork) { attachSuspenseRetryListeners(finishedWork); return; } - switch (finishedWork.tag) { + a: switch (finishedWork.tag) { case 1: case 5: case 6: case 20: - break; + break a; case 3: case 4: - break; + break a; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5058,7 +4984,7 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || @@ -5113,18 +5039,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5135,7 +5064,6 @@ var ceil = Math.ceil, rootDoesHavePassiveEffects = !1, rootWithPendingPassiveEffects = null, pendingPassiveEffectsRenderPriority = 90, - pendingPassiveEffectsExpirationTime = 0, rootsWithPendingDiscreteUpdates = null, nestedUpdateCount = 0, rootWithNestedUpdates = null, @@ -5179,10 +5107,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5193,30 +5121,19 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? performSyncWorkOnRoot(fiber) + : (ensureRootIsScheduled(fiber), + executionContext === NoContext && flushSyncCallbackQueue()) + : ensureRootIsScheduled(fiber); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5251,78 +5168,334 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var priorityLevel = requestCurrentTime(); + 1073741823 === expirationTime + ? (priorityLevel = 99) + : 1 === expirationTime || 2 === expirationTime + ? (priorityLevel = 95) + : ((priorityLevel = + 10 * (1073741821 - expirationTime) - + 10 * (1073741821 - priorityLevel)), + (priorityLevel = + 0 >= priorityLevel + ? 99 + : 250 >= priorityLevel + ? 98 + : 5250 >= priorityLevel + ? 97 + : 95)); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= priorityLevel + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && expirationTime === renderExpirationTime) || + prepareFreshStack(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if (workInProgressRootHasPendingPing) { + var lastPingedTime = root.lastPingedTime; + if (0 === lastPingedTime || lastPingedTime >= expirationTime) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + lastPingedTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== lastPingedTime && lastPingedTime !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + lastPingedTime = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (lastPingedTime = + now() - + (10 * (1073741821 - lastPingedTime) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + lastPingedTime <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + lastPingedTime)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && lastExpiredTime === renderExpirationTime) || + prepareFreshStack(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5368,345 +5541,188 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var next = beginWork$$1( unitOfWork.alternate, @@ -5723,9 +5739,9 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { a: { - var current = current$$1; + var instance = current$$1; current$$1 = workInProgress; var renderExpirationTime$jscomp$0 = renderExpirationTime, newProps = current$$1.pendingProps; @@ -5743,91 +5759,86 @@ function completeUnitOfWork(unitOfWork) { case 3: popHostContainer(current$$1); popTopLevelContextObject(current$$1); - renderExpirationTime$jscomp$0 = current$$1.stateNode; - renderExpirationTime$jscomp$0.pendingContext && - ((renderExpirationTime$jscomp$0.context = - renderExpirationTime$jscomp$0.pendingContext), - (renderExpirationTime$jscomp$0.pendingContext = null)); - if (null === current || null === current.child) - current$$1.effectTag &= -3; + instance = current$$1.stateNode; + instance.pendingContext && + ((instance.context = instance.pendingContext), + (instance.pendingContext = null)); updateHostContainer(current$$1); break; case 5: popHostContext(current$$1); - renderExpirationTime$jscomp$0 = requiredContext( - rootInstanceStackCursor.current - ); - var type = current$$1.type; - if (null !== current && null != current$$1.stateNode) + var rootContainerInstance = requiredContext( + rootInstanceStackCursor.current + ), + type = current$$1.type; + if (null !== instance && null != current$$1.stateNode) updateHostComponent$1( - current, + instance, current$$1, type, newProps, - renderExpirationTime$jscomp$0 + rootContainerInstance ), - current.ref !== current$$1.ref && (current$$1.effectTag |= 128); + instance.ref !== current$$1.ref && + (current$$1.effectTag |= 128); else if (newProps) { requiredContext(contextStackCursor$1.current); - current = newProps; - var rootContainerInstance = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = current$$1; - newProps = nextReactTag; + instance = current$$1; + renderExpirationTime$jscomp$0 = nextReactTag; nextReactTag += 2; type = getViewConfigForType(type); var updatePayload = diffProperties( null, emptyObject, - current, + newProps, type.validAttributes ); rootContainerInstance = createNode( - newProps, + renderExpirationTime$jscomp$0, type.uiViewClassName, rootContainerInstance, updatePayload, - renderExpirationTime$jscomp$0 + instance ); - current = new ReactFabricHostComponent( - newProps, + instance = new ReactFabricHostComponent( + renderExpirationTime$jscomp$0, type, - current, - renderExpirationTime$jscomp$0 + newProps, + instance ); - current = { node: rootContainerInstance, canonical: current }; - appendAllChildren(current, current$$1, !1, !1); - current$$1.stateNode = current; + instance = { + node: rootContainerInstance, + canonical: instance + }; + appendAllChildren(instance, current$$1, !1, !1); + current$$1.stateNode = instance; null !== current$$1.ref && (current$$1.effectTag |= 128); } else if (null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: - if (current && null != current$$1.stateNode) + if (instance && null != current$$1.stateNode) updateHostText$1( - current, + instance, current$$1, - current.memoizedProps, + instance.memoizedProps, newProps ); else { if ("string" !== typeof newProps && null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); - current = requiredContext(rootInstanceStackCursor.current); - renderExpirationTime$jscomp$0 = requiredContext( + instance = requiredContext(rootInstanceStackCursor.current); + rootContainerInstance = requiredContext( contextStackCursor$1.current ); current$$1.stateNode = createTextInstance( newProps, - current, - renderExpirationTime$jscomp$0, + instance, + rootContainerInstance, current$$1 ); } @@ -5841,41 +5852,52 @@ function completeUnitOfWork(unitOfWork) { current$$1.expirationTime = renderExpirationTime$jscomp$0; break a; } - renderExpirationTime$jscomp$0 = null !== newProps; - newProps = !1; - null !== current && - ((type = current.memoizedState), - (newProps = null !== type), - renderExpirationTime$jscomp$0 || - null === type || - ((type = current.child.sibling), - null !== type && - ((rootContainerInstance = current$$1.firstEffect), - null !== rootContainerInstance - ? ((current$$1.firstEffect = type), - (type.nextEffect = rootContainerInstance)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8)))); + newProps = null !== newProps; + rootContainerInstance = !1; + null !== instance && + ((renderExpirationTime$jscomp$0 = instance.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), + newProps || + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = instance.child.sibling), + null !== renderExpirationTime$jscomp$0 && + ((type = current$$1.firstEffect), + null !== type + ? ((current$$1.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = type)) + : ((current$$1.firstEffect = current$$1.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if ( - renderExpirationTime$jscomp$0 && - !newProps && + newProps && + !rootContainerInstance && 0 !== (current$$1.mode & 2) ) if ( - (null === current && + (null === instance && !0 !== current$$1.memoizedProps.unstable_avoidThisFallback) || - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; - renderExpirationTime$jscomp$0 && (current$$1.effectTag |= 4); + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime( + workInProgressRoot, + renderExpirationTime + ), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } + newProps && (current$$1.effectTag |= 4); break; case 7: break; @@ -5897,103 +5919,99 @@ function completeUnitOfWork(unitOfWork) { case 17: isContextProvider(current$$1.type) && popContext(current$$1); break; - case 18: - break; case 19: pop(suspenseStackCursor, current$$1); newProps = current$$1.memoizedState; if (null === newProps) break; - type = 0 !== (current$$1.effectTag & 64); - rootContainerInstance = newProps.rendering; - if (null === rootContainerInstance) - if (type) cutOffTailIfNeeded(newProps, !1); + rootContainerInstance = 0 !== (current$$1.effectTag & 64); + type = newProps.rendering; + if (null === type) + if (rootContainerInstance) cutOffTailIfNeeded(newProps, !1); else { if ( workInProgressRootExitStatus !== RootIncomplete || - (null !== current && 0 !== (current.effectTag & 64)) + (null !== instance && 0 !== (instance.effectTag & 64)) ) - for (current = current$$1.child; null !== current; ) { - rootContainerInstance = findFirstSuspended(current); - if (null !== rootContainerInstance) { + for (instance = current$$1.child; null !== instance; ) { + type = findFirstSuspended(instance); + if (null !== type) { current$$1.effectTag |= 64; cutOffTailIfNeeded(newProps, !1); - current = rootContainerInstance.updateQueue; - null !== current && - ((current$$1.updateQueue = current), + instance = type.updateQueue; + null !== instance && + ((current$$1.updateQueue = instance), (current$$1.effectTag |= 4)); - current$$1.firstEffect = current$$1.lastEffect = null; - current = renderExpirationTime$jscomp$0; - for ( - renderExpirationTime$jscomp$0 = current$$1.child; - null !== renderExpirationTime$jscomp$0; - - ) - (newProps = renderExpirationTime$jscomp$0), - (type = current), - (newProps.effectTag &= 2), - (newProps.nextEffect = null), - (newProps.firstEffect = null), - (newProps.lastEffect = null), - (rootContainerInstance = newProps.alternate), - null === rootContainerInstance - ? ((newProps.childExpirationTime = 0), - (newProps.expirationTime = type), - (newProps.child = null), - (newProps.memoizedProps = null), - (newProps.memoizedState = null), - (newProps.updateQueue = null), - (newProps.dependencies = null)) - : ((newProps.childExpirationTime = - rootContainerInstance.childExpirationTime), - (newProps.expirationTime = - rootContainerInstance.expirationTime), - (newProps.child = rootContainerInstance.child), - (newProps.memoizedProps = - rootContainerInstance.memoizedProps), - (newProps.memoizedState = - rootContainerInstance.memoizedState), - (newProps.updateQueue = - rootContainerInstance.updateQueue), - (type = rootContainerInstance.dependencies), - (newProps.dependencies = - null === type + null === newProps.lastEffect && + (current$$1.firstEffect = null); + current$$1.lastEffect = newProps.lastEffect; + instance = renderExpirationTime$jscomp$0; + for (newProps = current$$1.child; null !== newProps; ) + (rootContainerInstance = newProps), + (renderExpirationTime$jscomp$0 = instance), + (rootContainerInstance.effectTag &= 2), + (rootContainerInstance.nextEffect = null), + (rootContainerInstance.firstEffect = null), + (rootContainerInstance.lastEffect = null), + (type = rootContainerInstance.alternate), + null === type + ? ((rootContainerInstance.childExpirationTime = 0), + (rootContainerInstance.expirationTime = renderExpirationTime$jscomp$0), + (rootContainerInstance.child = null), + (rootContainerInstance.memoizedProps = null), + (rootContainerInstance.memoizedState = null), + (rootContainerInstance.updateQueue = null), + (rootContainerInstance.dependencies = null)) + : ((rootContainerInstance.childExpirationTime = + type.childExpirationTime), + (rootContainerInstance.expirationTime = + type.expirationTime), + (rootContainerInstance.child = type.child), + (rootContainerInstance.memoizedProps = + type.memoizedProps), + (rootContainerInstance.memoizedState = + type.memoizedState), + (rootContainerInstance.updateQueue = + type.updateQueue), + (renderExpirationTime$jscomp$0 = + type.dependencies), + (rootContainerInstance.dependencies = + null === renderExpirationTime$jscomp$0 ? null : { - expirationTime: type.expirationTime, - firstContext: type.firstContext, - responders: type.responders + expirationTime: + renderExpirationTime$jscomp$0.expirationTime, + firstContext: + renderExpirationTime$jscomp$0.firstContext, + responders: + renderExpirationTime$jscomp$0.responders })), - (renderExpirationTime$jscomp$0 = - renderExpirationTime$jscomp$0.sibling); + (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & - SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, current$$1 ); current$$1 = current$$1.child; break a; } - current = current.sibling; + instance = instance.sibling; } } else { - if (!type) + if (!rootContainerInstance) if ( - ((current = findFirstSuspended(rootContainerInstance)), - null !== current) + ((instance = findFirstSuspended(type)), null !== instance) ) { if ( ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), + (instance = instance.updateQueue), + null !== instance && + ((current$$1.updateQueue = instance), + (current$$1.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((current$$1.updateQueue = current), - (current$$1.effectTag |= 4)); current$$1 = current$$1.lastEffect = newProps.lastEffect; null !== current$$1 && (current$$1.nextEffect = null); break; @@ -6002,68 +6020,68 @@ function completeUnitOfWork(unitOfWork) { now() > newProps.tailExpiration && 1 < renderExpirationTime$jscomp$0 && ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), (current$$1.expirationTime = current$$1.childExpirationTime = renderExpirationTime$jscomp$0 - 1)); newProps.isBackwards - ? ((rootContainerInstance.sibling = current$$1.child), - (current$$1.child = rootContainerInstance)) - : ((current = newProps.last), - null !== current - ? (current.sibling = rootContainerInstance) - : (current$$1.child = rootContainerInstance), - (newProps.last = rootContainerInstance)); + ? ((type.sibling = current$$1.child), (current$$1.child = type)) + : ((instance = newProps.last), + null !== instance + ? (instance.sibling = type) + : (current$$1.child = type), + (newProps.last = type)); } if (null !== newProps.tail) { 0 === newProps.tailExpiration && (newProps.tailExpiration = now() + 500); - current = newProps.tail; - newProps.rendering = current; - newProps.tail = current.sibling; + instance = newProps.tail; + newProps.rendering = instance; + newProps.tail = instance.sibling; newProps.lastEffect = current$$1.lastEffect; - current.sibling = null; - renderExpirationTime$jscomp$0 = suspenseStackCursor.current; - renderExpirationTime$jscomp$0 = type - ? (renderExpirationTime$jscomp$0 & SubtreeSuspenseContextMask) | - ForceSuspenseFallback - : renderExpirationTime$jscomp$0 & SubtreeSuspenseContextMask; - push( - suspenseStackCursor, - renderExpirationTime$jscomp$0, - current$$1 - ); - current$$1 = current; + instance.sibling = null; + newProps = suspenseStackCursor.current; + newProps = rootContainerInstance + ? (newProps & 1) | 2 + : newProps & 1; + push(suspenseStackCursor, newProps, current$$1); + current$$1 = instance; break a; } break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + current$$1.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } current$$1 = null; } - current = workInProgress; - if (1 === renderExpirationTime || 1 !== current.childExpirationTime) { - renderExpirationTime$jscomp$0 = 0; - for (newProps = current.child; null !== newProps; ) - (type = newProps.expirationTime), - (rootContainerInstance = newProps.childExpirationTime), - type > renderExpirationTime$jscomp$0 && - (renderExpirationTime$jscomp$0 = type), - rootContainerInstance > renderExpirationTime$jscomp$0 && - (renderExpirationTime$jscomp$0 = rootContainerInstance), - (newProps = newProps.sibling); - current.childExpirationTime = renderExpirationTime$jscomp$0; + instance = workInProgress; + if (1 === renderExpirationTime || 1 !== instance.childExpirationTime) { + newProps = 0; + for ( + rootContainerInstance = instance.child; + null !== rootContainerInstance; + + ) + (renderExpirationTime$jscomp$0 = + rootContainerInstance.expirationTime), + (type = rootContainerInstance.childExpirationTime), + renderExpirationTime$jscomp$0 > newProps && + (newProps = renderExpirationTime$jscomp$0), + type > newProps && (newProps = type), + (rootContainerInstance = rootContainerInstance.sibling); + instance.childExpirationTime = newProps; } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6078,10 +6096,10 @@ function completeUnitOfWork(unitOfWork) { } else { current$$1 = unwindWork(workInProgress, renderExpirationTime); if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6091,131 +6109,88 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority$1(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$1, renderPriorityLevel$jscomp$1) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$1.finishedWork, + expirationTime = root$jscomp$1.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$1.finishedWork = null; + root$jscomp$1.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$1.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$1.callbackNode = null; + root$jscomp$1.callbackExpirationTime = 0; + root$jscomp$1.callbackPriority = 90; + root$jscomp$1.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$1.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$1.lastSuspendedTime + ? (root$jscomp$1.firstSuspendedTime = root$jscomp$1.lastSuspendedTime = root$jscomp$1.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$1.firstSuspendedTime && + (root$jscomp$1.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$1.lastPingedTime && + (root$jscomp$1.lastPingedTime = 0); + expirationTime <= root$jscomp$1.lastExpiredTime && + (root$jscomp$1.lastExpiredTime = 0); + root$jscomp$1 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$1, + renderPriorityLevel = renderPriorityLevel$jscomp$1; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: nextEffect.effectTag &= -3; break; @@ -6223,126 +6198,118 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - prevProps = nextEffect; + var current$$1$jscomp$0 = nextEffect; a: for ( - prevState = prevProps, - instance = current$$1, - snapshot = prevState; + var finishedRoot = root, + root$jscomp$0 = current$$1$jscomp$0, + renderPriorityLevel$jscomp$0 = renderPriorityLevel, + node = root$jscomp$0; ; ) if ( - (commitUnmount(snapshot, instance), null !== snapshot.child) + (commitUnmount( + finishedRoot, + node, + renderPriorityLevel$jscomp$0 + ), + null !== node.child) ) - (snapshot.child.return = snapshot), - (snapshot = snapshot.child); + (node.child.return = node), (node = node.child); else { - if (snapshot === prevState) break; - for (; null === snapshot.sibling; ) { - if ( - null === snapshot.return || - snapshot.return === prevState - ) + if (node === root$jscomp$0) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === root$jscomp$0) break a; - snapshot = snapshot.return; + node = node.return; } - snapshot.sibling.return = snapshot.return; - snapshot = snapshot.sibling; + node.sibling.return = node.return; + node = node.sibling; } - detachFiber(prevProps); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$1.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for (effectTag = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { var current$$1$jscomp$1 = nextEffect.alternate; - current$$1$jscomp$0 = nextEffect; + current$$1 = nextEffect; currentRef = effectTag; - switch (current$$1$jscomp$0.tag) { + switch (current$$1.tag) { case 0: case 11: case 15: - commitHookEffectList( - UnmountLayout, - MountLayout, - current$$1$jscomp$0 - ); + commitHookEffectList(16, 32, current$$1); break; case 1: - var instance$jscomp$0 = current$$1$jscomp$0.stateNode; - if (current$$1$jscomp$0.effectTag & 4) + var instance = current$$1.stateNode; + if (current$$1.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = - current$$1$jscomp$0.elementType === - current$$1$jscomp$0.type + var prevProps = + current$$1.elementType === current$$1.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( - current$$1$jscomp$0.type, + current$$1.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } - var updateQueue = current$$1$jscomp$0.updateQueue; + var updateQueue = current$$1.updateQueue; null !== updateQueue && commitUpdateQueue( - current$$1$jscomp$0, + current$$1, updateQueue, - instance$jscomp$0, + instance, currentRef ); break; case 3: - var _updateQueue = current$$1$jscomp$0.updateQueue; + var _updateQueue = current$$1.updateQueue; if (null !== _updateQueue) { - current$$1 = null; - if (null !== current$$1$jscomp$0.child) - switch (current$$1$jscomp$0.child.tag) { + root = null; + if (null !== current$$1.child) + switch (current$$1.child.tag) { case 5: - current$$1 = - current$$1$jscomp$0.child.stateNode.canonical; + root = current$$1.child.stateNode.canonical; break; case 1: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; } - commitUpdateQueue( - current$$1$jscomp$0, - _updateQueue, - current$$1, - currentRef - ); + commitUpdateQueue(current$$1, _updateQueue, root, currentRef); } break; case 5: - if ( - null === current$$1$jscomp$1 && - current$$1$jscomp$0.effectTag & 4 - ) - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) + if (null === current$$1$jscomp$1 && current$$1.effectTag & 4) + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6352,101 +6319,111 @@ function commitRootImpl(root, renderPriorityLevel) { case 12: break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + current$$1 = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1.canonical; + current$$1 = instance$jscomp$0.canonical; break; default: - instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(current$$1) + : (ref.current = current$$1); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); nextEffect = null; requestPaint(); - executionContext = childExpirationTimeBeforeCommit; - } else root.current = finishedWork; + executionContext = prevExecutionContext; + } else root$jscomp$1.current = finishedWork; if (rootDoesHavePassiveEffects) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (rootWithPendingPassiveEffects = root$jscomp$1), + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$1); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$1 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - 0 !== renderPriorityLevel - ? ((effectTag$jscomp$0 = requestCurrentTime()), - (effectTag$jscomp$0 = inferPriorityFromExpirationTime( - effectTag$jscomp$0, - renderPriorityLevel - )), - scheduleCallbackForRoot(root, effectTag$jscomp$0, renderPriorityLevel)) - : (legacyErrorBoundariesThatAlreadyFailed = null); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + (nextEffect = renderPriorityLevel$jscomp$1); + renderPriorityLevel$jscomp$1 = root$jscomp$1.firstPendingTime; + 0 === renderPriorityLevel$jscomp$1 && + (legacyErrorBoundariesThatAlreadyFailed = null); + 1073741823 === renderPriorityLevel$jscomp$1 + ? root$jscomp$1 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$1)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$1); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$1 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$1); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; - var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + var root = rootWithPendingPassiveEffects; rootWithPendingPassiveEffects = null; - pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority$1( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root) { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; for (root = root.current.firstEffect; null !== root; ) { @@ -6457,12 +6434,11 @@ function flushPassiveEffectsImpl(root) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === root) - throw ReactError(Error("Should be working on an effect.")); + if (null === root) throw Error("Should be working on an effect."); captureCommitPhaseError(root, error); } finishedWork = root.nextEffect; @@ -6478,7 +6454,7 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && ensureRootIsScheduled(rootFiber); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6500,7 +6476,7 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && ensureRootIsScheduled(fiber); break; } } @@ -6517,27 +6493,25 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + null !== boundaryFiber && ensureRootIsScheduled(boundaryFiber); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6583,7 +6557,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6595,7 +6569,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6627,6 +6601,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6711,7 +6686,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6754,12 +6731,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6799,10 +6774,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -6840,7 +6813,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -6930,7 +6904,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7119,10 +7093,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; var onCommitFiberRoot = null, @@ -7293,12 +7267,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7342,19 +7314,54 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; +} +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; } function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7364,23 +7371,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7398,10 +7402,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7420,14 +7422,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7440,31 +7441,6 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits$1(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; var fabricDispatchCommand = nativeFabricUIManager.dispatchCommand; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7498,33 +7474,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits$1(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7537,10 +7503,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7553,34 +7518,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7654,9 +7617,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7670,9 +7632,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7686,29 +7647,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7770,9 +7729,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromInstance, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/implementations/ReactFabric-prod.js b/Libraries/Renderer/implementations/ReactFabric-prod.js index d7d6730de83b95..fd321e770c51a4 100644 --- a/Libraries/Renderer/implementations/ReactFabric-prod.js +++ b/Libraries/Renderer/implementations/ReactFabric-prod.js @@ -15,10 +15,6 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} var eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { @@ -27,21 +23,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -51,12 +43,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -81,14 +71,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -96,12 +84,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -149,10 +135,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -170,7 +154,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -182,10 +166,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -221,10 +203,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -240,12 +220,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -286,14 +264,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -456,10 +432,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -495,8 +469,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -610,8 +583,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -711,7 +684,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -724,7 +697,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -733,9 +706,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -744,194 +717,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -939,7 +920,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -953,9 +934,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -988,10 +972,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1017,7 +999,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - if (!inst) throw ReactError(Error("All native instances should have a tag.")); + if (!inst) throw Error("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1056,6 +1038,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1064,6 +1047,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1103,27 +1106,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1143,7 +1150,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1179,22 +1186,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1446,10 +1449,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1480,51 +1481,26 @@ function batchedUpdates(fn, bookkeeping) { restoreStateOfTarget(fn[bookkeeping]); } } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() {}; - ReactNativeComponent.prototype.focus = function() {}; - ReactNativeComponent.prototype.measure = function() {}; - ReactNativeComponent.prototype.measureInWindow = function() {}; - ReactNativeComponent.prototype.measureLayout = function() {}; - ReactNativeComponent.prototype.setNativeProps = function() {}; + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() {}; + _proto.focus = function() {}; + _proto.measure = function() {}; + _proto.measureInWindow = function() {}; + _proto.measureLayout = function() {}; + _proto.setNativeProps = function() {}; return ReactNativeComponent; })(React.Component); new Map(); -new Map(); -new Set(); -new Map(); function dispatchEvent(target, topLevelType, nativeEvent) { batchedUpdates(function() { var events = nativeEvent.target; @@ -1535,7 +1511,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { topLevelType, target, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1546,10 +1523,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1560,10 +1535,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { }); } function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var _nativeFabricUIManage$1 = nativeFabricUIManager, @@ -1592,36 +1565,31 @@ var ReactFabricHostComponent = (function() { props, internalInstanceHandle ) { - if (!(this instanceof ReactFabricHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this.viewConfig = viewConfig; this.currentProps = props; this._internalInstanceHandle = internalInstanceHandle; } - ReactFabricHostComponent.prototype.blur = function() { + var _proto = ReactFabricHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { fabricMeasure( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { fabricMeasureInWindow( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { "number" !== typeof relativeToNativeNode && relativeToNativeNode instanceof ReactFabricHostComponent && fabricMeasureLayout( @@ -1631,7 +1599,7 @@ var ReactFabricHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactFabricHostComponent.prototype.setNativeProps = function() {}; + _proto.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1641,9 +1609,7 @@ function createTextInstance( internalInstanceHandle ) { if (!hostContext.isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") - ); + throw Error("Text strings must be rendered within a component."); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1756,10 +1722,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1771,15 +1735,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1798,10 +1760,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1851,7 +1811,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1867,7 +1827,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority$1(reactPriorityLevel, fn) { @@ -1889,8 +1849,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1919,25 +1882,13 @@ function flushSyncCallbackQueueImpl() { } } } -function inferPriorityFromExpirationTime(currentTime, expirationTime) { - if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; - currentTime = - 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); - return 0 >= currentTime - ? 99 - : 250 >= currentTime - ? 98 - : 5250 >= currentTime - ? 97 - : 95; -} function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1951,7 +1902,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1966,41 +1917,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2056,10 +1972,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2179,7 +2093,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2274,6 +2188,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2290,18 +2205,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2329,7 +2241,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2494,23 +2406,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2529,32 +2436,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2956,14 +2857,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3055,7 +2954,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3080,10 +2979,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3119,7 +3022,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3139,10 +3042,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3197,11 +3101,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3215,10 +3117,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3256,14 +3156,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3284,15 +3187,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3307,16 +3202,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3359,10 +3252,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3398,9 +3289,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3424,10 +3313,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3441,7 +3328,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3469,7 +3356,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3483,7 +3371,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3523,7 +3411,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3551,10 +3439,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3582,28 +3468,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3611,10 +3493,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3646,19 +3528,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3726,19 +3608,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3793,7 +3675,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3813,7 +3695,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4303,7 +4185,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4312,116 +4194,37 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; - if (0 === (workInProgress.mode & 2)) - for ( - nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); - renderExpirationTime = createFiberFromFragment( - nextProps, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime - ); - else { - if (null !== current$$1.memoizedState) - if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { nextDidTimeout = nextProps.fallback; nextProps = createFiberFromFragment(null, mode, 0, null); nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); if (0 === (workInProgress.mode & 2)) for ( - suspenseContext = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + nextProps.child = current$$1; + null !== current$$1; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( nextDidTimeout, mode, @@ -4430,28 +4233,118 @@ function updateSuspenseComponent( ); renderExpirationTime.return = workInProgress; nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - workInProgress.stateNode = current$$1.stateNode; + renderExpirationTime.return = workInProgress; + if ( + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) + for ( + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; + + ) + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4461,14 +4354,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4485,24 +4380,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4519,7 +4407,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4528,9 +4416,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4544,33 +4432,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4584,9 +4481,11 @@ function bailoutOnAlreadyFinishedWork( ) { null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4611,10 +4510,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function( parent, workInProgress, @@ -4826,8 +4725,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -4835,12 +4734,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -4848,13 +4745,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -4876,8 +4771,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -4885,7 +4780,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -4935,24 +4830,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -4960,12 +4888,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority$1( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5022,7 +4950,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); return; case 12: return; @@ -5035,20 +4963,18 @@ function commitWork(current$$1, finishedWork) { attachSuspenseRetryListeners(finishedWork); return; } - switch (finishedWork.tag) { + a: switch (finishedWork.tag) { case 1: case 5: case 6: case 20: - break; + break a; case 3: case 4: - break; + break a; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5058,7 +4984,7 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || @@ -5113,18 +5039,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5135,7 +5064,6 @@ var ceil = Math.ceil, rootDoesHavePassiveEffects = !1, rootWithPendingPassiveEffects = null, pendingPassiveEffectsRenderPriority = 90, - pendingPassiveEffectsExpirationTime = 0, rootsWithPendingDiscreteUpdates = null, nestedUpdateCount = 0, rootWithNestedUpdates = null, @@ -5179,10 +5107,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5193,30 +5121,19 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? performSyncWorkOnRoot(fiber) + : (ensureRootIsScheduled(fiber), + executionContext === NoContext && flushSyncCallbackQueue()) + : ensureRootIsScheduled(fiber); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5251,78 +5168,334 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var priorityLevel = requestCurrentTime(); + 1073741823 === expirationTime + ? (priorityLevel = 99) + : 1 === expirationTime || 2 === expirationTime + ? (priorityLevel = 95) + : ((priorityLevel = + 10 * (1073741821 - expirationTime) - + 10 * (1073741821 - priorityLevel)), + (priorityLevel = + 0 >= priorityLevel + ? 99 + : 250 >= priorityLevel + ? 98 + : 5250 >= priorityLevel + ? 97 + : 95)); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= priorityLevel + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && expirationTime === renderExpirationTime) || + prepareFreshStack(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if (workInProgressRootHasPendingPing) { + var lastPingedTime = root.lastPingedTime; + if (0 === lastPingedTime || lastPingedTime >= expirationTime) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + lastPingedTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== lastPingedTime && lastPingedTime !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + lastPingedTime = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (lastPingedTime = + now() - + (10 * (1073741821 - lastPingedTime) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + lastPingedTime <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + lastPingedTime)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && lastExpiredTime === renderExpirationTime) || + prepareFreshStack(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5368,345 +5541,188 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var next = beginWork$$1( unitOfWork.alternate, @@ -5723,9 +5739,9 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { a: { - var current = current$$1; + var instance = current$$1; current$$1 = workInProgress; var renderExpirationTime$jscomp$0 = renderExpirationTime, newProps = current$$1.pendingProps; @@ -5743,91 +5759,86 @@ function completeUnitOfWork(unitOfWork) { case 3: popHostContainer(current$$1); popTopLevelContextObject(current$$1); - renderExpirationTime$jscomp$0 = current$$1.stateNode; - renderExpirationTime$jscomp$0.pendingContext && - ((renderExpirationTime$jscomp$0.context = - renderExpirationTime$jscomp$0.pendingContext), - (renderExpirationTime$jscomp$0.pendingContext = null)); - if (null === current || null === current.child) - current$$1.effectTag &= -3; + instance = current$$1.stateNode; + instance.pendingContext && + ((instance.context = instance.pendingContext), + (instance.pendingContext = null)); updateHostContainer(current$$1); break; case 5: popHostContext(current$$1); - renderExpirationTime$jscomp$0 = requiredContext( - rootInstanceStackCursor.current - ); - var type = current$$1.type; - if (null !== current && null != current$$1.stateNode) + var rootContainerInstance = requiredContext( + rootInstanceStackCursor.current + ), + type = current$$1.type; + if (null !== instance && null != current$$1.stateNode) updateHostComponent$1( - current, + instance, current$$1, type, newProps, - renderExpirationTime$jscomp$0 + rootContainerInstance ), - current.ref !== current$$1.ref && (current$$1.effectTag |= 128); + instance.ref !== current$$1.ref && + (current$$1.effectTag |= 128); else if (newProps) { requiredContext(contextStackCursor$1.current); - current = newProps; - var rootContainerInstance = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = current$$1; - newProps = nextReactTag; + instance = current$$1; + renderExpirationTime$jscomp$0 = nextReactTag; nextReactTag += 2; type = getViewConfigForType(type); var updatePayload = diffProperties( null, emptyObject, - current, + newProps, type.validAttributes ); rootContainerInstance = createNode( - newProps, + renderExpirationTime$jscomp$0, type.uiViewClassName, rootContainerInstance, updatePayload, - renderExpirationTime$jscomp$0 + instance ); - current = new ReactFabricHostComponent( - newProps, + instance = new ReactFabricHostComponent( + renderExpirationTime$jscomp$0, type, - current, - renderExpirationTime$jscomp$0 + newProps, + instance ); - current = { node: rootContainerInstance, canonical: current }; - appendAllChildren(current, current$$1, !1, !1); - current$$1.stateNode = current; + instance = { + node: rootContainerInstance, + canonical: instance + }; + appendAllChildren(instance, current$$1, !1, !1); + current$$1.stateNode = instance; null !== current$$1.ref && (current$$1.effectTag |= 128); } else if (null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: - if (current && null != current$$1.stateNode) + if (instance && null != current$$1.stateNode) updateHostText$1( - current, + instance, current$$1, - current.memoizedProps, + instance.memoizedProps, newProps ); else { if ("string" !== typeof newProps && null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); - current = requiredContext(rootInstanceStackCursor.current); - renderExpirationTime$jscomp$0 = requiredContext( + instance = requiredContext(rootInstanceStackCursor.current); + rootContainerInstance = requiredContext( contextStackCursor$1.current ); current$$1.stateNode = createTextInstance( newProps, - current, - renderExpirationTime$jscomp$0, + instance, + rootContainerInstance, current$$1 ); } @@ -5841,41 +5852,52 @@ function completeUnitOfWork(unitOfWork) { current$$1.expirationTime = renderExpirationTime$jscomp$0; break a; } - renderExpirationTime$jscomp$0 = null !== newProps; - newProps = !1; - null !== current && - ((type = current.memoizedState), - (newProps = null !== type), - renderExpirationTime$jscomp$0 || - null === type || - ((type = current.child.sibling), - null !== type && - ((rootContainerInstance = current$$1.firstEffect), - null !== rootContainerInstance - ? ((current$$1.firstEffect = type), - (type.nextEffect = rootContainerInstance)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8)))); + newProps = null !== newProps; + rootContainerInstance = !1; + null !== instance && + ((renderExpirationTime$jscomp$0 = instance.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), + newProps || + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = instance.child.sibling), + null !== renderExpirationTime$jscomp$0 && + ((type = current$$1.firstEffect), + null !== type + ? ((current$$1.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = type)) + : ((current$$1.firstEffect = current$$1.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if ( - renderExpirationTime$jscomp$0 && - !newProps && + newProps && + !rootContainerInstance && 0 !== (current$$1.mode & 2) ) if ( - (null === current && + (null === instance && !0 !== current$$1.memoizedProps.unstable_avoidThisFallback) || - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; - renderExpirationTime$jscomp$0 && (current$$1.effectTag |= 4); + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime( + workInProgressRoot, + renderExpirationTime + ), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } + newProps && (current$$1.effectTag |= 4); break; case 7: break; @@ -5897,103 +5919,99 @@ function completeUnitOfWork(unitOfWork) { case 17: isContextProvider(current$$1.type) && popContext(current$$1); break; - case 18: - break; case 19: pop(suspenseStackCursor, current$$1); newProps = current$$1.memoizedState; if (null === newProps) break; - type = 0 !== (current$$1.effectTag & 64); - rootContainerInstance = newProps.rendering; - if (null === rootContainerInstance) - if (type) cutOffTailIfNeeded(newProps, !1); + rootContainerInstance = 0 !== (current$$1.effectTag & 64); + type = newProps.rendering; + if (null === type) + if (rootContainerInstance) cutOffTailIfNeeded(newProps, !1); else { if ( workInProgressRootExitStatus !== RootIncomplete || - (null !== current && 0 !== (current.effectTag & 64)) + (null !== instance && 0 !== (instance.effectTag & 64)) ) - for (current = current$$1.child; null !== current; ) { - rootContainerInstance = findFirstSuspended(current); - if (null !== rootContainerInstance) { + for (instance = current$$1.child; null !== instance; ) { + type = findFirstSuspended(instance); + if (null !== type) { current$$1.effectTag |= 64; cutOffTailIfNeeded(newProps, !1); - current = rootContainerInstance.updateQueue; - null !== current && - ((current$$1.updateQueue = current), + instance = type.updateQueue; + null !== instance && + ((current$$1.updateQueue = instance), (current$$1.effectTag |= 4)); - current$$1.firstEffect = current$$1.lastEffect = null; - current = renderExpirationTime$jscomp$0; - for ( - renderExpirationTime$jscomp$0 = current$$1.child; - null !== renderExpirationTime$jscomp$0; - - ) - (newProps = renderExpirationTime$jscomp$0), - (type = current), - (newProps.effectTag &= 2), - (newProps.nextEffect = null), - (newProps.firstEffect = null), - (newProps.lastEffect = null), - (rootContainerInstance = newProps.alternate), - null === rootContainerInstance - ? ((newProps.childExpirationTime = 0), - (newProps.expirationTime = type), - (newProps.child = null), - (newProps.memoizedProps = null), - (newProps.memoizedState = null), - (newProps.updateQueue = null), - (newProps.dependencies = null)) - : ((newProps.childExpirationTime = - rootContainerInstance.childExpirationTime), - (newProps.expirationTime = - rootContainerInstance.expirationTime), - (newProps.child = rootContainerInstance.child), - (newProps.memoizedProps = - rootContainerInstance.memoizedProps), - (newProps.memoizedState = - rootContainerInstance.memoizedState), - (newProps.updateQueue = - rootContainerInstance.updateQueue), - (type = rootContainerInstance.dependencies), - (newProps.dependencies = - null === type + null === newProps.lastEffect && + (current$$1.firstEffect = null); + current$$1.lastEffect = newProps.lastEffect; + instance = renderExpirationTime$jscomp$0; + for (newProps = current$$1.child; null !== newProps; ) + (rootContainerInstance = newProps), + (renderExpirationTime$jscomp$0 = instance), + (rootContainerInstance.effectTag &= 2), + (rootContainerInstance.nextEffect = null), + (rootContainerInstance.firstEffect = null), + (rootContainerInstance.lastEffect = null), + (type = rootContainerInstance.alternate), + null === type + ? ((rootContainerInstance.childExpirationTime = 0), + (rootContainerInstance.expirationTime = renderExpirationTime$jscomp$0), + (rootContainerInstance.child = null), + (rootContainerInstance.memoizedProps = null), + (rootContainerInstance.memoizedState = null), + (rootContainerInstance.updateQueue = null), + (rootContainerInstance.dependencies = null)) + : ((rootContainerInstance.childExpirationTime = + type.childExpirationTime), + (rootContainerInstance.expirationTime = + type.expirationTime), + (rootContainerInstance.child = type.child), + (rootContainerInstance.memoizedProps = + type.memoizedProps), + (rootContainerInstance.memoizedState = + type.memoizedState), + (rootContainerInstance.updateQueue = + type.updateQueue), + (renderExpirationTime$jscomp$0 = + type.dependencies), + (rootContainerInstance.dependencies = + null === renderExpirationTime$jscomp$0 ? null : { - expirationTime: type.expirationTime, - firstContext: type.firstContext, - responders: type.responders + expirationTime: + renderExpirationTime$jscomp$0.expirationTime, + firstContext: + renderExpirationTime$jscomp$0.firstContext, + responders: + renderExpirationTime$jscomp$0.responders })), - (renderExpirationTime$jscomp$0 = - renderExpirationTime$jscomp$0.sibling); + (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & - SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, current$$1 ); current$$1 = current$$1.child; break a; } - current = current.sibling; + instance = instance.sibling; } } else { - if (!type) + if (!rootContainerInstance) if ( - ((current = findFirstSuspended(rootContainerInstance)), - null !== current) + ((instance = findFirstSuspended(type)), null !== instance) ) { if ( ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), + (instance = instance.updateQueue), + null !== instance && + ((current$$1.updateQueue = instance), + (current$$1.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((current$$1.updateQueue = current), - (current$$1.effectTag |= 4)); current$$1 = current$$1.lastEffect = newProps.lastEffect; null !== current$$1 && (current$$1.nextEffect = null); break; @@ -6002,68 +6020,68 @@ function completeUnitOfWork(unitOfWork) { now() > newProps.tailExpiration && 1 < renderExpirationTime$jscomp$0 && ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), (current$$1.expirationTime = current$$1.childExpirationTime = renderExpirationTime$jscomp$0 - 1)); newProps.isBackwards - ? ((rootContainerInstance.sibling = current$$1.child), - (current$$1.child = rootContainerInstance)) - : ((current = newProps.last), - null !== current - ? (current.sibling = rootContainerInstance) - : (current$$1.child = rootContainerInstance), - (newProps.last = rootContainerInstance)); + ? ((type.sibling = current$$1.child), (current$$1.child = type)) + : ((instance = newProps.last), + null !== instance + ? (instance.sibling = type) + : (current$$1.child = type), + (newProps.last = type)); } if (null !== newProps.tail) { 0 === newProps.tailExpiration && (newProps.tailExpiration = now() + 500); - current = newProps.tail; - newProps.rendering = current; - newProps.tail = current.sibling; + instance = newProps.tail; + newProps.rendering = instance; + newProps.tail = instance.sibling; newProps.lastEffect = current$$1.lastEffect; - current.sibling = null; - renderExpirationTime$jscomp$0 = suspenseStackCursor.current; - renderExpirationTime$jscomp$0 = type - ? (renderExpirationTime$jscomp$0 & SubtreeSuspenseContextMask) | - ForceSuspenseFallback - : renderExpirationTime$jscomp$0 & SubtreeSuspenseContextMask; - push( - suspenseStackCursor, - renderExpirationTime$jscomp$0, - current$$1 - ); - current$$1 = current; + instance.sibling = null; + newProps = suspenseStackCursor.current; + newProps = rootContainerInstance + ? (newProps & 1) | 2 + : newProps & 1; + push(suspenseStackCursor, newProps, current$$1); + current$$1 = instance; break a; } break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + current$$1.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } current$$1 = null; } - current = workInProgress; - if (1 === renderExpirationTime || 1 !== current.childExpirationTime) { - renderExpirationTime$jscomp$0 = 0; - for (newProps = current.child; null !== newProps; ) - (type = newProps.expirationTime), - (rootContainerInstance = newProps.childExpirationTime), - type > renderExpirationTime$jscomp$0 && - (renderExpirationTime$jscomp$0 = type), - rootContainerInstance > renderExpirationTime$jscomp$0 && - (renderExpirationTime$jscomp$0 = rootContainerInstance), - (newProps = newProps.sibling); - current.childExpirationTime = renderExpirationTime$jscomp$0; + instance = workInProgress; + if (1 === renderExpirationTime || 1 !== instance.childExpirationTime) { + newProps = 0; + for ( + rootContainerInstance = instance.child; + null !== rootContainerInstance; + + ) + (renderExpirationTime$jscomp$0 = + rootContainerInstance.expirationTime), + (type = rootContainerInstance.childExpirationTime), + renderExpirationTime$jscomp$0 > newProps && + (newProps = renderExpirationTime$jscomp$0), + type > newProps && (newProps = type), + (rootContainerInstance = rootContainerInstance.sibling); + instance.childExpirationTime = newProps; } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6078,10 +6096,10 @@ function completeUnitOfWork(unitOfWork) { } else { current$$1 = unwindWork(workInProgress, renderExpirationTime); if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6091,131 +6109,88 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority$1(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$1, renderPriorityLevel$jscomp$1) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$1.finishedWork, + expirationTime = root$jscomp$1.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$1.finishedWork = null; + root$jscomp$1.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$1.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$1.callbackNode = null; + root$jscomp$1.callbackExpirationTime = 0; + root$jscomp$1.callbackPriority = 90; + root$jscomp$1.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$1.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$1.lastSuspendedTime + ? (root$jscomp$1.firstSuspendedTime = root$jscomp$1.lastSuspendedTime = root$jscomp$1.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$1.firstSuspendedTime && + (root$jscomp$1.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$1.lastPingedTime && + (root$jscomp$1.lastPingedTime = 0); + expirationTime <= root$jscomp$1.lastExpiredTime && + (root$jscomp$1.lastExpiredTime = 0); + root$jscomp$1 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$1, + renderPriorityLevel = renderPriorityLevel$jscomp$1; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: nextEffect.effectTag &= -3; break; @@ -6223,126 +6198,118 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - prevProps = nextEffect; + var current$$1$jscomp$0 = nextEffect; a: for ( - prevState = prevProps, - instance = current$$1, - snapshot = prevState; + var finishedRoot = root, + root$jscomp$0 = current$$1$jscomp$0, + renderPriorityLevel$jscomp$0 = renderPriorityLevel, + node = root$jscomp$0; ; ) if ( - (commitUnmount(snapshot, instance), null !== snapshot.child) + (commitUnmount( + finishedRoot, + node, + renderPriorityLevel$jscomp$0 + ), + null !== node.child) ) - (snapshot.child.return = snapshot), - (snapshot = snapshot.child); + (node.child.return = node), (node = node.child); else { - if (snapshot === prevState) break; - for (; null === snapshot.sibling; ) { - if ( - null === snapshot.return || - snapshot.return === prevState - ) + if (node === root$jscomp$0) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === root$jscomp$0) break a; - snapshot = snapshot.return; + node = node.return; } - snapshot.sibling.return = snapshot.return; - snapshot = snapshot.sibling; + node.sibling.return = node.return; + node = node.sibling; } - detachFiber(prevProps); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$1.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for (effectTag = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { var current$$1$jscomp$1 = nextEffect.alternate; - current$$1$jscomp$0 = nextEffect; + current$$1 = nextEffect; currentRef = effectTag; - switch (current$$1$jscomp$0.tag) { + switch (current$$1.tag) { case 0: case 11: case 15: - commitHookEffectList( - UnmountLayout, - MountLayout, - current$$1$jscomp$0 - ); + commitHookEffectList(16, 32, current$$1); break; case 1: - var instance$jscomp$0 = current$$1$jscomp$0.stateNode; - if (current$$1$jscomp$0.effectTag & 4) + var instance = current$$1.stateNode; + if (current$$1.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = - current$$1$jscomp$0.elementType === - current$$1$jscomp$0.type + var prevProps = + current$$1.elementType === current$$1.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( - current$$1$jscomp$0.type, + current$$1.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } - var updateQueue = current$$1$jscomp$0.updateQueue; + var updateQueue = current$$1.updateQueue; null !== updateQueue && commitUpdateQueue( - current$$1$jscomp$0, + current$$1, updateQueue, - instance$jscomp$0, + instance, currentRef ); break; case 3: - var _updateQueue = current$$1$jscomp$0.updateQueue; + var _updateQueue = current$$1.updateQueue; if (null !== _updateQueue) { - current$$1 = null; - if (null !== current$$1$jscomp$0.child) - switch (current$$1$jscomp$0.child.tag) { + root = null; + if (null !== current$$1.child) + switch (current$$1.child.tag) { case 5: - current$$1 = - current$$1$jscomp$0.child.stateNode.canonical; + root = current$$1.child.stateNode.canonical; break; case 1: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; } - commitUpdateQueue( - current$$1$jscomp$0, - _updateQueue, - current$$1, - currentRef - ); + commitUpdateQueue(current$$1, _updateQueue, root, currentRef); } break; case 5: - if ( - null === current$$1$jscomp$1 && - current$$1$jscomp$0.effectTag & 4 - ) - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) + if (null === current$$1$jscomp$1 && current$$1.effectTag & 4) + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6352,101 +6319,111 @@ function commitRootImpl(root, renderPriorityLevel) { case 12: break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + current$$1 = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1.canonical; + current$$1 = instance$jscomp$0.canonical; break; default: - instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(current$$1) + : (ref.current = current$$1); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); nextEffect = null; requestPaint(); - executionContext = childExpirationTimeBeforeCommit; - } else root.current = finishedWork; + executionContext = prevExecutionContext; + } else root$jscomp$1.current = finishedWork; if (rootDoesHavePassiveEffects) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (rootWithPendingPassiveEffects = root$jscomp$1), + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$1); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$1 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - 0 !== renderPriorityLevel - ? ((effectTag$jscomp$0 = requestCurrentTime()), - (effectTag$jscomp$0 = inferPriorityFromExpirationTime( - effectTag$jscomp$0, - renderPriorityLevel - )), - scheduleCallbackForRoot(root, effectTag$jscomp$0, renderPriorityLevel)) - : (legacyErrorBoundariesThatAlreadyFailed = null); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + (nextEffect = renderPriorityLevel$jscomp$1); + renderPriorityLevel$jscomp$1 = root$jscomp$1.firstPendingTime; + 0 === renderPriorityLevel$jscomp$1 && + (legacyErrorBoundariesThatAlreadyFailed = null); + 1073741823 === renderPriorityLevel$jscomp$1 + ? root$jscomp$1 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$1)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$1); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$1 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$1); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; - var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + var root = rootWithPendingPassiveEffects; rootWithPendingPassiveEffects = null; - pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority$1( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root) { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; for (root = root.current.firstEffect; null !== root; ) { @@ -6457,12 +6434,11 @@ function flushPassiveEffectsImpl(root) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === root) - throw ReactError(Error("Should be working on an effect.")); + if (null === root) throw Error("Should be working on an effect."); captureCommitPhaseError(root, error); } finishedWork = root.nextEffect; @@ -6478,7 +6454,7 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && ensureRootIsScheduled(rootFiber); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6500,7 +6476,7 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && ensureRootIsScheduled(fiber); break; } } @@ -6517,27 +6493,25 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + null !== boundaryFiber && ensureRootIsScheduled(boundaryFiber); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6583,7 +6557,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6595,7 +6569,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6627,6 +6601,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6711,7 +6686,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6754,12 +6731,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6799,10 +6774,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -6840,7 +6813,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -6930,7 +6904,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7119,10 +7093,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; var onCommitFiberRoot = null, @@ -7293,12 +7267,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7342,19 +7314,54 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; +} +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; } function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7364,23 +7371,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7398,10 +7402,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7420,14 +7422,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7440,31 +7441,6 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits$1(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; var fabricDispatchCommand = nativeFabricUIManager.dispatchCommand; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7498,33 +7474,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits$1(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7537,10 +7503,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7553,34 +7518,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7654,9 +7617,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7670,9 +7632,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7686,29 +7647,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7770,9 +7729,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromInstance, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/implementations/ReactFabric-profiling.fb.js b/Libraries/Renderer/implementations/ReactFabric-profiling.fb.js index df8e8a1552e7c8..12b99f243fb52a 100644 --- a/Libraries/Renderer/implementations/ReactFabric-profiling.fb.js +++ b/Libraries/Renderer/implementations/ReactFabric-profiling.fb.js @@ -14,12 +14,8 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"), - tracing = require("scheduler/tracing"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} -var eventPluginOrder = null, + tracing = require("scheduler/tracing"), + eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { if (eventPluginOrder) @@ -27,21 +23,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -51,12 +43,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -81,14 +71,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -96,12 +84,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -149,10 +135,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -170,7 +154,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -182,10 +166,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -221,10 +203,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -240,12 +220,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -286,14 +264,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -456,10 +432,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -495,8 +469,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -610,8 +583,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -711,7 +684,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -724,7 +697,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -733,9 +706,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -744,194 +717,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -939,7 +920,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -953,9 +934,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -988,10 +972,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1017,7 +999,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - if (!inst) throw ReactError(Error("All native instances should have a tag.")); + if (!inst) throw Error("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1056,6 +1038,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1064,6 +1047,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1104,27 +1107,31 @@ function getComponentName(type) { return null; } require("../shims/ReactFeatureFlags"); -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1144,7 +1151,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1180,22 +1187,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1447,10 +1450,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1481,51 +1482,26 @@ function batchedUpdates(fn, bookkeeping) { restoreStateOfTarget(fn[bookkeeping]); } } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() {}; - ReactNativeComponent.prototype.focus = function() {}; - ReactNativeComponent.prototype.measure = function() {}; - ReactNativeComponent.prototype.measureInWindow = function() {}; - ReactNativeComponent.prototype.measureLayout = function() {}; - ReactNativeComponent.prototype.setNativeProps = function() {}; + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() {}; + _proto.focus = function() {}; + _proto.measure = function() {}; + _proto.measureInWindow = function() {}; + _proto.measureLayout = function() {}; + _proto.setNativeProps = function() {}; return ReactNativeComponent; })(React.Component); new Map(); -new Map(); -new Set(); -new Map(); function dispatchEvent(target, topLevelType, nativeEvent) { batchedUpdates(function() { var events = nativeEvent.target; @@ -1536,7 +1512,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { topLevelType, target, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1547,10 +1524,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1561,10 +1536,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { }); } function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var _nativeFabricUIManage$1 = nativeFabricUIManager, @@ -1593,36 +1566,31 @@ var ReactFabricHostComponent = (function() { props, internalInstanceHandle ) { - if (!(this instanceof ReactFabricHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this.viewConfig = viewConfig; this.currentProps = props; this._internalInstanceHandle = internalInstanceHandle; } - ReactFabricHostComponent.prototype.blur = function() { + var _proto = ReactFabricHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { fabricMeasure( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { fabricMeasureInWindow( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { "number" !== typeof relativeToNativeNode && relativeToNativeNode instanceof ReactFabricHostComponent && fabricMeasureLayout( @@ -1632,7 +1600,7 @@ var ReactFabricHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactFabricHostComponent.prototype.setNativeProps = function() {}; + _proto.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1642,9 +1610,7 @@ function createTextInstance( internalInstanceHandle ) { if (!hostContext.isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") - ); + throw Error("Text strings must be rendered within a component."); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1757,10 +1723,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1772,15 +1736,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1799,10 +1761,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1830,10 +1790,8 @@ if ( null == tracing.__interactionsRef || null == tracing.__interactionsRef.current ) - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) + 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" ); var fakeCallbackNode = {}, requestPaint = @@ -1861,7 +1819,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1877,7 +1835,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority$1(reactPriorityLevel, fn) { @@ -1899,8 +1857,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1931,7 +1892,7 @@ function flushSyncCallbackQueueImpl() { } function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; + if (1 === expirationTime || 2 === expirationTime) return 95; currentTime = 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); return 0 >= currentTime @@ -1945,9 +1906,10 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1961,7 +1923,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1976,41 +1938,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2066,10 +1993,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2189,7 +2114,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2284,6 +2209,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2300,18 +2226,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2339,7 +2262,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2504,23 +2427,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2539,32 +2457,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2966,14 +2878,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3065,7 +2975,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3090,10 +3000,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3129,7 +3043,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3149,10 +3063,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3207,11 +3122,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3225,10 +3138,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3266,14 +3177,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3294,15 +3208,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3317,16 +3223,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3369,10 +3273,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3408,9 +3310,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3434,10 +3334,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3451,7 +3349,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3479,7 +3377,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3493,7 +3392,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3533,7 +3432,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3561,10 +3460,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3592,28 +3489,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3621,10 +3514,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3656,19 +3549,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3736,19 +3629,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3814,7 +3707,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3834,7 +3727,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4328,7 +4221,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4337,164 +4230,171 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; if (0 === (workInProgress.mode & 2)) for ( - nextDidTimeout = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; + nextProps.child = current$$1; + null !== current$$1; ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( - nextProps, + nextDidTimeout, mode, renderExpirationTime, null ); renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime + nextProps.sibling = renderExpirationTime; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - else { - if (null !== current$$1.memoizedState) + renderExpirationTime.return = workInProgress; if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - if (workInProgress.mode & 8) { - nextDidTimeout = 0; - for ( - suspenseContext = renderExpirationTime.child; - null !== suspenseContext; - - ) - (nextDidTimeout += suspenseContext.treeBaseDuration), - (suspenseContext = suspenseContext.sibling); - renderExpirationTime.treeBaseDuration = nextDidTimeout; - } - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { - nextDidTimeout = nextProps.fallback; - nextProps = createFiberFromFragment(null, mode, 0, null); - nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); - if (0 === (workInProgress.mode & 2)) + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) for ( - suspenseContext = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); if (workInProgress.mode & 8) { - suspenseContext = 0; - for (JSCompiler_temp = nextProps.child; null !== JSCompiler_temp; ) - (suspenseContext += JSCompiler_temp.treeBaseDuration), - (JSCompiler_temp = JSCompiler_temp.sibling); - nextProps.treeBaseDuration = suspenseContext; + nextDidTimeout = 0; + for (current$$1 = renderExpirationTime.child; null !== current$$1; ) + (nextDidTimeout += current$$1.treeBaseDuration), + (current$$1 = current$$1.sibling); + renderExpirationTime.treeBaseDuration = nextDidTimeout; } - renderExpirationTime = createFiberFromFragment( - nextDidTimeout, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime - ); - workInProgress.stateNode = current$$1.stateNode; + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + if (workInProgress.mode & 8) { + current$$1 = 0; + for (suspenseContext = nextProps.child; null !== suspenseContext; ) + (current$$1 += suspenseContext.treeBaseDuration), + (suspenseContext = suspenseContext.sibling); + nextProps.treeBaseDuration = current$$1; + } + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4504,14 +4404,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4528,24 +4430,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4562,7 +4457,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4571,9 +4466,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4587,33 +4482,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4628,9 +4532,11 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); profilerStartTime = -1; + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4655,10 +4561,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function( parent, workInProgress, @@ -4865,7 +4771,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { : (_lastTailNode.sibling = null); } } -function completeWork(current, workInProgress, renderExpirationTime) { +function completeWork(current, workInProgress, renderExpirationTime$jscomp$0) { var newProps = workInProgress.pendingProps; switch (workInProgress.tag) { case 2: @@ -4881,12 +4787,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 3: popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); - newProps = workInProgress.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - workInProgress.effectTag &= -3; + current = workInProgress.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(workInProgress); break; case 5: @@ -4894,12 +4798,12 @@ function completeWork(current, workInProgress, renderExpirationTime) { var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - renderExpirationTime = workInProgress.type; + renderExpirationTime$jscomp$0 = workInProgress.type; if (null !== current && null != workInProgress.stateNode) updateHostComponent$1( current, workInProgress, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance ), @@ -4909,23 +4813,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { requiredContext(contextStackCursor$1.current); current = nextReactTag; nextReactTag += 2; - renderExpirationTime = getViewConfigForType(renderExpirationTime); + renderExpirationTime$jscomp$0 = getViewConfigForType( + renderExpirationTime$jscomp$0 + ); var updatePayload = diffProperties( null, emptyObject, newProps, - renderExpirationTime.validAttributes + renderExpirationTime$jscomp$0.validAttributes ); rootContainerInstance = createNode( current, - renderExpirationTime.uiViewClassName, + renderExpirationTime$jscomp$0.uiViewClassName, rootContainerInstance, updatePayload, workInProgress ); current = new ReactFabricHostComponent( current, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, workInProgress ); @@ -4934,10 +4840,8 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.stateNode = current; null !== workInProgress.ref && (workInProgress.effectTag |= 128); } else if (null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -4950,10 +4854,8 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); else { if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); current = requiredContext(rootInstanceStackCursor.current); rootContainerInstance = requiredContext(contextStackCursor$1.current); @@ -4972,37 +4874,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { newProps = workInProgress.memoizedState; if (0 !== (workInProgress.effectTag & 64)) return ( - (workInProgress.expirationTime = renderExpirationTime), workInProgress + (workInProgress.expirationTime = renderExpirationTime$jscomp$0), + workInProgress ); newProps = null !== newProps; rootContainerInstance = !1; null !== current && - ((renderExpirationTime = current.memoizedState), - (rootContainerInstance = null !== renderExpirationTime), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === renderExpirationTime || - ((renderExpirationTime = current.child.sibling), - null !== renderExpirationTime && + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && ((updatePayload = workInProgress.firstEffect), null !== updatePayload - ? ((workInProgress.firstEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = updatePayload)) - : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = null)), - (renderExpirationTime.effectTag = 8)))); + ? ((workInProgress.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = updatePayload)) + : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if (newProps && !rootContainerInstance && 0 !== (workInProgress.mode & 2)) if ( (null === current && !0 !== workInProgress.memoizedProps.unstable_avoidThisFallback) || - 0 !== (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } newProps && (workInProgress.effectTag |= 4); break; case 7: @@ -5025,8 +4937,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 17: isContextProvider(workInProgress.type) && popContext(workInProgress); break; - case 18: - break; case 19: pop(suspenseStackCursor, workInProgress); newProps = workInProgress.memoizedState; @@ -5049,8 +4959,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { null !== current && ((workInProgress.updateQueue = current), (workInProgress.effectTag |= 4)); - workInProgress.firstEffect = workInProgress.lastEffect = null; - current = renderExpirationTime; + null === newProps.lastEffect && + (workInProgress.firstEffect = null); + workInProgress.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; for (newProps = workInProgress.child; null !== newProps; ) (rootContainerInstance = newProps), (updatePayload = current), @@ -5058,8 +4970,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.nextEffect = null), (rootContainerInstance.firstEffect = null), (rootContainerInstance.lastEffect = null), - (renderExpirationTime = rootContainerInstance.alternate), - null === renderExpirationTime + (renderExpirationTime$jscomp$0 = + rootContainerInstance.alternate), + null === renderExpirationTime$jscomp$0 ? ((rootContainerInstance.childExpirationTime = 0), (rootContainerInstance.expirationTime = updatePayload), (rootContainerInstance.child = null), @@ -5070,18 +4983,19 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.selfBaseDuration = 0), (rootContainerInstance.treeBaseDuration = 0)) : ((rootContainerInstance.childExpirationTime = - renderExpirationTime.childExpirationTime), + renderExpirationTime$jscomp$0.childExpirationTime), (rootContainerInstance.expirationTime = - renderExpirationTime.expirationTime), + renderExpirationTime$jscomp$0.expirationTime), (rootContainerInstance.child = - renderExpirationTime.child), + renderExpirationTime$jscomp$0.child), (rootContainerInstance.memoizedProps = - renderExpirationTime.memoizedProps), + renderExpirationTime$jscomp$0.memoizedProps), (rootContainerInstance.memoizedState = - renderExpirationTime.memoizedState), + renderExpirationTime$jscomp$0.memoizedState), (rootContainerInstance.updateQueue = - renderExpirationTime.updateQueue), - (updatePayload = renderExpirationTime.dependencies), + renderExpirationTime$jscomp$0.updateQueue), + (updatePayload = + renderExpirationTime$jscomp$0.dependencies), (rootContainerInstance.dependencies = null === updatePayload ? null @@ -5091,14 +5005,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { responders: updatePayload.responders }), (rootContainerInstance.selfBaseDuration = - renderExpirationTime.selfBaseDuration), + renderExpirationTime$jscomp$0.selfBaseDuration), (rootContainerInstance.treeBaseDuration = - renderExpirationTime.treeBaseDuration)), + renderExpirationTime$jscomp$0.treeBaseDuration)), (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, workInProgress ); return workInProgress.child; @@ -5114,24 +5027,24 @@ function completeWork(current, workInProgress, renderExpirationTime) { if ( ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((workInProgress.updateQueue = current), + (workInProgress.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((workInProgress.updateQueue = current), - (workInProgress.effectTag |= 4)); workInProgress = workInProgress.lastEffect = newProps.lastEffect; null !== workInProgress && (workInProgress.nextEffect = null); break; } } else now() > newProps.tailExpiration && - 1 < renderExpirationTime && + 1 < renderExpirationTime$jscomp$0 && ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), - (current = renderExpirationTime - 1), + (current = renderExpirationTime$jscomp$0 - 1), (workInProgress.expirationTime = workInProgress.childExpirationTime = current), null === spawnedWorkDuringRender ? (spawnedWorkDuringRender = [current]) @@ -5155,20 +5068,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { (newProps.lastEffect = workInProgress.lastEffect), (current.sibling = null), (newProps = suspenseStackCursor.current), - (newProps = rootContainerInstance - ? (newProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask), - push(suspenseStackCursor, newProps, workInProgress), + push( + suspenseStackCursor, + rootContainerInstance ? (newProps & 1) | 2 : newProps & 1, + workInProgress + ), current ); break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } return null; @@ -5178,8 +5094,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -5187,12 +5103,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -5200,13 +5114,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -5228,8 +5140,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -5237,7 +5149,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5287,24 +5199,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -5312,12 +5257,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority$1( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5374,7 +5319,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); return; case 12: return; @@ -5387,20 +5332,18 @@ function commitWork(current$$1, finishedWork) { attachSuspenseRetryListeners(finishedWork); return; } - switch (finishedWork.tag) { + a: switch (finishedWork.tag) { case 1: case 5: case 6: case 20: - break; + break a; case 3: case 4: - break; + break a; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5410,11 +5353,12 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || - ((retry = tracing.unstable_wrap(retry)), + (!0 !== thenable.__reactDoNotTraceInteractions && + (retry = tracing.unstable_wrap(retry)), retryCache.add(thenable), thenable.then(retry, retry)); }); @@ -5467,18 +5411,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5534,10 +5481,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5548,35 +5495,22 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - scheduleInteractions( - fiber, - expirationTime, - tracing.__interactionsRef.current - ); - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - } else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? (schedulePendingInteractions(fiber, expirationTime), + performSyncWorkOnRoot(fiber)) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime), + executionContext === NoContext && flushSyncCallbackQueue()) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime)); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5611,79 +5545,330 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var currentTime = requestCurrentTime(); + currentTime = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= currentTime + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = currentTime; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + currentTime, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } - scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) + prepareFreshStack(root, expirationTime), + startWorkOnPendingInteractions(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if ( + workInProgressRootHasPendingPing && + ((prevInteractions = root.lastPingedTime), + 0 === prevInteractions || prevInteractions >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevInteractions = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevInteractions && prevInteractions !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + prevInteractions = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (prevInteractions = + now() - + (10 * (1073741821 - prevInteractions) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + prevInteractions <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + prevInteractions)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || lastExpiredTime !== renderExpirationTime) + prepareFreshStack(root, lastExpiredTime), + startWorkOnPendingInteractions(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5729,354 +5914,196 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; spawnedWorkDuringRender = null; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime), - startWorkOnPendingInteractions(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root$jscomp$0.memoizedInteractions; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - (tracing.__interactionsRef.current = prevInteractions), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - currentTime.mode & 8 && - stopProfilerTimerIfRunningAndRecordDelta(currentTime, !0); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + workInProgress.mode & 8 && + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, !0); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - (sourceFiber = tracing.unstable_wrap(sourceFiber)), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - tracing.__interactionsRef.current = prevInteractions; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function pushInteractions(root) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var current$$1 = unitOfWork.alternate; 0 !== (unitOfWork.mode & 8) @@ -6095,7 +6122,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { if (0 === (workInProgress.mode & 8)) current$$1 = completeWork( current$$1, @@ -6154,7 +6181,7 @@ function completeUnitOfWork(unitOfWork) { } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6181,10 +6208,10 @@ function completeUnitOfWork(unitOfWork) { workInProgress.actualDuration = fiber; } if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6194,134 +6221,90 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority$1(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$1, renderPriorityLevel$jscomp$1) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$1.finishedWork, + expirationTime = root$jscomp$1.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$1.finishedWork = null; + root$jscomp$1.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$1.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$1.callbackNode = null; + root$jscomp$1.callbackExpirationTime = 0; + root$jscomp$1.callbackPriority = 90; + root$jscomp$1.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$1.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$1.lastSuspendedTime + ? (root$jscomp$1.firstSuspendedTime = root$jscomp$1.lastSuspendedTime = root$jscomp$1.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$1.firstSuspendedTime && + (root$jscomp$1.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$1.lastPingedTime && + (root$jscomp$1.lastPingedTime = 0); + expirationTime <= root$jscomp$1.lastExpiredTime && + (root$jscomp$1.lastExpiredTime = 0); + root$jscomp$1 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + var prevInteractions = pushInteractions(root$jscomp$1); ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); commitTime = now$1(); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$1, + renderPriorityLevel = renderPriorityLevel$jscomp$1; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: nextEffect.effectTag &= -3; break; @@ -6329,122 +6312,124 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - prevProps = nextEffect; + var current$$1$jscomp$0 = nextEffect; a: for ( - prevState = prevProps, - instance = current$$1, - snapshot = prevState; + var finishedRoot = root, + root$jscomp$0 = current$$1$jscomp$0, + renderPriorityLevel$jscomp$0 = renderPriorityLevel, + node = root$jscomp$0; ; ) if ( - (commitUnmount(snapshot, instance), null !== snapshot.child) + (commitUnmount( + finishedRoot, + node, + renderPriorityLevel$jscomp$0 + ), + null !== node.child) ) - (snapshot.child.return = snapshot), - (snapshot = snapshot.child); + (node.child.return = node), (node = node.child); else { - if (snapshot === prevState) break; - for (; null === snapshot.sibling; ) { - if ( - null === snapshot.return || - snapshot.return === prevState - ) + if (node === root$jscomp$0) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === root$jscomp$0) break a; - snapshot = snapshot.return; + node = node.return; } - snapshot.sibling.return = snapshot.return; - snapshot = snapshot.sibling; + node.sibling.return = node.return; + node = node.sibling; } - detachFiber(prevProps); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$1.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for ( - effectTag = root, current$$1$jscomp$0 = expirationTime; + effectTag = root$jscomp$1, current$$1 = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { - prevProps = effectTag; + renderPriorityLevel = effectTag; var current$$1$jscomp$1 = nextEffect.alternate; currentRef = nextEffect; - current$$1 = current$$1$jscomp$0; + root = current$$1; switch (currentRef.tag) { case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, currentRef); + commitHookEffectList(16, 32, currentRef); break; case 1: - var instance$jscomp$0 = currentRef.stateNode; + var instance = currentRef.stateNode; if (currentRef.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = + var prevProps = currentRef.elementType === currentRef.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( currentRef.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } var updateQueue = currentRef.updateQueue; null !== updateQueue && - commitUpdateQueue( - currentRef, - updateQueue, - instance$jscomp$0, - current$$1 - ); + commitUpdateQueue(currentRef, updateQueue, instance, root); break; case 3: var _updateQueue = currentRef.updateQueue; if (null !== _updateQueue) { - prevProps = null; + renderPriorityLevel = null; if (null !== currentRef.child) switch (currentRef.child.tag) { case 5: - prevProps = currentRef.child.stateNode.canonical; + renderPriorityLevel = + currentRef.child.stateNode.canonical; break; case 1: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; } commitUpdateQueue( currentRef, _updateQueue, - prevProps, - current$$1 + renderPriorityLevel, + root ); } break; case 5: if (null === current$$1$jscomp$1 && currentRef.effectTag & 4) - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6461,44 +6446,43 @@ function commitRootImpl(root, renderPriorityLevel) { currentRef.treeBaseDuration, currentRef.actualStartTime, commitTime, - prevProps.memoizedInteractions + renderPriorityLevel.memoizedInteractions ); break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + currentRef = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1.canonical; + currentRef = instance$jscomp$0.canonical; break; default: - instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(currentRef) + : (ref.current = currentRef); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } @@ -6506,80 +6490,99 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect = null; requestPaint(); tracing.__interactionsRef.current = prevInteractions; - executionContext = childExpirationTimeBeforeCommit; - } else (root.current = finishedWork), (commitTime = now$1()); + executionContext = prevExecutionContext; + } else (root$jscomp$1.current = finishedWork), (commitTime = now$1()); if ((effectTag$jscomp$0 = rootDoesHavePassiveEffects)) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), + (rootWithPendingPassiveEffects = root$jscomp$1), (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$1); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$1 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - if (0 !== renderPriorityLevel) { - current$$1$jscomp$1 = requestCurrentTime(); - current$$1$jscomp$1 = inferPriorityFromExpirationTime( - current$$1$jscomp$1, - renderPriorityLevel - ); + (nextEffect = renderPriorityLevel$jscomp$1); + renderPriorityLevel$jscomp$1 = root$jscomp$1.firstPendingTime; + if (0 !== renderPriorityLevel$jscomp$1) { if (null !== spawnedWorkDuringRender) for ( - instance$jscomp$0 = spawnedWorkDuringRender, + remainingExpirationTimeBeforeCommit = spawnedWorkDuringRender, spawnedWorkDuringRender = null, - prevProps$jscomp$0 = 0; - prevProps$jscomp$0 < instance$jscomp$0.length; - prevProps$jscomp$0++ + current$$1$jscomp$1 = 0; + current$$1$jscomp$1 < remainingExpirationTimeBeforeCommit.length; + current$$1$jscomp$1++ ) scheduleInteractions( - root, - instance$jscomp$0[prevProps$jscomp$0], - root.memoizedInteractions + root$jscomp$1, + remainingExpirationTimeBeforeCommit[current$$1$jscomp$1], + root$jscomp$1.memoizedInteractions ); - scheduleCallbackForRoot(root, current$$1$jscomp$1, renderPriorityLevel); + schedulePendingInteractions(root$jscomp$1, renderPriorityLevel$jscomp$1); } else legacyErrorBoundariesThatAlreadyFailed = null; - effectTag$jscomp$0 || finishPendingInteractions(root, expirationTime); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + effectTag$jscomp$0 || + finishPendingInteractions(root$jscomp$1, expirationTime); + 1073741823 === renderPriorityLevel$jscomp$1 + ? root$jscomp$1 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$1)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$1); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$1 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$1); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + expirationTime = pendingPassiveEffectsExpirationTime; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority$1( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; - for (var effect = root.current.firstEffect; null !== effect; ) { + for ( + var prevInteractions = pushInteractions(root), + effect = root.current.firstEffect; + null !== effect; + + ) { try { var finishedWork = effect; if (0 !== (finishedWork.effectTag & 512)) @@ -6587,12 +6590,11 @@ function flushPassiveEffectsImpl(root, expirationTime) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === effect) - throw ReactError(Error("Should be working on an effect.")); + if (null === effect) throw Error("Should be working on an effect."); captureCommitPhaseError(effect, error); } finishedWork = effect.nextEffect; @@ -6610,7 +6612,9 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && + (ensureRootIsScheduled(rootFiber), + schedulePendingInteractions(rootFiber, 1073741823)); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6632,7 +6636,9 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && + (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, 1073741823)); break; } } @@ -6649,27 +6655,28 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root), + schedulePendingInteractions(root, suspendedTime))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + (ensureRootIsScheduled(boundaryFiber), + schedulePendingInteractions(boundaryFiber, thenable)); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6718,7 +6725,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6730,7 +6737,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6762,6 +6769,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6846,7 +6854,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6889,12 +6899,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6934,10 +6942,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -6975,7 +6981,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7066,7 +7073,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7255,10 +7262,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; function scheduleInteractions(root, expirationTime, interactions) { @@ -7282,6 +7289,9 @@ function scheduleInteractions(root, expirationTime, interactions) { ); } } +function schedulePendingInteractions(root, expirationTime) { + scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); +} function startWorkOnPendingInteractions(root, expirationTime) { var interactions = new Set(); root.pendingInteractionMap.forEach(function( @@ -7309,13 +7319,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { } } function finishPendingInteractions(root, committedExpirationTime) { - var earliestRemainingTimeAfterCommit = root.firstPendingTime, - subscriber = void 0; + var earliestRemainingTimeAfterCommit = root.firstPendingTime; try { - if ( - ((subscriber = tracing.__subscriberRef.current), - null !== subscriber && 0 < root.memoizedInteractions.size) - ) + var subscriber = tracing.__subscriberRef.current; + if (null !== subscriber && 0 < root.memoizedInteractions.size) subscriber.onWorkStopped( root.memoizedInteractions, 1e3 * committedExpirationTime + root.interactionThreadID @@ -7523,12 +7530,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7572,22 +7577,57 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; +} function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7597,23 +7637,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7631,10 +7668,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7653,14 +7688,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7673,31 +7707,6 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits$1(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; var fabricDispatchCommand = nativeFabricUIManager.dispatchCommand; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7731,33 +7740,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits$1(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7770,10 +7769,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7786,34 +7784,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7889,9 +7885,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7905,9 +7900,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7921,29 +7915,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8005,9 +7997,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromInstance, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/implementations/ReactFabric-profiling.js b/Libraries/Renderer/implementations/ReactFabric-profiling.js index 438c943a0ad3df..47e8f56ab146ad 100644 --- a/Libraries/Renderer/implementations/ReactFabric-profiling.js +++ b/Libraries/Renderer/implementations/ReactFabric-profiling.js @@ -15,12 +15,8 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"), - tracing = require("scheduler/tracing"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} -var eventPluginOrder = null, + tracing = require("scheduler/tracing"), + eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { if (eventPluginOrder) @@ -28,21 +24,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -52,12 +44,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -82,14 +72,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -97,12 +85,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -150,10 +136,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -171,7 +155,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -183,10 +167,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -222,10 +204,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -241,12 +221,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -287,14 +265,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -457,10 +433,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -496,8 +470,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -611,8 +584,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -712,7 +685,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -725,7 +698,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -734,9 +707,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -745,194 +718,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -940,7 +921,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -954,9 +935,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -989,10 +973,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1018,7 +1000,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - if (!inst) throw ReactError(Error("All native instances should have a tag.")); + if (!inst) throw Error("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1057,6 +1039,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1065,6 +1048,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1104,27 +1107,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1144,7 +1151,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1180,22 +1187,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1447,10 +1450,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1481,51 +1482,26 @@ function batchedUpdates(fn, bookkeeping) { restoreStateOfTarget(fn[bookkeeping]); } } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; } (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() {}; - ReactNativeComponent.prototype.focus = function() {}; - ReactNativeComponent.prototype.measure = function() {}; - ReactNativeComponent.prototype.measureInWindow = function() {}; - ReactNativeComponent.prototype.measureLayout = function() {}; - ReactNativeComponent.prototype.setNativeProps = function() {}; + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() {}; + _proto.focus = function() {}; + _proto.measure = function() {}; + _proto.measureInWindow = function() {}; + _proto.measureLayout = function() {}; + _proto.setNativeProps = function() {}; return ReactNativeComponent; })(React.Component); new Map(); -new Map(); -new Set(); -new Map(); function dispatchEvent(target, topLevelType, nativeEvent) { batchedUpdates(function() { var events = nativeEvent.target; @@ -1536,7 +1512,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { topLevelType, target, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1547,10 +1524,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1561,10 +1536,8 @@ function dispatchEvent(target, topLevelType, nativeEvent) { }); } function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var _nativeFabricUIManage$1 = nativeFabricUIManager, @@ -1593,36 +1566,31 @@ var ReactFabricHostComponent = (function() { props, internalInstanceHandle ) { - if (!(this instanceof ReactFabricHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this.viewConfig = viewConfig; this.currentProps = props; this._internalInstanceHandle = internalInstanceHandle; } - ReactFabricHostComponent.prototype.blur = function() { + var _proto = ReactFabricHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { fabricMeasure( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { fabricMeasureInWindow( this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { "number" !== typeof relativeToNativeNode && relativeToNativeNode instanceof ReactFabricHostComponent && fabricMeasureLayout( @@ -1632,7 +1600,7 @@ var ReactFabricHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactFabricHostComponent.prototype.setNativeProps = function() {}; + _proto.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1642,9 +1610,7 @@ function createTextInstance( internalInstanceHandle ) { if (!hostContext.isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") - ); + throw Error("Text strings must be rendered within a component."); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1757,10 +1723,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1772,15 +1736,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1799,10 +1761,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1830,10 +1790,8 @@ if ( null == tracing.__interactionsRef || null == tracing.__interactionsRef.current ) - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) + 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" ); var fakeCallbackNode = {}, requestPaint = @@ -1861,7 +1819,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1877,7 +1835,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority$1(reactPriorityLevel, fn) { @@ -1899,8 +1857,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1931,7 +1892,7 @@ function flushSyncCallbackQueueImpl() { } function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; + if (1 === expirationTime || 2 === expirationTime) return 95; currentTime = 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); return 0 >= currentTime @@ -1945,9 +1906,10 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1961,7 +1923,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1976,41 +1938,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2066,10 +1993,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2189,7 +2114,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2284,6 +2209,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2300,18 +2226,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2339,7 +2262,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2504,23 +2427,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2539,32 +2457,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2966,14 +2878,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3065,7 +2975,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3090,10 +3000,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3129,7 +3043,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3149,10 +3063,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3207,11 +3122,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3225,10 +3138,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3266,14 +3177,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3294,15 +3208,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3317,16 +3223,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3369,10 +3273,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3408,9 +3310,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3434,10 +3334,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3451,7 +3349,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3479,7 +3377,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3493,7 +3392,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3533,7 +3432,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3561,10 +3460,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3592,28 +3489,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3621,10 +3514,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3656,19 +3549,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3736,19 +3629,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3814,7 +3707,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3834,7 +3727,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4328,7 +4221,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4337,164 +4230,171 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; if (0 === (workInProgress.mode & 2)) for ( - nextDidTimeout = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; + nextProps.child = current$$1; + null !== current$$1; ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( - nextProps, + nextDidTimeout, mode, renderExpirationTime, null ); renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime + nextProps.sibling = renderExpirationTime; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - else { - if (null !== current$$1.memoizedState) + renderExpirationTime.return = workInProgress; if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - if (workInProgress.mode & 8) { - nextDidTimeout = 0; - for ( - suspenseContext = renderExpirationTime.child; - null !== suspenseContext; - - ) - (nextDidTimeout += suspenseContext.treeBaseDuration), - (suspenseContext = suspenseContext.sibling); - renderExpirationTime.treeBaseDuration = nextDidTimeout; - } - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { - nextDidTimeout = nextProps.fallback; - nextProps = createFiberFromFragment(null, mode, 0, null); - nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); - if (0 === (workInProgress.mode & 2)) + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) for ( - suspenseContext = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); if (workInProgress.mode & 8) { - suspenseContext = 0; - for (JSCompiler_temp = nextProps.child; null !== JSCompiler_temp; ) - (suspenseContext += JSCompiler_temp.treeBaseDuration), - (JSCompiler_temp = JSCompiler_temp.sibling); - nextProps.treeBaseDuration = suspenseContext; + nextDidTimeout = 0; + for (current$$1 = renderExpirationTime.child; null !== current$$1; ) + (nextDidTimeout += current$$1.treeBaseDuration), + (current$$1 = current$$1.sibling); + renderExpirationTime.treeBaseDuration = nextDidTimeout; } - renderExpirationTime = createFiberFromFragment( - nextDidTimeout, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime - ); - workInProgress.stateNode = current$$1.stateNode; + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + if (workInProgress.mode & 8) { + current$$1 = 0; + for (suspenseContext = nextProps.child; null !== suspenseContext; ) + (current$$1 += suspenseContext.treeBaseDuration), + (suspenseContext = suspenseContext.sibling); + nextProps.treeBaseDuration = current$$1; + } + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4504,14 +4404,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4528,24 +4430,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4562,7 +4457,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4571,9 +4466,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4587,33 +4482,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4628,9 +4532,11 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); profilerStartTime = -1; + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4655,10 +4561,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function( parent, workInProgress, @@ -4865,7 +4771,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { : (_lastTailNode.sibling = null); } } -function completeWork(current, workInProgress, renderExpirationTime) { +function completeWork(current, workInProgress, renderExpirationTime$jscomp$0) { var newProps = workInProgress.pendingProps; switch (workInProgress.tag) { case 2: @@ -4881,12 +4787,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 3: popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); - newProps = workInProgress.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - workInProgress.effectTag &= -3; + current = workInProgress.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(workInProgress); break; case 5: @@ -4894,12 +4798,12 @@ function completeWork(current, workInProgress, renderExpirationTime) { var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - renderExpirationTime = workInProgress.type; + renderExpirationTime$jscomp$0 = workInProgress.type; if (null !== current && null != workInProgress.stateNode) updateHostComponent$1( current, workInProgress, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance ), @@ -4909,23 +4813,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { requiredContext(contextStackCursor$1.current); current = nextReactTag; nextReactTag += 2; - renderExpirationTime = getViewConfigForType(renderExpirationTime); + renderExpirationTime$jscomp$0 = getViewConfigForType( + renderExpirationTime$jscomp$0 + ); var updatePayload = diffProperties( null, emptyObject, newProps, - renderExpirationTime.validAttributes + renderExpirationTime$jscomp$0.validAttributes ); rootContainerInstance = createNode( current, - renderExpirationTime.uiViewClassName, + renderExpirationTime$jscomp$0.uiViewClassName, rootContainerInstance, updatePayload, workInProgress ); current = new ReactFabricHostComponent( current, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, workInProgress ); @@ -4934,10 +4840,8 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.stateNode = current; null !== workInProgress.ref && (workInProgress.effectTag |= 128); } else if (null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -4950,10 +4854,8 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); else { if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); current = requiredContext(rootInstanceStackCursor.current); rootContainerInstance = requiredContext(contextStackCursor$1.current); @@ -4972,37 +4874,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { newProps = workInProgress.memoizedState; if (0 !== (workInProgress.effectTag & 64)) return ( - (workInProgress.expirationTime = renderExpirationTime), workInProgress + (workInProgress.expirationTime = renderExpirationTime$jscomp$0), + workInProgress ); newProps = null !== newProps; rootContainerInstance = !1; null !== current && - ((renderExpirationTime = current.memoizedState), - (rootContainerInstance = null !== renderExpirationTime), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === renderExpirationTime || - ((renderExpirationTime = current.child.sibling), - null !== renderExpirationTime && + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && ((updatePayload = workInProgress.firstEffect), null !== updatePayload - ? ((workInProgress.firstEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = updatePayload)) - : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = null)), - (renderExpirationTime.effectTag = 8)))); + ? ((workInProgress.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = updatePayload)) + : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if (newProps && !rootContainerInstance && 0 !== (workInProgress.mode & 2)) if ( (null === current && !0 !== workInProgress.memoizedProps.unstable_avoidThisFallback) || - 0 !== (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } newProps && (workInProgress.effectTag |= 4); break; case 7: @@ -5025,8 +4937,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 17: isContextProvider(workInProgress.type) && popContext(workInProgress); break; - case 18: - break; case 19: pop(suspenseStackCursor, workInProgress); newProps = workInProgress.memoizedState; @@ -5049,8 +4959,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { null !== current && ((workInProgress.updateQueue = current), (workInProgress.effectTag |= 4)); - workInProgress.firstEffect = workInProgress.lastEffect = null; - current = renderExpirationTime; + null === newProps.lastEffect && + (workInProgress.firstEffect = null); + workInProgress.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; for (newProps = workInProgress.child; null !== newProps; ) (rootContainerInstance = newProps), (updatePayload = current), @@ -5058,8 +4970,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.nextEffect = null), (rootContainerInstance.firstEffect = null), (rootContainerInstance.lastEffect = null), - (renderExpirationTime = rootContainerInstance.alternate), - null === renderExpirationTime + (renderExpirationTime$jscomp$0 = + rootContainerInstance.alternate), + null === renderExpirationTime$jscomp$0 ? ((rootContainerInstance.childExpirationTime = 0), (rootContainerInstance.expirationTime = updatePayload), (rootContainerInstance.child = null), @@ -5070,18 +4983,19 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.selfBaseDuration = 0), (rootContainerInstance.treeBaseDuration = 0)) : ((rootContainerInstance.childExpirationTime = - renderExpirationTime.childExpirationTime), + renderExpirationTime$jscomp$0.childExpirationTime), (rootContainerInstance.expirationTime = - renderExpirationTime.expirationTime), + renderExpirationTime$jscomp$0.expirationTime), (rootContainerInstance.child = - renderExpirationTime.child), + renderExpirationTime$jscomp$0.child), (rootContainerInstance.memoizedProps = - renderExpirationTime.memoizedProps), + renderExpirationTime$jscomp$0.memoizedProps), (rootContainerInstance.memoizedState = - renderExpirationTime.memoizedState), + renderExpirationTime$jscomp$0.memoizedState), (rootContainerInstance.updateQueue = - renderExpirationTime.updateQueue), - (updatePayload = renderExpirationTime.dependencies), + renderExpirationTime$jscomp$0.updateQueue), + (updatePayload = + renderExpirationTime$jscomp$0.dependencies), (rootContainerInstance.dependencies = null === updatePayload ? null @@ -5091,14 +5005,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { responders: updatePayload.responders }), (rootContainerInstance.selfBaseDuration = - renderExpirationTime.selfBaseDuration), + renderExpirationTime$jscomp$0.selfBaseDuration), (rootContainerInstance.treeBaseDuration = - renderExpirationTime.treeBaseDuration)), + renderExpirationTime$jscomp$0.treeBaseDuration)), (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, workInProgress ); return workInProgress.child; @@ -5114,24 +5027,24 @@ function completeWork(current, workInProgress, renderExpirationTime) { if ( ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((workInProgress.updateQueue = current), + (workInProgress.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((workInProgress.updateQueue = current), - (workInProgress.effectTag |= 4)); workInProgress = workInProgress.lastEffect = newProps.lastEffect; null !== workInProgress && (workInProgress.nextEffect = null); break; } } else now() > newProps.tailExpiration && - 1 < renderExpirationTime && + 1 < renderExpirationTime$jscomp$0 && ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), - (current = renderExpirationTime - 1), + (current = renderExpirationTime$jscomp$0 - 1), (workInProgress.expirationTime = workInProgress.childExpirationTime = current), null === spawnedWorkDuringRender ? (spawnedWorkDuringRender = [current]) @@ -5155,20 +5068,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { (newProps.lastEffect = workInProgress.lastEffect), (current.sibling = null), (newProps = suspenseStackCursor.current), - (newProps = rootContainerInstance - ? (newProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask), - push(suspenseStackCursor, newProps, workInProgress), + push( + suspenseStackCursor, + rootContainerInstance ? (newProps & 1) | 2 : newProps & 1, + workInProgress + ), current ); break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } return null; @@ -5178,8 +5094,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -5187,12 +5103,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -5200,13 +5114,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -5228,8 +5140,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -5237,7 +5149,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5287,24 +5199,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -5312,12 +5257,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority$1( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5374,7 +5319,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); return; case 12: return; @@ -5387,20 +5332,18 @@ function commitWork(current$$1, finishedWork) { attachSuspenseRetryListeners(finishedWork); return; } - switch (finishedWork.tag) { + a: switch (finishedWork.tag) { case 1: case 5: case 6: case 20: - break; + break a; case 3: case 4: - break; + break a; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5410,11 +5353,12 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || - ((retry = tracing.unstable_wrap(retry)), + (!0 !== thenable.__reactDoNotTraceInteractions && + (retry = tracing.unstable_wrap(retry)), retryCache.add(thenable), thenable.then(retry, retry)); }); @@ -5467,18 +5411,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5534,10 +5481,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5548,35 +5495,22 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - scheduleInteractions( - fiber, - expirationTime, - tracing.__interactionsRef.current - ); - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - } else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? (schedulePendingInteractions(fiber, expirationTime), + performSyncWorkOnRoot(fiber)) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime), + executionContext === NoContext && flushSyncCallbackQueue()) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime)); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5611,79 +5545,330 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var currentTime = requestCurrentTime(); + currentTime = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= currentTime + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = currentTime; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + currentTime, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } - scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) + prepareFreshStack(root, expirationTime), + startWorkOnPendingInteractions(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if ( + workInProgressRootHasPendingPing && + ((prevInteractions = root.lastPingedTime), + 0 === prevInteractions || prevInteractions >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevInteractions = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevInteractions && prevInteractions !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + prevInteractions = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (prevInteractions = + now() - + (10 * (1073741821 - prevInteractions) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + prevInteractions <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + prevInteractions)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || lastExpiredTime !== renderExpirationTime) + prepareFreshStack(root, lastExpiredTime), + startWorkOnPendingInteractions(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5729,354 +5914,196 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; spawnedWorkDuringRender = null; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime), - startWorkOnPendingInteractions(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root$jscomp$0.memoizedInteractions; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - (tracing.__interactionsRef.current = prevInteractions), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - currentTime.mode & 8 && - stopProfilerTimerIfRunningAndRecordDelta(currentTime, !0); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + workInProgress.mode & 8 && + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, !0); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - (sourceFiber = tracing.unstable_wrap(sourceFiber)), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - tracing.__interactionsRef.current = prevInteractions; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function pushInteractions(root) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var current$$1 = unitOfWork.alternate; 0 !== (unitOfWork.mode & 8) @@ -6095,7 +6122,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { if (0 === (workInProgress.mode & 8)) current$$1 = completeWork( current$$1, @@ -6154,7 +6181,7 @@ function completeUnitOfWork(unitOfWork) { } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6181,10 +6208,10 @@ function completeUnitOfWork(unitOfWork) { workInProgress.actualDuration = fiber; } if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6194,134 +6221,90 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority$1(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$1, renderPriorityLevel$jscomp$1) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$1.finishedWork, + expirationTime = root$jscomp$1.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$1.finishedWork = null; + root$jscomp$1.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$1.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$1.callbackNode = null; + root$jscomp$1.callbackExpirationTime = 0; + root$jscomp$1.callbackPriority = 90; + root$jscomp$1.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$1.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$1.lastSuspendedTime + ? (root$jscomp$1.firstSuspendedTime = root$jscomp$1.lastSuspendedTime = root$jscomp$1.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$1.firstSuspendedTime && + (root$jscomp$1.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$1.lastPingedTime && + (root$jscomp$1.lastPingedTime = 0); + expirationTime <= root$jscomp$1.lastExpiredTime && + (root$jscomp$1.lastExpiredTime = 0); + root$jscomp$1 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + var prevInteractions = pushInteractions(root$jscomp$1); ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); commitTime = now$1(); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$1, + renderPriorityLevel = renderPriorityLevel$jscomp$1; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: nextEffect.effectTag &= -3; break; @@ -6329,122 +6312,124 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - prevProps = nextEffect; + var current$$1$jscomp$0 = nextEffect; a: for ( - prevState = prevProps, - instance = current$$1, - snapshot = prevState; + var finishedRoot = root, + root$jscomp$0 = current$$1$jscomp$0, + renderPriorityLevel$jscomp$0 = renderPriorityLevel, + node = root$jscomp$0; ; ) if ( - (commitUnmount(snapshot, instance), null !== snapshot.child) + (commitUnmount( + finishedRoot, + node, + renderPriorityLevel$jscomp$0 + ), + null !== node.child) ) - (snapshot.child.return = snapshot), - (snapshot = snapshot.child); + (node.child.return = node), (node = node.child); else { - if (snapshot === prevState) break; - for (; null === snapshot.sibling; ) { - if ( - null === snapshot.return || - snapshot.return === prevState - ) + if (node === root$jscomp$0) break; + for (; null === node.sibling; ) { + if (null === node.return || node.return === root$jscomp$0) break a; - snapshot = snapshot.return; + node = node.return; } - snapshot.sibling.return = snapshot.return; - snapshot = snapshot.sibling; + node.sibling.return = node.return; + node = node.sibling; } - detachFiber(prevProps); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$1.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for ( - effectTag = root, current$$1$jscomp$0 = expirationTime; + effectTag = root$jscomp$1, current$$1 = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { - prevProps = effectTag; + renderPriorityLevel = effectTag; var current$$1$jscomp$1 = nextEffect.alternate; currentRef = nextEffect; - current$$1 = current$$1$jscomp$0; + root = current$$1; switch (currentRef.tag) { case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, currentRef); + commitHookEffectList(16, 32, currentRef); break; case 1: - var instance$jscomp$0 = currentRef.stateNode; + var instance = currentRef.stateNode; if (currentRef.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = + var prevProps = currentRef.elementType === currentRef.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( currentRef.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } var updateQueue = currentRef.updateQueue; null !== updateQueue && - commitUpdateQueue( - currentRef, - updateQueue, - instance$jscomp$0, - current$$1 - ); + commitUpdateQueue(currentRef, updateQueue, instance, root); break; case 3: var _updateQueue = currentRef.updateQueue; if (null !== _updateQueue) { - prevProps = null; + renderPriorityLevel = null; if (null !== currentRef.child) switch (currentRef.child.tag) { case 5: - prevProps = currentRef.child.stateNode.canonical; + renderPriorityLevel = + currentRef.child.stateNode.canonical; break; case 1: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; } commitUpdateQueue( currentRef, _updateQueue, - prevProps, - current$$1 + renderPriorityLevel, + root ); } break; case 5: if (null === current$$1$jscomp$1 && currentRef.effectTag & 4) - throw ReactError( - Error( - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6461,44 +6446,43 @@ function commitRootImpl(root, renderPriorityLevel) { currentRef.treeBaseDuration, currentRef.actualStartTime, commitTime, - prevProps.memoizedInteractions + renderPriorityLevel.memoizedInteractions ); break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + currentRef = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1.canonical; + currentRef = instance$jscomp$0.canonical; break; default: - instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(currentRef) + : (ref.current = currentRef); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } @@ -6506,80 +6490,99 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect = null; requestPaint(); tracing.__interactionsRef.current = prevInteractions; - executionContext = childExpirationTimeBeforeCommit; - } else (root.current = finishedWork), (commitTime = now$1()); + executionContext = prevExecutionContext; + } else (root$jscomp$1.current = finishedWork), (commitTime = now$1()); if ((effectTag$jscomp$0 = rootDoesHavePassiveEffects)) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), + (rootWithPendingPassiveEffects = root$jscomp$1), (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$1); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$1 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - if (0 !== renderPriorityLevel) { - current$$1$jscomp$1 = requestCurrentTime(); - current$$1$jscomp$1 = inferPriorityFromExpirationTime( - current$$1$jscomp$1, - renderPriorityLevel - ); + (nextEffect = renderPriorityLevel$jscomp$1); + renderPriorityLevel$jscomp$1 = root$jscomp$1.firstPendingTime; + if (0 !== renderPriorityLevel$jscomp$1) { if (null !== spawnedWorkDuringRender) for ( - instance$jscomp$0 = spawnedWorkDuringRender, + remainingExpirationTimeBeforeCommit = spawnedWorkDuringRender, spawnedWorkDuringRender = null, - prevProps$jscomp$0 = 0; - prevProps$jscomp$0 < instance$jscomp$0.length; - prevProps$jscomp$0++ + current$$1$jscomp$1 = 0; + current$$1$jscomp$1 < remainingExpirationTimeBeforeCommit.length; + current$$1$jscomp$1++ ) scheduleInteractions( - root, - instance$jscomp$0[prevProps$jscomp$0], - root.memoizedInteractions + root$jscomp$1, + remainingExpirationTimeBeforeCommit[current$$1$jscomp$1], + root$jscomp$1.memoizedInteractions ); - scheduleCallbackForRoot(root, current$$1$jscomp$1, renderPriorityLevel); + schedulePendingInteractions(root$jscomp$1, renderPriorityLevel$jscomp$1); } else legacyErrorBoundariesThatAlreadyFailed = null; - effectTag$jscomp$0 || finishPendingInteractions(root, expirationTime); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + effectTag$jscomp$0 || + finishPendingInteractions(root$jscomp$1, expirationTime); + 1073741823 === renderPriorityLevel$jscomp$1 + ? root$jscomp$1 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$1)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$1); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$1 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$1); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + expirationTime = pendingPassiveEffectsExpirationTime; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority$1( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; - for (var effect = root.current.firstEffect; null !== effect; ) { + for ( + var prevInteractions = pushInteractions(root), + effect = root.current.firstEffect; + null !== effect; + + ) { try { var finishedWork = effect; if (0 !== (finishedWork.effectTag & 512)) @@ -6587,12 +6590,11 @@ function flushPassiveEffectsImpl(root, expirationTime) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === effect) - throw ReactError(Error("Should be working on an effect.")); + if (null === effect) throw Error("Should be working on an effect."); captureCommitPhaseError(effect, error); } finishedWork = effect.nextEffect; @@ -6610,7 +6612,9 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && + (ensureRootIsScheduled(rootFiber), + schedulePendingInteractions(rootFiber, 1073741823)); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6632,7 +6636,9 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && + (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, 1073741823)); break; } } @@ -6649,27 +6655,28 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root), + schedulePendingInteractions(root, suspendedTime))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + (ensureRootIsScheduled(boundaryFiber), + schedulePendingInteractions(boundaryFiber, thenable)); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6718,7 +6725,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6730,7 +6737,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6762,6 +6769,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6846,7 +6854,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6889,12 +6899,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6934,10 +6942,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -6975,7 +6981,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7066,7 +7073,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7255,10 +7262,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; function scheduleInteractions(root, expirationTime, interactions) { @@ -7282,6 +7289,9 @@ function scheduleInteractions(root, expirationTime, interactions) { ); } } +function schedulePendingInteractions(root, expirationTime) { + scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); +} function startWorkOnPendingInteractions(root, expirationTime) { var interactions = new Set(); root.pendingInteractionMap.forEach(function( @@ -7309,13 +7319,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { } } function finishPendingInteractions(root, committedExpirationTime) { - var earliestRemainingTimeAfterCommit = root.firstPendingTime, - subscriber = void 0; + var earliestRemainingTimeAfterCommit = root.firstPendingTime; try { - if ( - ((subscriber = tracing.__subscriberRef.current), - null !== subscriber && 0 < root.memoizedInteractions.size) - ) + var subscriber = tracing.__subscriberRef.current; + if (null !== subscriber && 0 < root.memoizedInteractions.size) subscriber.onWorkStopped( root.memoizedInteractions, 1e3 * committedExpirationTime + root.interactionThreadID @@ -7523,12 +7530,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7572,22 +7577,57 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; +} function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7597,23 +7637,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7631,10 +7668,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7653,14 +7688,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7673,31 +7707,6 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits$1(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; var fabricDispatchCommand = nativeFabricUIManager.dispatchCommand; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7731,33 +7740,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits$1(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7770,10 +7769,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7786,34 +7784,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7889,9 +7885,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7905,9 +7900,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7921,29 +7915,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8005,9 +7997,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromInstance, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-dev.fb.js b/Libraries/Renderer/implementations/ReactNativeRenderer-dev.fb.js index 374adcab380b51..755cd15bdac128 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-dev.fb.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-dev.fb.js @@ -22,15 +22,6 @@ var checkPropTypes = require("prop-types/checkPropTypes"); var Scheduler = require("scheduler"); var tracing = require("scheduler/tracing"); -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. - -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} - /** * Use invariant() to assert state which your program assumes to be true. * @@ -46,76 +37,69 @@ function ReactError(error) { * Injectable ordering of event plugins. */ var eventPluginOrder = null; - /** * Injectable mapping from names to event plugin modules. */ -var namesToPlugins = {}; +var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ + function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } + for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); - (function() { - if (!(pluginIndex > -1)) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) - ); - } - })(); + + if (!(pluginIndex > -1)) { + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + if (plugins[pluginIndex]) { continue; } - (function() { - if (!pluginModule.extractEvents) { - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) - ); - } - })(); + + if (!pluginModule.extractEvents) { + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + } + plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { - (function() { - if ( - !publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ) - ) { - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) - ); - } - })(); + if ( + !publishEventForPlugin( + publishedEvents[eventName], + pluginModule, + eventName + ) + ) { + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } } } } - /** * Publishes an event so that it can be dispatched by the supplied plugin. * @@ -124,21 +108,19 @@ function recomputePluginOrdering() { * @return {boolean} True if the event was successfully published. * @private */ + function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - (function() { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName + - "`." - ) - ); - } - })(); - eventNameDispatchConfigs[eventName] = dispatchConfig; + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." + ); + } + eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { @@ -150,6 +132,7 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); } } + return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( @@ -159,9 +142,9 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); return true; } + return false; } - /** * Publishes a registration name that is used to identify dispatched events. * @@ -169,18 +152,16 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { * @param {object} PluginModule Plugin publishing the event. * @private */ + function publishRegistrationName(registrationName, pluginModule, eventName) { - (function() { - if (!!registrationNameModules[registrationName]) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) - ); - } - })(); + if (!!registrationNameModules[registrationName]) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + registrationNameModules[registrationName] = pluginModule; registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; @@ -189,7 +170,6 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { var lowerCasedName = registrationName.toLowerCase(); } } - /** * Registers plugins so that they can extract and dispatch events. * @@ -199,23 +179,23 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { /** * Ordered list of injected plugins. */ -var plugins = []; +var plugins = []; /** * Mapping from event name to dispatch config */ -var eventNameDispatchConfigs = {}; +var eventNameDispatchConfigs = {}; /** * Mapping from registration name to plugin module */ -var registrationNameModules = {}; +var registrationNameModules = {}; /** * Mapping from registration name to event name */ -var registrationNameDependencies = {}; +var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available @@ -234,21 +214,17 @@ var registrationNameDependencies = {}; * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ + function injectEventPluginOrder(injectedEventPluginOrder) { - (function() { - if (!!eventPluginOrder) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) - ); - } - })(); - // Clone the ordering so it cannot be dynamically mutated. + if (!!eventPluginOrder) { + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." + ); + } // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); } - /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. @@ -259,32 +235,34 @@ function injectEventPluginOrder(injectedEventPluginOrder) { * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ + function injectEventPluginsByName(injectedNamesToPlugins) { var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } + var pluginModule = injectedNamesToPlugins[pluginName]; + if ( !namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule ) { - (function() { - if (!!namesToPlugins[pluginName]) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) - ); - } - })(); + if (!!namesToPlugins[pluginName]) { + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } + if (isOrderingDirty) { recomputePluginOrdering(); } @@ -302,6 +280,7 @@ var invokeGuardedCallbackImpl = function( f ) { var funcArgs = Array.prototype.slice.call(arguments, 3); + try { func.apply(context, funcArgs); } catch (error) { @@ -328,7 +307,6 @@ var invokeGuardedCallbackImpl = function( // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if ( @@ -354,52 +332,45 @@ var invokeGuardedCallbackImpl = function( // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebookincubator/create-react-app/issues/3482 // So we preemptively throw with a better message instead. - (function() { - if (!(typeof document !== "undefined")) { - throw ReactError( - Error( - "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." - ) - ); - } - })(); - var evt = document.createEvent("Event"); + if (!(typeof document !== "undefined")) { + 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." + ); + } - // Keeps track of whether the user-provided callback threw an error. We + var evt = document.createEvent("Event"); // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. - var didError = true; - // Keeps track of the value of window.event so that we can reset it + var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. - var windowEvent = window.event; - // Keeps track of the descriptor of window.event to restore it after event + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 + var windowEventDescriptor = Object.getOwnPropertyDescriptor( window, "event" - ); - - // Create an event handler for our fake event. We will synchronously + ); // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - - // We check for window.hasOwnProperty('event') to prevent the + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. + if ( typeof window.event !== "undefined" && window.hasOwnProperty("event") @@ -409,9 +380,7 @@ var invokeGuardedCallbackImpl = function( func.apply(context, funcArgs); didError = false; - } - - // Create a global error event handler. We use this to capture the value + } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of @@ -422,17 +391,20 @@ var invokeGuardedCallbackImpl = function( // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. + + var error; // Use this to track whether the error event is ever called. + var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } + if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. @@ -445,17 +417,14 @@ var invokeGuardedCallbackImpl = function( } } } - } + } // Create a fake event type. - // Create a fake event type. - var evtType = "react-" + (name ? name : "invokeguardedcallback"); + var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - // Attach our event handlers window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); - - // Synchronously dispatch our fake event. If the user-provided function + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); @@ -483,10 +452,10 @@ var invokeGuardedCallbackImpl = function( "See https://fb.me/react-crossorigin-error for more information." ); } + this.onError(error); - } + } // Remove our event listeners - // Remove our event listeners window.removeEventListener("error", handleWindowError); }; @@ -496,21 +465,17 @@ var invokeGuardedCallbackImpl = function( var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// Used by Fiber to simulate a try-catch. var hasError = false; -var caughtError = null; +var caughtError = null; // Used by event system to capture/rethrow the first error. -// Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; - var reporter = { onError: function(error) { hasError = true; caughtError = error; } }; - /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. @@ -524,12 +489,12 @@ var reporter = { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } - /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. @@ -540,6 +505,7 @@ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallbackAndCatchFirstError( name, func, @@ -552,19 +518,21 @@ function invokeGuardedCallbackAndCatchFirstError( f ) { invokeGuardedCallback.apply(this, arguments); + if (hasError) { var error = clearCaughtError(); + if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } - /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ + function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; @@ -573,11 +541,9 @@ function rethrowCaughtError() { throw error; } } - function hasCaughtError() { return hasError; } - function clearCaughtError() { if (hasError) { var error = caughtError; @@ -585,15 +551,11 @@ function clearCaughtError() { caughtError = null; return error; } else { - (function() { - { - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -603,14 +565,13 @@ function clearCaughtError() { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - var warningWithoutStack = function() {}; { warningWithoutStack = function(condition, format) { for ( var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), + args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++ @@ -624,25 +585,28 @@ var warningWithoutStack = function() {}; "message argument" ); } + if (args.length > 8) { // Check before the condition to catch violations early. throw new Error( "warningWithoutStack() currently supports at most 8 arguments." ); } + if (condition) { return; } + if (typeof console !== "undefined") { var argsWithFormat = args.map(function(item) { return "" + item; }); - argsWithFormat.unshift("Warning: " + format); - - // We intentionally don't use spread (or .apply) directly because it + argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 + Function.prototype.apply.call(console.error, console, argsWithFormat); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -663,7 +627,6 @@ var warningWithoutStack$1 = warningWithoutStack; var getFiberCurrentPropsFromNode = null; var getInstanceFromNode = null; var getNodeFromInstance = null; - function setComponentTree( getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, @@ -672,6 +635,7 @@ function setComponentTree( getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode = getInstanceFromNodeImpl; getNodeFromInstance = getNodeFromInstanceImpl; + { !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1( @@ -682,70 +646,69 @@ function setComponentTree( : void 0; } } +var validateEventDispatches; -var validateEventDispatches = void 0; { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, "EventPluginUtils: Invalid `event`.") : void 0; }; } - /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ + function executeDispatch(event, listener, inst) { var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } - /** * Standard/simple iteration through an event's collected dispatches. */ + function executeDispatchesInOrder(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, dispatchListeners, dispatchInstances); } + event._dispatchListeners = null; event._dispatchInstances = null; } - /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. @@ -753,18 +716,21 @@ function executeDispatchesInOrder(event) { * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ + function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } @@ -774,19 +740,19 @@ function executeDispatchesInOrderStopAtTrueImpl(event) { return dispatchInstances; } } + return null; } - /** * @see executeDispatchesInOrderStopAtTrueImpl */ + function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } - /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make @@ -796,17 +762,19 @@ function executeDispatchesInOrderStopAtTrue(event) { * * @return {*} The return value of executing the single dispatch. */ + function executeDirectDispatch(event) { { validateEventDispatches(event); } + var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - (function() { - if (!!Array.isArray(dispatchListener)) { - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); - } - })(); + + if (!!Array.isArray(dispatchListener)) { + throw Error("executeDirectDispatch(...): Invalid `event`."); + } + event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -816,11 +784,11 @@ function executeDirectDispatch(event) { event._dispatchInstances = null; return res; } - /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ + function hasDispatches(event) { return !!event._dispatchListeners; } @@ -839,27 +807,23 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } + current.push(next); return current; } @@ -893,14 +857,15 @@ function forEachAccumulated(arr, cb, scope) { * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ -var eventQueue = null; +var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ + var executeDispatchesAndRelease = function(event) { if (event) { executeDispatchesInOrder(event); @@ -910,6 +875,7 @@ var executeDispatchesAndRelease = function(event) { } } }; + var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(e); }; @@ -917,10 +883,9 @@ var executeDispatchesAndReleaseTopLevel = function(e) { function runEventsInBatch(events) { if (events !== null) { eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more + } // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. + var processingEventQueue = eventQueue; eventQueue = null; @@ -929,16 +894,13 @@ function runEventsInBatch(events) { } forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - (function() { - if (!!eventQueue) { - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) - ); - } - })(); - // This would be a good time to rethrow if any of the event handlers threw. + + if (!!eventQueue) { + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + } // This would be a good time to rethrow if any of the event handlers threw. + rethrowCaughtError(); } @@ -964,11 +926,11 @@ function shouldPreventMouseEvent(name, type, props) { case "onMouseUp": case "onMouseUpCapture": return !!(props.disabled && isInteractive(type)); + default: return false; } } - /** * This is a unified interface for event plugins to be installed and configured. * @@ -995,6 +957,7 @@ function shouldPreventMouseEvent(name, type, props) { /** * Methods for injecting dependencies. */ + var injection = { /** * @param {array} InjectedEventPluginOrder @@ -1007,47 +970,48 @@ var injection = { */ injectEventPluginsByName: injectEventPluginsByName }; - /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ -function getListener(inst, registrationName) { - var listener = void 0; - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not +function getListener(inst, registrationName) { + var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon + var stateNode = inst.stateNode; + if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } + var props = getFiberCurrentPropsFromNode(stateNode); + if (!props) { // Work in progress. return null; } + listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - (function() { - if (!(!listener || typeof listener === "function")) { - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) - ); - } - })(); + + if (!(!listener || typeof listener === "function")) { + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + return listener; } - /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. @@ -1055,28 +1019,35 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ + function extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = null; + for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; + if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); + if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } + return events; } @@ -1084,13 +1055,15 @@ function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); runEventsInBatch(events); } @@ -1098,8 +1071,11 @@ function runExtractedPluginEventsInBatch( var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + var HostComponent = 5; var HostText = 6; var Fragment = 7; @@ -1113,101 +1089,111 @@ var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; -var DehydratedSuspenseComponent = 18; +var DehydratedFragment = 18; var SuspenseListComponent = 19; var FundamentalComponent = 20; +var ScopeComponent = 21; function getParent(inst) { do { - inst = inst.return; - // TODO: If this is a HostRoot we might want to bail out. + inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); + if (inst) { return inst; } + return null; } - /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ + function getLowestCommonAncestor(instA, instB) { var depthA = 0; + for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } + var depthB = 0; + for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; - } + } // If A is deeper, crawl up. - // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; - } + } // If B is deeper, crawl up. - // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; - } + } // Walk in lockstep until we find a match. - // Walk in lockstep until we find a match. var depth = depthA; + while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } + instA = getParent(instA); instB = getParent(instB); } + return null; } - /** * Return if A is an ancestor of B. */ + function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } + instB = getParent(instB); } + return false; } - /** * Return the parent instance of the passed-in instance. */ + function getParentInstance(inst) { return getParent(inst); } - /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ + function traverseTwoPhase(inst, fn, arg) { var path = []; + while (inst) { path.push(inst); inst = getParent(inst); } - var i = void 0; + + var i; + for (i = path.length; i-- > 0; ) { fn(path[i], "captured", arg); } + for (i = 0; i < path.length; i++) { fn(path[i], "bubbled", arg); } } - /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. @@ -1225,7 +1211,6 @@ function listenerAtPhase(inst, event, propagationPhase) { event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } - /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which @@ -1242,13 +1227,16 @@ function listenerAtPhase(inst, event, propagationPhase) { * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ + function accumulateDirectionalDispatches(inst, phase, event) { { !inst ? warningWithoutStack$1(false, "Dispatching inst must not be null") : void 0; } + var listener = listenerAtPhase(inst, event, phase); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1257,7 +1245,6 @@ function accumulateDirectionalDispatches(inst, phase, event) { event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } - /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through @@ -1265,15 +1252,16 @@ function accumulateDirectionalDispatches(inst, phase, event) { * single traversal for the entire collection of events because each event may * have a different target. */ + function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } - /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ + function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; @@ -1281,16 +1269,17 @@ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } - /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ + function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1300,12 +1289,12 @@ function accumulateDispatches(inst, ignoredDirection, event) { } } } - /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ + function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); @@ -1315,7 +1304,6 @@ function accumulateDirectDispatchesSingle(event) { function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } - function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } @@ -1325,13 +1313,12 @@ function accumulateDirectDispatches(events) { } /* eslint valid-typeof: 0 */ - var EVENT_POOL_SIZE = 10; - /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ + var EventInterface = { type: null, target: null, @@ -1356,7 +1343,6 @@ function functionThatReturnsTrue() { function functionThatReturnsFalse() { return false; } - /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. @@ -1375,6 +1361,7 @@ function functionThatReturnsFalse() { * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ + function SyntheticEvent( dispatchConfig, targetInst, @@ -1393,16 +1380,19 @@ function SyntheticEvent( this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; - var Interface = this.constructor.Interface; + for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } + { delete this[propName]; // this has a getter/setter for warnings } + var normalize = Interface[propName]; + if (normalize) { this[propName] = normalize(nativeEvent); } else { @@ -1418,11 +1408,13 @@ function SyntheticEvent( nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } + this.isPropagationStopped = functionThatReturnsFalse; return this; } @@ -1431,6 +1423,7 @@ Object.assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; + if (!event) { return; } @@ -1440,11 +1433,12 @@ Object.assign(SyntheticEvent.prototype, { } else if (typeof event.returnValue !== "unknown") { event.returnValue = false; } + this.isDefaultPrevented = functionThatReturnsTrue; }, - stopPropagation: function() { var event = this.nativeEvent; + if (!event) { return; } @@ -1484,6 +1478,7 @@ Object.assign(SyntheticEvent.prototype, { */ destructor: function() { var Interface = this.constructor.Interface; + for (var propName in Interface) { { Object.defineProperty( @@ -1493,6 +1488,7 @@ Object.assign(SyntheticEvent.prototype, { ); } } + this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; @@ -1500,6 +1496,7 @@ Object.assign(SyntheticEvent.prototype, { this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; + { Object.defineProperty( this, @@ -1535,35 +1532,33 @@ Object.assign(SyntheticEvent.prototype, { } } }); - SyntheticEvent.Interface = EventInterface; - /** * Helper to reduce boilerplate when creating subclasses. */ + SyntheticEvent.extend = function(Interface) { var Super = this; var E = function() {}; + E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } + Object.assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; - Class.Interface = Object.assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); - return Class; }; addEventPoolingTo(SyntheticEvent); - /** * Helper to nullify syntheticEvent instance properties when destructing * @@ -1571,6 +1566,7 @@ addEventPoolingTo(SyntheticEvent); * @param {?object} getVal * @return {object} defineProperty object */ + function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === "function"; return { @@ -1613,6 +1609,7 @@ function getPooledWarningPropertyDefinition(propName, getVal) { function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; + if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call( @@ -1624,6 +1621,7 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { ); return instance; } + return new EventConstructor( dispatchConfig, targetInst, @@ -1634,16 +1632,15 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - (function() { - if (!(event instanceof EventConstructor)) { - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) - ); - } - })(); + + if (!(event instanceof EventConstructor)) { + throw Error( + "Trying to release an event instance into a pool of a different type." + ); + } + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } @@ -1660,6 +1657,7 @@ function addEventPoolingTo(EventConstructor) { * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ + var ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function(nativeEvent) { return null; // Actually doesn't even look at the native event. @@ -1672,19 +1670,15 @@ var TOP_TOUCH_END = "topTouchEnd"; var TOP_TOUCH_CANCEL = "topTouchCancel"; var TOP_SCROLL = "topScroll"; var TOP_SELECTION_CHANGE = "topSelectionChange"; - function isStartish(topLevelType) { return topLevelType === TOP_TOUCH_START; } - function isMoveish(topLevelType) { return topLevelType === TOP_TOUCH_MOVE; } - function isEndish(topLevelType) { return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL; } - var startDependencies = [TOP_TOUCH_START]; var moveDependencies = [TOP_TOUCH_MOVE]; var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END]; @@ -1713,11 +1707,11 @@ function timestampForTouch(touch) { // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } - /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ + function createTouchRecord(touch) { return { touchActive: true, @@ -1749,11 +1743,10 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - (function() { - if (!(identifier != null)) { - throw ReactError(Error("Touch object is missing identifier.")); - } - })(); + if (!(identifier != null)) { + throw Error("Touch object is missing identifier."); + } + { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1765,22 +1758,26 @@ function getTouchIdentifier(_ref) { ) : void 0; } + return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; + if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1802,6 +1799,7 @@ function recordTouchMove(touch) { function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1832,9 +1830,11 @@ function printTouch(touch) { function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + if (touchBank.length > MAX_TOUCH_BANK) { printed += " (original size: " + touchBank.length + ")"; } + return printed; } @@ -1845,6 +1845,7 @@ var ResponderTouchHistoryStore = { } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; @@ -1852,14 +1853,17 @@ var ResponderTouchHistoryStore = { } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; + if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } + { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; !(activeRecord != null && activeRecord.touchActive) @@ -1869,7 +1873,6 @@ var ResponderTouchHistoryStore = { } } }, - touchHistory: touchHistory }; @@ -1880,23 +1883,19 @@ var ResponderTouchHistoryStore = { * * @return {*|array<*>} An accumulation of items. */ + function accumulate(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulate(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { return current.concat(next); } @@ -1912,17 +1911,19 @@ function accumulate(current, next) { * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ -var responderInst = null; +var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ + var trackedTouchCount = 0; var changeResponder = function(nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; + if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange( oldResponderInst, @@ -2025,7 +2026,6 @@ var eventTypes = { dependencies: [] } }; - /** * * Responder System: @@ -2228,17 +2228,15 @@ function setResponderAndExtractTransfer( ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder - : eventTypes.scrollShouldSetResponder; + : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. - // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst - : getLowestCommonAncestor(responderInst, targetInst); - - // When capturing/bubbling the "shouldSet" event, we want to skip the target + : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. + var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent.getPooled( shouldSetEventType, @@ -2247,12 +2245,15 @@ function setResponderAndExtractTransfer( nativeEventTarget ); shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; + if (skipOverBubbleShouldSetFrom) { accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { accumulateTwoPhaseDispatches(shouldSetEvent); } + var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent); + if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } @@ -2260,7 +2261,8 @@ function setResponderAndExtractTransfer( if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } - var extracted = void 0; + + var extracted; var grantEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, wantsResponderInst, @@ -2268,9 +2270,9 @@ function setResponderAndExtractTransfer( nativeEventTarget ); grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; - accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch(grantEvent) === true; + if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderTerminationRequest, @@ -2284,6 +2286,7 @@ function setResponderAndExtractTransfer( var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent); + if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } @@ -2314,9 +2317,9 @@ function setResponderAndExtractTransfer( extracted = accumulate(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } + return extracted; } - /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer @@ -2325,10 +2328,10 @@ function setResponderAndExtractTransfer( * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ + function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return ( - topLevelInst && - // responderIgnoreScroll: We are trying to migrate away from specifically + topLevelInst && // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead ((topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll) || @@ -2337,7 +2340,6 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { isMoveish(topLevelType)) ); } - /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. @@ -2345,22 +2347,28 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ + function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; + if (!touches || touches.length === 0) { return true; } + for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; + if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = getInstanceFromNode(target); + if (isAncestor(responderInst, targetInst)) { return false; } } } + return true; } @@ -2369,7 +2377,6 @@ var ResponderEventPlugin = { _getResponder: function() { return responderInst; }, - eventTypes: eventTypes, /** @@ -2381,7 +2388,8 @@ var ResponderEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (isStartish(topLevelType)) { trackedTouchCount += 1; @@ -2389,7 +2397,7 @@ var ResponderEventPlugin = { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ); return null; @@ -2397,7 +2405,6 @@ var ResponderEventPlugin = { } ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); - var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer( topLevelType, @@ -2405,8 +2412,7 @@ var ResponderEventPlugin = { nativeEvent, nativeEventTarget ) - : null; - // Responder may or may not have transferred on a new touch start/move. + : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional @@ -2416,6 +2422,7 @@ var ResponderEventPlugin = { // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). + var isResponderTouchStart = responderInst && isStartish(topLevelType); var isResponderTouchMove = responderInst && isMoveish(topLevelType); var isResponderTouchEnd = responderInst && isEndish(topLevelType); @@ -2451,6 +2458,7 @@ var ResponderEventPlugin = { : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { var finalEvent = ResponderSyntheticEvent.getPooled( finalTouch, @@ -2466,9 +2474,7 @@ var ResponderEventPlugin = { return extracted; }, - GlobalResponderHandler: null, - injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler @@ -2481,14 +2487,12 @@ var ResponderEventPlugin = { } }; -// Module provided by RN: var customBubblingEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customBubblingEventTypes; var customDirectEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customDirectEventTypes; - var ReactNativeBridgeEventPlugin = { eventTypes: {}, @@ -2499,29 +2503,30 @@ var ReactNativeBridgeEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (targetInst == null) { // Probably a node belonging to another renderer's tree. return null; } + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; var directDispatchConfig = customDirectEventTypes[topLevelType]; - (function() { - if (!(bubbleDispatchConfig || directDispatchConfig)) { - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) - ); - } - })(); + + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget ); + if (bubbleDispatchConfig) { accumulateTwoPhaseDispatches(event); } else if (directDispatchConfig) { @@ -2529,6 +2534,7 @@ var ReactNativeBridgeEventPlugin = { } else { return null; } + return event; } }; @@ -2548,12 +2554,13 @@ var ReactNativeEventPluginOrder = [ /** * Inject module for resolving DOM hierarchy and plugin ordering. */ -injection.injectEventPluginOrder(ReactNativeEventPluginOrder); +injection.injectEventPluginOrder(ReactNativeEventPluginOrder); /** * Some important event plugins included by default (without having to require * them). */ + injection.injectEventPluginsByName({ ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin @@ -2561,11 +2568,9 @@ injection.injectEventPluginsByName({ var instanceCache = new Map(); var instanceProps = new Map(); - function precacheFiberNode(hostInst, tag) { instanceCache.set(tag, hostInst); } - function uncacheFiberNode(tag) { instanceCache.delete(tag); instanceProps.delete(tag); @@ -2577,26 +2582,26 @@ function getInstanceFromTag(tag) { function getTagFromInstance(inst) { var tag = inst.stateNode._nativeTag; + if (tag === undefined) { tag = inst.stateNode.canonical._nativeTag; } - (function() { - if (!tag) { - throw ReactError(Error("All native instances should have a tag.")); - } - })(); + + if (!tag) { + throw Error("All native instances should have a tag."); + } + return tag; } function getFiberCurrentPropsFromNode$1(stateNode) { return instanceProps.get(stateNode._nativeTag) || null; } - function updateFiberProps(tag, props) { instanceProps.set(tag, props); } -// Use to restore controlled state after a change event has fired. +var PLUGIN_EVENT_SYSTEM = 1; var restoreImpl = null; var restoreTarget = null; @@ -2606,19 +2611,18 @@ function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { // Unmounted return; } - (function() { - if (!(typeof restoreImpl === "function")) { - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof restoreImpl === "function")) { + 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." + ); + } + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, props); } @@ -2626,17 +2630,17 @@ function restoreStateOfTarget(target) { function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } - function restoreStateIfNeeded() { if (!restoreTarget) { return; } + var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; - restoreStateOfTarget(target); + if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); @@ -2646,8 +2650,7 @@ function restoreStateIfNeeded() { // Re-export dynamic flags from the fbsource version. var _require = require("../shims/ReactFeatureFlags"); - -var debugRenderPhaseSideEffects = _require.debugRenderPhaseSideEffects; +var debugRenderPhaseSideEffects = _require.debugRenderPhaseSideEffects; // The rest of the flags are static for better dead code elimination. var enableUserTimingAPI = true; var enableProfilerTimer = true; @@ -2660,38 +2663,39 @@ var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; var warnAboutDeprecatedLifecycles = true; var enableFlareAPI = false; var enableFundamentalAPI = false; +var enableScopeAPI = false; var warnAboutUnmockedScheduler = true; -var revertPassiveEffectsChange = false; var flushSuspenseFallbacksInTests = true; - var enableSuspenseCallback = false; var warnAboutDefaultPropsOnFunctionComponents = false; var warnAboutStringRefs = false; var disableLegacyContext = false; var disableSchedulerTimeoutBasedOnReactExpirationTime = false; - // Only used in www builds. -// Used as a way to call batchedUpdates when we don't have a reference to +// Flow magic to verify the exports of this file match the original version. + // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. - // Defaults + var batchedUpdatesImpl = function(fn, bookkeeping) { return fn(bookkeeping); }; + var flushDiscreteUpdatesImpl = function() {}; -var isInsideEventHandler = false; +var isInsideEventHandler = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React @@ -2707,7 +2711,9 @@ function batchedUpdates(fn, bookkeeping) { // fully completes before restoring state. return fn(bookkeeping); } + isInsideEventHandler = true; + try { return batchedUpdatesImpl(fn, bookkeeping); } finally { @@ -2715,6 +2721,7 @@ function batchedUpdates(fn, bookkeeping) { finishEventHandler(); } } +// This is for the React Flare event system function setBatchingImplementation( _batchedUpdatesImpl, @@ -2730,10 +2737,9 @@ function setBatchingImplementation( * Version of `ReactBrowserEventEmitter` that works on the receiving side of a * serialized worker boundary. */ - // Shared default empty native event - conserve memory. -var EMPTY_NATIVE_EVENT = {}; +var EMPTY_NATIVE_EVENT = {}; /** * Selects a subsequence of `Touch`es, without destroying `touches`. * @@ -2741,14 +2747,16 @@ var EMPTY_NATIVE_EVENT = {}; * @param {Array} indices Indices by which to pull subsequence. * @return {Array} Subsequence of touch objects. */ + var touchSubsequence = function(touches, indices) { var ret = []; + for (var i = 0; i < indices.length; i++) { ret.push(touches[indices[i]]); } + return ret; }; - /** * TODO: Pool all of this. * @@ -2760,27 +2768,32 @@ var touchSubsequence = function(touches, indices) { * @param {Array} indices Indices to remove from `touches`. * @return {Array} Subsequence of removed touch objects. */ + var removeTouchesAtIndices = function(touches, indices) { - var rippedOut = []; - // use an unsafe downcast to alias to nullable elements, + var rippedOut = []; // use an unsafe downcast to alias to nullable elements, // so we can delete and then compact. + var temp = touches; + for (var i = 0; i < indices.length; i++) { var index = indices[i]; rippedOut.push(touches[index]); temp[index] = null; } + var fillAt = 0; + for (var j = 0; j < temp.length; j++) { var cur = temp[j]; + if (cur !== null) { temp[fillAt++] = cur; } } + temp.length = fillAt; return rippedOut; }; - /** * Internal version of `receiveEvent` in terms of normalized (non-tag) * `rootNodeID`. @@ -2791,6 +2804,7 @@ var removeTouchesAtIndices = function(touches, indices) { * @param {TopLevelType} topLevelType Top level type of event. * @param {?object} nativeEventParam Object passed from native. */ + function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; var inst = getInstanceFromTag(rootNodeID); @@ -2799,13 +2813,12 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - nativeEvent.target + nativeEvent.target, + PLUGIN_EVENT_SYSTEM ); - }); - // React Native doesn't use ReactControlledComponent but if it did, here's + }); // React Native doesn't use ReactControlledComponent but if it did, here's // where it would do it. } - /** * Publicly exposed method on module for native objc to invoke when a top * level event is extracted. @@ -2813,10 +2826,10 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { * @param {TopLevelType} topLevelType Top level type of event. * @param {object} nativeEventParam Object passed from native. */ + function receiveEvent(rootNodeID, topLevelType, nativeEventParam) { _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); } - /** * Simple multi-wrapper around `receiveEvent` that is intended to receive an * efficient representation of `Touch` objects, and other information that @@ -2841,6 +2854,7 @@ function receiveEvent(rootNodeID, topLevelType, nativeEventParam) { * Web desktop polyfills only need to construct a fake touch event with * identifier 0, also abandoning traditional click handlers. */ + function receiveTouches(eventTopLevelType, touches, changedIndices) { var changedTouches = eventTopLevelType === "topTouchEnd" || @@ -2849,14 +2863,15 @@ function receiveTouches(eventTopLevelType, touches, changedIndices) { : touchSubsequence(touches, changedIndices); for (var jj = 0; jj < changedTouches.length; jj++) { - var touch = changedTouches[jj]; - // Touch objects can fulfill the role of `DOM` `Event` objects if we set + var touch = changedTouches[jj]; // Touch objects can fulfill the role of `DOM` `Event` objects if we set // the `changedTouches`/`touches`. This saves allocations. + touch.changedTouches = changedTouches; touch.touches = touches; var nativeEvent = touch; var rootNodeID = null; var target = nativeEvent.target; + if (target !== null && target !== undefined) { if (target < 1) { { @@ -2868,8 +2883,8 @@ function receiveTouches(eventTopLevelType, touches, changedIndices) { } else { rootNodeID = target; } - } - // $FlowFixMe Shouldn't we *not* call it if rootNodeID is null? + } // $FlowFixMe Shouldn't we *not* call it if rootNodeID is null? + _receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); } } @@ -2889,21 +2904,19 @@ var ReactNativeGlobalResponderHandler = { } }; -// Module provided by RN: /** * Register the event emitter with the native bridge */ + ReactNativePrivateInterface.RCTEventEmitter.register({ receiveEvent: receiveEvent, receiveTouches: receiveTouches }); - setComponentTree( getFiberCurrentPropsFromNode$1, getInstanceFromTag, getTagFromInstance ); - ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactNativeGlobalResponderHandler ); @@ -2933,16 +2946,16 @@ function set(key, value) { } var ReactSharedInternals = - React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -// Prevent newer renderers from RTE when used with older react package versions. + React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentDispatcher")) { ReactSharedInternals.ReactCurrentDispatcher = { current: null }; } + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null @@ -2952,7 +2965,6 @@ if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === "function" && Symbol.for; - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 0xeacb; @@ -2961,8 +2973,7 @@ var REACT_STRICT_MODE_TYPE = hasSymbol : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; -// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_CONCURRENT_MODE_TYPE = hasSymbol @@ -2981,32 +2992,107 @@ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 0xead6; - +var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } + var maybeIterator = (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { return maybeIterator; } + return null; } +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = warningWithoutStack$1; + +{ + warning = function(condition, format) { + if (condition) { + return; + } + + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args + + for ( + var _len = arguments.length, + args = new Array(_len > 2 ? _len - 2 : 0), + _key = 2; + _key < _len; + _key++ + ) { + args[_key - 2] = arguments[_key]; + } + + warningWithoutStack$1.apply( + void 0, + [false, format + "%s"].concat(args, [stack]) + ); + }; +} + +var warning$1 = warning; + +var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; - function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then( + function(moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; -function getWrappedName(outerType, innerType, wrapperName) { + { + if (defaultExport === undefined) { + 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 + ); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, + function(error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + } + ); + } +} + +function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ""; return ( outerType.displayName || @@ -3019,6 +3105,7 @@ function getComponentName(type) { // Host root, text node or just invalid type. return null; } + { if (typeof type.tag === "number") { warningWithoutStack$1( @@ -3028,116 +3115,169 @@ function getComponentName(type) { ); } } + if (typeof type === "function") { return type.displayName || type.name || null; } + if (typeof type === "string") { return type; } + switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; + case REACT_PORTAL_TYPE: return "Portal"; + case REACT_PROFILER_TYPE: return "Profiler"; + case REACT_STRICT_MODE_TYPE: return "StrictMode"; + case REACT_SUSPENSE_TYPE: return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } + if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return "Context.Consumer"; + case REACT_PROVIDER_TYPE: return "Context.Provider"; + case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: return getComponentName(type.type); + case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); + if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; } } } + return null; } // Don't change these two values. They're used by React Dev Tools. -var NoEffect = /* */ 0; -var PerformedWork = /* */ 1; - -// You can change the rest (and add more). -var Placement = /* */ 2; -var Update = /* */ 4; -var PlacementAndUpdate = /* */ 6; -var Deletion = /* */ 8; -var ContentReset = /* */ 16; -var Callback = /* */ 32; -var DidCapture = /* */ 64; -var Ref = /* */ 128; -var Snapshot = /* */ 256; -var Passive = /* */ 512; - -// Passive & Update & Callback & Ref & Snapshot -var LifecycleEffectMask = /* */ 932; - -// Union of all host effects -var HostEffectMask = /* */ 1023; - -var Incomplete = /* */ 1024; -var ShouldCapture = /* */ 2048; +var NoEffect = + /* */ + 0; +var PerformedWork = + /* */ + 1; // You can change the rest (and add more). + +var Placement = + /* */ + 2; +var Update = + /* */ + 4; +var PlacementAndUpdate = + /* */ + 6; +var Deletion = + /* */ + 8; +var ContentReset = + /* */ + 16; +var Callback = + /* */ + 32; +var DidCapture = + /* */ + 64; +var Ref = + /* */ + 128; +var Snapshot = + /* */ + 256; +var Passive = + /* */ + 512; +var Hydrating = + /* */ + 1024; +var HydratingAndUpdate = + /* */ + 1028; // Passive & Update & Callback & Ref & Snapshot + +var LifecycleEffectMask = + /* */ + 932; // Union of all host effects + +var HostEffectMask = + /* */ + 2047; +var Incomplete = + /* */ + 2048; +var ShouldCapture = + /* */ + 4096; var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; - -function isFiberMountedImpl(fiber) { +function getNearestMountedFiber(fiber) { var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node.return) { - node = node.return; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; + var nextNode = node; + + do { + node = nextNode; + + if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; } - } + + nextNode = node.return; + } while (nextNode); } else { while (node.return) { node = node.return; } } + if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. - return UNMOUNTED; + + return null; } function isFiberMounted(fiber) { - return isFiberMountedImpl(fiber) === MOUNTED; + return getNearestMountedFiber(fiber) === fiber; } - function isMounted(component) { { var owner = ReactCurrentOwner$1.current; + if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; @@ -3157,90 +3297,93 @@ function isMounted(component) { } var fiber = get(component); + if (!fiber) { return false; } - return isFiberMountedImpl(fiber) === MOUNTED; + + return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { - (function() { - if (!(isFiberMountedImpl(fiber) === MOUNTED)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); - } - })(); + if (!(getNearestMountedFiber(fiber) === fiber)) { + throw Error("Unable to find node on an unmounted component."); + } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; + if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. - var state = isFiberMountedImpl(fiber); - (function() { - if (!(state !== UNMOUNTED)) { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - if (state === MOUNTING) { + var nearestMounted = getNearestMountedFiber(fiber); + + if (!(nearestMounted !== null)) { + throw Error("Unable to find node on an unmounted component."); + } + + if (nearestMounted !== fiber) { return null; } + return fiber; - } - // If we have two possible branches, we'll walk backwards up to the root + } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. + var a = fiber; var b = alternate; + while (true) { var parentA = a.return; + if (parentA === null) { // We're at the root. break; } + var parentB = parentA.alternate; + if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; + if (nextParent !== null) { a = b = nextParent; continue; - } - // If there's no parent, we're at the root. - break; - } + } // If there's no parent, we're at the root. - // If both copies of the parent fiber point to the same child, we can + break; + } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. + if (parentA.child === parentB.child) { var child = parentA.child; + while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } + if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } + child = child.sibling; - } - // We should never have an alternate for any mounting node. So the only + } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); + + { + throw Error("Unable to find node on an unmounted component."); + } } if (a.return !== b.return) { @@ -3258,6 +3401,7 @@ function findCurrentFiberUsingSlowPath(fiber) { // Search parent A's child set var didFindChild = false; var _child = parentA.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3265,17 +3409,21 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentB; break; } + if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } + _child = _child.sibling; } + if (!didFindChild) { // Search parent B's child set _child = parentB.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3283,59 +3431,53 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentA; break; } + if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } + _child = _child.sibling; } - (function() { - if (!didFindChild) { - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) - ); - } - })(); + + if (!didFindChild) { + 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." + ); + } } } - (function() { - if (!(a.alternate === b)) { - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - (function() { - if (!(a.tag === HostRoot)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (!(a.alternate === b)) { + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - })(); + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. + + if (!(a.tag === HostRoot)) { + throw Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; - } - // Otherwise B has to be current branch. + } // Otherwise B has to be current branch. + return alternate; } - function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { return null; - } + } // Next we'll drill down this component to find the first HostComponent/Text. - // Next we'll drill down this component to find the first HostComponent/Text. var node = currentParent; + while (true) { if (node.tag === HostComponent || node.tag === HostText) { return node; @@ -3344,26 +3486,29 @@ function findCurrentHostFiber(parent) { node = node.child; continue; } + if (node === currentParent) { return null; } + while (!node.sibling) { if (!node.return || node.return === currentParent) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. + } // Flow needs the return null here, but ESLint complains about it. // eslint-disable-next-line no-unreachable + return null; } // Modules provided by RN: var emptyObject = {}; - /** * Create a payload that contains all the updates between two sets of props. * @@ -3394,6 +3539,7 @@ function restoreDeletedValuesInNestedArray( ) { if (Array.isArray(node)) { var i = node.length; + while (i-- && removedKeyCount > 0) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3403,16 +3549,20 @@ function restoreDeletedValuesInNestedArray( } } else if (node && removedKeyCount > 0) { var obj = node; + for (var propKey in removedKeys) { if (!removedKeys[propKey]) { continue; } + var nextProp = obj[propKey]; + if (nextProp === undefined) { continue; } var attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3420,6 +3570,7 @@ function restoreDeletedValuesInNestedArray( if (typeof nextProp === "function") { nextProp = true; } + if (typeof nextProp === "undefined") { nextProp = null; } @@ -3438,6 +3589,7 @@ function restoreDeletedValuesInNestedArray( : nextProp; updatePayload[propKey] = nextValue; } + removedKeys[propKey] = false; removedKeyCount--; } @@ -3452,7 +3604,8 @@ function diffNestedArrayProperty( ) { var minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; - var i = void 0; + var i; + for (i = 0; i < minLength; i++) { // Diff any items in the array in the forward direction. Repeated keys // will be overwritten by later values. @@ -3463,6 +3616,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < prevArray.length; i++) { // Clear out all remaining properties. updatePayload = clearNestedProperty( @@ -3471,6 +3625,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < nextArray.length; i++) { // Add all remaining properties. updatePayload = addNestedProperty( @@ -3479,6 +3634,7 @@ function diffNestedArrayProperty( validAttributes ); } + return updatePayload; } @@ -3498,9 +3654,11 @@ function diffNestedProperty( if (nextProp) { return addNestedProperty(updatePayload, nextProp, validAttributes); } + if (prevProp) { return clearNestedProperty(updatePayload, prevProp, validAttributes); } + return updatePayload; } @@ -3521,10 +3679,8 @@ function diffNestedProperty( if (Array.isArray(prevProp)) { return diffProperties( - updatePayload, - // $FlowFixMe - We know that this is always an object when the input is. - ReactNativePrivateInterface.flattenStyle(prevProp), - // $FlowFixMe - We know that this isn't an array because of above flow. + updatePayload, // $FlowFixMe - We know that this is always an object when the input is. + ReactNativePrivateInterface.flattenStyle(prevProp), // $FlowFixMe - We know that this isn't an array because of above flow. nextProp, validAttributes ); @@ -3532,18 +3688,17 @@ function diffNestedProperty( return diffProperties( updatePayload, - prevProp, - // $FlowFixMe - We know that this is always an object when the input is. + prevProp, // $FlowFixMe - We know that this is always an object when the input is. ReactNativePrivateInterface.flattenStyle(nextProp), validAttributes ); } - /** * addNestedProperty takes a single set of props and valid attribute * attribute configurations. It processes each prop and adds it to the * updatePayload. */ + function addNestedProperty(updatePayload, nextProp, validAttributes) { if (!nextProp) { return updatePayload; @@ -3565,11 +3720,11 @@ function addNestedProperty(updatePayload, nextProp, validAttributes) { return updatePayload; } - /** * clearNestedProperty takes a single set of props and valid attributes. It * adds a null sentinel to the updatePayload, for each prop key. */ + function clearNestedProperty(updatePayload, prevProp, validAttributes) { if (!prevProp) { return updatePayload; @@ -3588,44 +3743,45 @@ function clearNestedProperty(updatePayload, prevProp, validAttributes) { validAttributes ); } + return updatePayload; } - /** * diffProperties takes two sets of props and a set of valid attributes * and write to updatePayload the values that changed or were deleted. * If no updatePayload is provided, a new one is created and returned if * anything changed. */ + function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { - var attributeConfig = void 0; - var nextProp = void 0; - var prevProp = void 0; + var attributeConfig; + var nextProp; + var prevProp; for (var propKey in nextProps) { attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } prevProp = prevProps[propKey]; - nextProp = nextProps[propKey]; - - // functions are converted to booleans as markers that the associated + nextProp = nextProps[propKey]; // functions are converted to booleans as markers that the associated // events should be sent from native. + if (typeof nextProp === "function") { - nextProp = true; - // If nextProp is not a function, then don't bother changing prevProp + nextProp = true; // If nextProp is not a function, then don't bother changing prevProp // since nextProp will win and go into the updatePayload regardless. + if (typeof prevProp === "function") { prevProp = true; } - } - - // An explicit value of undefined is treated as a null because it overrides + } // An explicit value of undefined is treated as a null because it overrides // any other preceding value. + if (typeof nextProp === "undefined") { nextProp = null; + if (typeof prevProp === "undefined") { prevProp = null; } @@ -3640,7 +3796,6 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // value diffed. Since we're now later in the nested arrays our value is // more important so we need to calculate it and override the existing // value. It doesn't matter if nothing changed, we'll set it anyway. - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case @@ -3656,14 +3811,14 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { : nextProp; updatePayload[propKey] = nextValue; } + continue; } if (prevProp === nextProp) { continue; // nothing changed - } + } // Pattern match on: attributeConfig - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case if (defaultDiffer(prevProp, nextProp)) { @@ -3680,25 +3835,28 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { (typeof attributeConfig.diff === "function" ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + if (shouldUpdate) { var _nextValue = typeof attributeConfig.process === "function" ? attributeConfig.process(nextProp) : nextProp; + (updatePayload || (updatePayload = {}))[propKey] = _nextValue; } } else { // default: fallthrough case when nested properties are defined removedKeys = null; - removedKeyCount = 0; - // We think that attributeConfig is not CustomAttributeConfiguration at + removedKeyCount = 0; // We think that attributeConfig is not CustomAttributeConfiguration at // this point so we assume it must be AttributeConfiguration. + updatePayload = diffNestedProperty( updatePayload, prevProp, nextProp, attributeConfig ); + if (removedKeyCount > 0 && updatePayload) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3708,16 +3866,17 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { removedKeys = null; } } - } - - // Also iterate through all the previous props to catch any that have been + } // Also iterate through all the previous props to catch any that have been // removed and make sure native gets the signal so it can reset them to the // default. + for (var _propKey in prevProps) { if (nextProps[_propKey] !== undefined) { continue; // we've already covered this key in the previous pass } + attributeConfig = validAttributes[_propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3728,10 +3887,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { } prevProp = prevProps[_propKey]; + if (prevProp === undefined) { continue; // was already empty anyway - } - // Pattern match on: attributeConfig + } // Pattern match on: attributeConfig + if ( typeof attributeConfig !== "object" || typeof attributeConfig.diff === "function" || @@ -3740,9 +3900,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // case: CustomAttributeConfiguration | !Object // Flag the leaf property for removal by sending a sentinel. (updatePayload || (updatePayload = {}))[_propKey] = null; + if (!removedKeys) { removedKeys = {}; } + if (!removedKeys[_propKey]) { removedKeys[_propKey] = true; removedKeyCount++; @@ -3758,21 +3920,22 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ); } } + return updatePayload; } - /** * addProperties adds all the valid props to the payload after being processed. */ + function addProperties(updatePayload, props, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, emptyObject, props, validAttributes); } - /** * clearProperties clears all the previous props by adding a null sentinel * to the payload for each valid key. */ + function clearProperties(updatePayload, prevProps, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); @@ -3785,7 +3948,6 @@ function create(props, validAttributes) { validAttributes ); } - function diff(prevProps, nextProps, validAttributes) { return diffProperties( null, // updatePayload @@ -3803,24 +3965,20 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return function() { if (!callback) { return undefined; - } - // This protects against createClass() components. + } // This protects against createClass() components. // We don't know if there is code depending on it. // We intentionally don't use isMounted() because even accessing // isMounted property on a React ES6 class will trigger a warning. + if (typeof context.__isMounted === "boolean") { if (!context.__isMounted) { return undefined; } - } - - // FIXME: there used to be other branches that protected + } // FIXME: there used to be other branches that protected // against unmounted host components. But RN host components don't // define isMounted() anymore, so those checks didn't do anything. - // They caused false positive warning noise so we removed them: // https://github.com/facebook/react-native/issues/18868#issuecomment-413579095 - // However, this means that the callback is NOT guaranteed to be safe // for host components. The solution we should implement is to make // UIManager.measure() and similar calls truly cancelable. Then we @@ -3829,7 +3987,6 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return callback.apply(context, arguments); }; } - function throwOnStylesProp(component, props) { if (props.styles !== undefined) { var owner = component._owner || null; @@ -3839,6 +3996,7 @@ function throwOnStylesProp(component, props) { name + "`, did " + "you mean `style` (singular)?"; + if (owner && owner.constructor && owner.constructor.displayName) { msg += "\n\nCheck the `" + @@ -3846,10 +4004,10 @@ function throwOnStylesProp(component, props) { "` parent " + " component."; } + throw new Error(msg); } } - function warnForStyleProps(props, validAttributes) { for (var key in validAttributes.style) { if (!(validAttributes[key] || props[key] === undefined)) { @@ -3866,12 +4024,6 @@ function warnForStyleProps(props, validAttributes) { } } -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - // Modules provided by RN: /** * This component defines the same methods as NativeMethodsMixin but without the @@ -3881,119 +4033,103 @@ function _classCallCheck(instance, Constructor) { * ReactNativeFiber). */ -var ReactNativeFiberHostComponent = (function() { - function ReactNativeFiberHostComponent(tag, viewConfig) { - _classCallCheck(this, ReactNativeFiberHostComponent); - - this._nativeTag = tag; - this._children = []; - this.viewConfig = viewConfig; - } - - ReactNativeFiberHostComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); - }; - - ReactNativeFiberHostComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); - }; - - ReactNativeFiberHostComponent.prototype.measure = function measure(callback) { - ReactNativePrivateInterface.UIManager.measure( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - - ReactNativeFiberHostComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - ReactNativePrivateInterface.UIManager.measureInWindow( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; +var ReactNativeFiberHostComponent = + /*#__PURE__*/ + (function() { + function ReactNativeFiberHostComponent(tag, viewConfig) { + this._nativeTag = tag; + this._children = []; + this.viewConfig = viewConfig; + } - ReactNativeFiberHostComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var relativeNode = void 0; + var _proto = ReactNativeFiberHostComponent.prototype; - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } else if ( - /* $FlowFixMe canonical doesn't exist on the node. - I think this branch is dead and will remove it in a followup */ - relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag - ) { - /* $FlowFixMe canonical doesn't exist on the node. - I think this branch is dead and will remove it in a followup */ - relativeNode = relativeToNativeNode.canonical._nativeTag; - } + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); + }; - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + this._nativeTag ); + }; - return; - } + _proto.measure = function measure(callback) { + ReactNativePrivateInterface.UIManager.measure( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactNativePrivateInterface.UIManager.measureLayout( - this._nativeTag, - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; + _proto.measureInWindow = function measureInWindow(callback) { + ReactNativePrivateInterface.UIManager.measureInWindow( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) /* currently unused */ { - warnForStyleProps(nativeProps, this.viewConfig.validAttributes); - } + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } - var updatePayload = create(nativeProps, this.viewConfig.validAttributes); + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( + ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, - this.viewConfig.uiViewClassName, - updatePayload + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); - } - }; + }; + + _proto.setNativeProps = function setNativeProps(nativeProps) { + { + warnForStyleProps(nativeProps, this.viewConfig.validAttributes); + } + + var updatePayload = create(nativeProps, this.viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + this._nativeTag, + this.viewConfig.uiViewClassName, + updatePayload + ); + } + }; - return ReactNativeFiberHostComponent; -})(); + return ReactNativeFiberHostComponent; + })(); // eslint-disable-next-line no-unused-expressions -// Renderers that don't support persistence // can re-export everything from this module. function shim() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} - -// Persistence (when unsupported) + { + throw Error( + "The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Persistence (when unsupported) + var supportsPersistence = false; var cloneInstance = shim; var cloneFundamentalInstance = shim; @@ -4004,22 +4140,15 @@ var replaceContainerChildren = shim; var cloneHiddenInstance = shim; var cloneHiddenTextInstance = shim; -// Renderers that don't support hydration // can re-export everything from this module. function shim$1() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} - -// Hydration (when unsupported) + { + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Hydration (when unsupported) var supportsHydration = false; var canHydrateInstance = shim$1; @@ -4032,7 +4161,10 @@ var getNextHydratableSibling = shim$1; var getFirstHydratableChild = shim$1; var hydrateInstance = shim$1; var hydrateTextInstance = shim$1; +var hydrateSuspenseInstance = shim$1; var getNextHydratableInstanceAfterSuspenseInstance = shim$1; +var commitHydratedContainer = shim$1; +var commitHydratedSuspenseInstance = shim$1; var clearSuspenseBoundary = shim$1; var clearSuspenseBoundaryFromContainer = shim$1; var didNotMatchHydratedContainerTextInstance = shim$1; @@ -4046,25 +4178,25 @@ var didNotFindHydratableInstance = shim$1; var didNotFindHydratableTextInstance = shim$1; var didNotFindHydratableSuspenseInstance = shim$1; -// Modules provided by RN: var getViewConfigForType = - ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; // Unused -// Unused - + ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; var UPDATE_SIGNAL = {}; + { Object.freeze(UPDATE_SIGNAL); -} - -// Counter for uniquely identifying views. +} // Counter for uniquely identifying views. // % 10 === 1 means it is a rootTag. // % 2 === 0 means it is a Fabric tag. + var nextReactTag = 3; + function allocateTag() { var tag = nextReactTag; + if (tag % 10 === 1) { tag += 2; } + nextReactTag = tag + 2; return tag; } @@ -4083,7 +4215,6 @@ function recursivelyUncacheFiberNode(node) { function appendInitialChild(parentInstance, child) { parentInstance._children.push(child); } - function createInstance( type, props, @@ -4105,52 +4236,41 @@ function createInstance( } var updatePayload = create(props, viewConfig.validAttributes); - ReactNativePrivateInterface.UIManager.createView( tag, // reactTag viewConfig.uiViewClassName, // viewName rootContainerInstance, // rootTag updatePayload // props ); - var component = new ReactNativeFiberHostComponent(tag, viewConfig); - precacheFiberNode(internalInstanceHandle, tag); - updateFiberProps(tag, props); - - // Not sure how to avoid this cast. Flow is okay if the component is defined + updateFiberProps(tag, props); // Not sure how to avoid this cast. Flow is okay if the component is defined // in the same file but if it's external it can't see the types. + return component; } - function createTextInstance( text, rootContainerInstance, hostContext, internalInstanceHandle ) { - (function() { - if (!hostContext.isInAParentText) { - throw ReactError( - Error("Text strings must be rendered within a component.") - ); - } - })(); + if (!hostContext.isInAParentText) { + throw Error("Text strings must be rendered within a component."); + } var tag = allocateTag(); - ReactNativePrivateInterface.UIManager.createView( tag, // reactTag "RCTRawText", // viewName rootContainerInstance, // rootTag - { text: text } // props + { + text: text + } // props ); - precacheFiberNode(internalInstanceHandle, tag); - return tag; } - function finalizeInitialChildren( parentInstance, type, @@ -4161,10 +4281,9 @@ function finalizeInitialChildren( // Don't send a no-op message over the bridge. if (parentInstance._children.length === 0) { return false; - } - - // Map from child objects to native tags. + } // Map from child objects to native tags. // Either way we need to pass a copy of the Array to prevent it from being frozen. + var nativeTags = parentInstance._children.map(function(child) { return typeof child === "number" ? child // Leaf node (eg text) @@ -4175,14 +4294,13 @@ function finalizeInitialChildren( parentInstance._nativeTag, // containerTag nativeTags // reactTags ); - return false; } - function getRootHostContext(rootContainerInstance) { - return { isInAParentText: false }; + return { + isInAParentText: false + }; } - function getChildHostContext(parentHostContext, type, rootContainerInstance) { var prevIsInAParentText = parentHostContext.isInAParentText; var isInAParentText = @@ -4193,20 +4311,19 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { type === "RCTVirtualText"; if (prevIsInAParentText !== isInAParentText) { - return { isInAParentText: isInAParentText }; + return { + isInAParentText: isInAParentText + }; } else { return parentHostContext; } } - function getPublicInstance(instance) { return instance; } - function prepareForCommit(containerInfo) { // Noop } - function prepareUpdate( instance, type, @@ -4217,22 +4334,17 @@ function prepareUpdate( ) { return UPDATE_SIGNAL; } - function resetAfterCommit(containerInfo) { // Noop } - var isPrimaryRenderer = true; var warnsIfNotActing = true; - var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; var noTimeout = -1; - function shouldDeprioritizeSubtree(type, props) { return false; } - function shouldSetTextContent(type, props) { // TODO (bvaughn) Revisit this decision. // Always returning false simplifies the createInstance() implementation, @@ -4241,14 +4353,11 @@ function shouldSetTextContent(type, props) { // It's not clear to me which is better so I'm deferring for now. // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 return false; -} - -// ------------------- +} // ------------------- // Mutation // ------------------- var supportsMutation = true; - function appendChild(parentInstance, child) { var childTag = typeof child === "number" ? child : child._nativeTag; var children = parentInstance._children; @@ -4257,7 +4366,6 @@ function appendChild(parentInstance, child) { if (index >= 0) { children.splice(index, 1); children.push(child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerTag [index], // moveFromIndices @@ -4268,7 +4376,6 @@ function appendChild(parentInstance, child) { ); } else { children.push(child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerTag [], // moveFromIndices @@ -4279,7 +4386,6 @@ function appendChild(parentInstance, child) { ); } } - function appendChildToContainer(parentInstance, child) { var childTag = typeof child === "number" ? child : child._nativeTag; ReactNativePrivateInterface.UIManager.setChildren( @@ -4287,12 +4393,13 @@ function appendChildToContainer(parentInstance, child) { [childTag] // reactTags ); } - function commitTextUpdate(textInstance, oldText, newText) { ReactNativePrivateInterface.UIManager.updateView( textInstance, // reactTag "RCTRawText", // viewName - { text: newText } // props + { + text: newText + } // props ); } @@ -4305,14 +4412,11 @@ function commitUpdate( internalInstanceHandle ) { var viewConfig = instance.viewConfig; - updateFiberProps(instance._nativeTag, newProps); - - var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( instance._nativeTag, // reactTag @@ -4321,17 +4425,14 @@ function commitUpdate( ); } } - function insertBefore(parentInstance, child, beforeChild) { var children = parentInstance._children; - var index = children.indexOf(child); + var index = children.indexOf(child); // Move existing child or add new child? - // Move existing child or add new child? if (index >= 0) { children.splice(index, 1); var beforeChildIndex = children.indexOf(beforeChild); children.splice(beforeChildIndex, 0, child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [index], // moveFromIndices @@ -4342,10 +4443,9 @@ function insertBefore(parentInstance, child, beforeChild) { ); } else { var _beforeChildIndex = children.indexOf(beforeChild); - children.splice(_beforeChildIndex, 0, child); + children.splice(_beforeChildIndex, 0, child); var childTag = typeof child === "number" ? child : child._nativeTag; - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [], // moveFromIndices @@ -4356,28 +4456,20 @@ function insertBefore(parentInstance, child, beforeChild) { ); } } - function insertInContainerBefore(parentInstance, child, beforeChild) { // TODO (bvaughn): Remove this check when... // We create a wrapper object for the container in ReactNative render() // Or we refactor to remove wrapper objects entirely. // For more info on pros/cons see PR #8560 description. - (function() { - if (!(typeof parentInstance !== "number")) { - throw ReactError( - Error("Container does not support insertBefore operation") - ); - } - })(); + if (!(typeof parentInstance !== "number")) { + throw Error("Container does not support insertBefore operation"); + } } - function removeChild(parentInstance, child) { recursivelyUncacheFiberNode(child); var children = parentInstance._children; var index = children.indexOf(child); - children.splice(index, 1); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [], // moveFromIndices @@ -4387,7 +4479,6 @@ function removeChild(parentInstance, child) { [index] // removeAtIndices ); } - function removeChildFromContainer(parentInstance, child) { recursivelyUncacheFiberNode(child); ReactNativePrivateInterface.UIManager.manageChildren( @@ -4399,15 +4490,17 @@ function removeChildFromContainer(parentInstance, child) { [0] // removeAtIndices ); } - function resetTextContent(instance) { // Noop } - function hideInstance(instance) { var viewConfig = instance.viewConfig; var updatePayload = create( - { style: { display: "none" } }, + { + style: { + display: "none" + } + }, viewConfig.validAttributes ); ReactNativePrivateInterface.UIManager.updateView( @@ -4416,15 +4509,20 @@ function hideInstance(instance) { updatePayload ); } - function hideTextInstance(textInstance) { throw new Error("Not yet implemented."); } - function unhideInstance(instance, props) { var viewConfig = instance.viewConfig; var updatePayload = diff( - Object.assign({}, props, { style: [props.style, { display: "none" }] }), + Object.assign({}, props, { + style: [ + props.style, + { + display: "none" + } + ] + }), props, viewConfig.validAttributes ); @@ -4434,60 +4532,57 @@ function unhideInstance(instance, props) { updatePayload ); } - function unhideTextInstance(textInstance, text) { throw new Error("Not yet implemented."); } - function mountResponderInstance( responder, responderInstance, props, state, - instance, - rootContainerInstance + instance ) { throw new Error("Not yet implemented."); } - function unmountResponderInstance(responderInstance) { throw new Error("Not yet implemented."); } - function getFundamentalComponentInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } - function mountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function shouldUpdateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function updateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function unmountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } +function getInstanceFromNode$1(node) { + throw new Error("Not yet implemented."); +} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; - var describeComponentFrame = function(name, source, ownerName) { var sourceInfo = ""; + if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ""); + { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); + if (match) { var pathBeforeSlash = match[1]; + if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ""); fileName = folderName + "/" + fileName; @@ -4495,10 +4590,12 @@ var describeComponentFrame = function(name, source, ownerName) { } } } + sourceInfo = " (at " + fileName + ":" + source.lineNumber + ")"; } else if (ownerName) { sourceInfo = " (created by " + ownerName + ")"; } + return "\n in " + (name || "Unknown") + sourceInfo; }; @@ -4513,14 +4610,17 @@ function describeFiber(fiber) { case ContextProvider: case ContextConsumer: return ""; + default: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName(fiber.type); var ownerName = null; + if (owner) { ownerName = getComponentName(owner.type); } + return describeComponentFrame(name, source, ownerName); } } @@ -4528,41 +4628,43 @@ function describeFiber(fiber) { function getStackByFiberInDevAndProd(workInProgress) { var info = ""; var node = workInProgress; + do { info += describeFiber(node); node = node.return; } while (node); + return info; } - var current = null; var phase = null; - function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { return getComponentName(owner.type); } } + return null; } - function getCurrentFiberStackInDev() { { if (current === null) { return ""; - } - // Safe because if current fiber exists, we are reconciling, + } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. + return getStackByFiberInDevAndProd(current); } + return ""; } - function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; @@ -4570,7 +4672,6 @@ function resetCurrentFiber() { phase = null; } } - function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; @@ -4578,7 +4679,6 @@ function setCurrentFiber(fiber) { phase = null; } } - function setCurrentPhase(lifeCyclePhase) { { phase = lifeCyclePhase; @@ -4594,28 +4694,26 @@ var supportsUserTiming = 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. + typeof performance.clearMeasures === "function"; // Keep track of current fiber so that we know the path to unwind on pause. // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? -var currentFiber = null; -// If we're in the middle of user code, which fiber and method is it? + +var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). + var currentPhase = null; -var currentPhaseFiber = null; -// Did lifecycle hook schedule an update? This is often a performance problem, +var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. + var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; -var isWaitingForCallback = false; -// During commits, we only show a measurement once per method name // to avoid stretch the commit phase with measurement overhead. + var labelsInCurrentCommit = new Set(); var formatMarkName = function(markName) { @@ -4639,14 +4737,14 @@ var clearMark = function(markName) { var endMark = function(label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); + try { performance.measure(formattedLabel, formattedMarkName); - } catch (err) {} - // If previous mark was missing for some reason, this will throw. + } catch (err) {} // If previous mark was missing for some reason, this will throw. // This could only happen if React crashed in an unexpected place earlier. // Don't pile on with more errors. - // Clear marks immediately to avoid growing buffer. + performance.clearMarks(formattedMarkName); performance.clearMeasures(formattedLabel); }; @@ -4677,8 +4775,8 @@ var beginFiberMark = function(fiber, phase) { // want to stretch the commit phase beyond necessary. return false; } - labelsInCurrentCommit.add(label); + labelsInCurrentCommit.add(label); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; @@ -4715,6 +4813,7 @@ var shouldIgnoreFiber = function(fiber) { case ContextConsumer: case Mode: return true; + default: return false; } @@ -4724,6 +4823,7 @@ var clearPendingPhaseMeasurement = function() { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } + currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; @@ -4733,10 +4833,12 @@ var pauseTimers = function() { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; + while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } + fiber = fiber.return; } }; @@ -4745,6 +4847,7 @@ var resumeTimersRecursively = function(fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } + if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } @@ -4762,12 +4865,12 @@ function recordEffect() { effectCountInCurrentCommit++; } } - function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } + if ( currentPhase !== null && currentPhase !== "componentWillMount" && @@ -4778,143 +4881,125 @@ function recordScheduleUpdate() { } } -function startRequestCallbackTimer() { - if (enableUserTimingAPI) { - if (supportsUserTiming && !isWaitingForCallback) { - isWaitingForCallback = true; - beginMark("(Waiting for async callback...)"); - } - } -} - -function stopRequestCallbackTimer(didExpire) { - if (enableUserTimingAPI) { - if (supportsUserTiming) { - isWaitingForCallback = false; - var warning = didExpire - ? "Update expired; will flush synchronously" - : null; - endMark( - "(Waiting for async callback...)", - "(Waiting for async callback...)", - warning - ); - } - } -} - function startWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, this is the fiber to unwind from. + } // If we pause, this is the fiber to unwind from. + currentFiber = fiber; + if (!beginFiberMark(fiber, null)) { return; } + fiber._debugIsCurrentlyTiming = true; } } - function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // Remember we shouldn't complete measurement for this fiber. + } // Remember we shouldn't complete measurement for this fiber. // Otherwise flamechart will be deep even for small updates. + fiber._debugIsCurrentlyTiming = false; clearFiberMark(fiber, null); } } - function stopWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; endFiberMark(fiber, null, null); } } - function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; var warning = - fiber.tag === SuspenseComponent || - fiber.tag === DehydratedSuspenseComponent + fiber.tag === SuspenseComponent ? "Rendering was suspended" : "An error was thrown inside this error boundary"; endFiberMark(fiber, null, warning); } } - function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + clearPendingPhaseMeasurement(); + if (!beginFiberMark(fiber, phase)) { return; } + currentPhaseFiber = fiber; currentPhase = phase; } } - function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? "Scheduled a cascading update" : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } + currentPhase = null; currentPhaseFiber = null; } } - function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; + if (!supportsUserTiming) { return; } - commitCountInCurrentWorkLoop = 0; - // This is top level call. + + commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. - beginMark("(React Tree Reconciliation)"); - // Resume any measurements that were in progress during the last loop. + + beginMark("(React Tree Reconciliation)"); // Resume any measurements that were in progress during the last loop. + resumeTimers(); } } - function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var warning = null; + if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = "A top-level update interrupted the previous render"; @@ -4926,28 +5011,28 @@ function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { } else if (commitCountInCurrentWorkLoop > 1) { warning = "There were cascading updates"; } + commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? "(React Tree Reconciliation: Completed Root)" - : "(React Tree Reconciliation: Yielded)"; - // Pause any measurements until the next loop. + : "(React Tree Reconciliation: Yielded)"; // Pause any measurements until the next loop. + pauseTimers(); endMark(label, "(React Tree Reconciliation)", warning); } } - function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark("(Committing Changes)"); } } - function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { @@ -4955,35 +5040,36 @@ function stopCommitTimer() { } var warning = null; + if (hasScheduledUpdateInCurrentCommit) { warning = "Lifecycle hook scheduled a cascading update"; } else if (commitCountInCurrentWorkLoop > 0) { warning = "Caused by a cascading update in earlier commit"; } + hasScheduledUpdateInCurrentCommit = false; commitCountInCurrentWorkLoop++; isCommitting = false; labelsInCurrentCommit.clear(); - endMark("(Committing Changes)", "(Committing Changes)", warning); } } - function startCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Snapshot Effects)"); } } - function stopCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -4993,22 +5079,22 @@ function stopCommitSnapshotEffectsTimer() { ); } } - function startCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Host Effects)"); } } - function stopCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5018,22 +5104,22 @@ function stopCommitHostEffectsTimer() { ); } } - function startCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Calling Lifecycle Methods)"); } } - function stopCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5045,8 +5131,7 @@ function stopCommitLifeCyclesTimer() { } var valueStack = []; - -var fiberStack = void 0; +var fiberStack; { fiberStack = []; @@ -5065,6 +5150,7 @@ function pop(cursor, fiber) { { warningWithoutStack$1(false, "Unexpected pop."); } + return; } @@ -5075,7 +5161,6 @@ function pop(cursor, fiber) { } cursor.current = valueStack[index]; - valueStack[index] = null; { @@ -5087,7 +5172,6 @@ function pop(cursor, fiber) { function push(cursor, value, fiber) { index++; - valueStack[index] = cursor.current; { @@ -5097,24 +5181,24 @@ function push(cursor, value, fiber) { cursor.current = value; } -var warnedAboutMissingGetChildContext = void 0; +var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; + { Object.freeze(emptyContextObject); -} +} // A cursor to the current merged context object on the stack. -// A cursor to the current merged context object on the stack. -var contextStackCursor = createCursor(emptyContextObject); -// A cursor to a boolean indicating whether the context has changed. -var didPerformWorkStackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. +var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. + +var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. + var previousContext = emptyContextObject; function getUnmaskedContext( @@ -5132,6 +5216,7 @@ function getUnmaskedContext( // previous (parent) context instead for a context provider. return previousContext; } + return contextStackCursor.current; } } @@ -5152,14 +5237,15 @@ function getMaskedContext(workInProgress, unmaskedContext) { } else { var type = workInProgress.type; var contextTypes = type.contextTypes; + if (!contextTypes) { return emptyContextObject; - } - - // Avoid recreating masked context unless unmasked context has changed. + } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. + var instance = workInProgress.stateNode; + if ( instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext @@ -5168,6 +5254,7 @@ function getMaskedContext(workInProgress, unmaskedContext) { } var context = {}; + for (var key in contextTypes) { context[key] = unmaskedContext[key]; } @@ -5181,10 +5268,9 @@ function getMaskedContext(workInProgress, unmaskedContext) { name, getCurrentFiberStackInDev ); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. + if (instance) { cacheContext(workInProgress, unmaskedContext, context); } @@ -5232,15 +5318,11 @@ function pushTopLevelContextObject(fiber, context, didChange) { if (disableLegacyContext) { return; } else { - (function() { - if (!(contextStackCursor.current === emptyContextObject)) { - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(contextStackCursor.current === emptyContextObject)) { + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." + ); + } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -5252,10 +5334,9 @@ function processChildContext(fiber, type, parentContext) { return parentContext; } else { var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== "function") { { var componentName = getComponentName(type) || "Unknown"; @@ -5272,41 +5353,42 @@ function processChildContext(fiber, type, parentContext) { ); } } + return parentContext; } - var childContext = void 0; + var childContext; + { setCurrentPhase("getChildContext"); } + startPhaseTimer(fiber, "getChildContext"); childContext = instance.getChildContext(); stopPhaseTimer(); + { setCurrentPhase(null); } + for (var contextKey in childContext) { - (function() { - if (!(contextKey in childContextTypes)) { - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) - ); - } - })(); + if (!(contextKey in childContextTypes)) { + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } } + { var name = getComponentName(type) || "Unknown"; checkPropTypes( childContextTypes, childContext, "child context", - name, - // In practice, there is one case in which we won't get a stack. It's when + name, // In practice, there is one case in which we won't get a stack. It's when // somebody calls unstable_renderSubtreeIntoContainer() and we process // context from the parent component instance. The stack will be missing // because it's outside of the reconciliation, and so the pointer has not @@ -5315,7 +5397,7 @@ function processChildContext(fiber, type, parentContext) { ); } - return Object.assign({}, parentContext, childContext); + return Object.assign({}, parentContext, {}, childContext); } } @@ -5323,16 +5405,15 @@ function pushContextProvider(workInProgress) { if (disableLegacyContext) { return false; } else { - var instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. + var memoizedMergedChildContext = (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - - // Remember the parent context so we can merge with it later. + emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. + previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push( @@ -5340,7 +5421,6 @@ function pushContextProvider(workInProgress) { didPerformWorkStackCursor.current, workInProgress ); - return true; } } @@ -5350,15 +5430,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { return; } else { var instance = workInProgress.stateNode; - (function() { - if (!instance) { - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!instance) { + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." + ); + } if (didChange) { // Merge parent and own context. @@ -5369,13 +5446,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { type, previousContext ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. + pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. + push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { @@ -5391,40 +5467,38 @@ function findCurrentUnmaskedContext(fiber) { } else { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - (function() { - if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + 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." + ); + } var node = fiber; + do { switch (node.tag) { case HostRoot: return node.stateNode.context; + case ClassComponent: { var Component = node.type; + if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } + break; } } + node = node.return; } while (node !== null); - (function() { - { - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -5432,43 +5506,6 @@ var LegacyRoot = 0; var BatchedRoot = 1; var ConcurrentRoot = 2; -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warning = warningWithoutStack$1; - -{ - warning = function(condition, format) { - if (condition) { - return; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - // eslint-disable-next-line react-internal/warning-and-invariant-args - - for ( - var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key]; - } - - warningWithoutStack$1.apply( - undefined, - [false, format + "%s"].concat(args, [stack]) - ); - }; -} - -var warning$1 = warning; - // Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority; @@ -5489,77 +5526,69 @@ if (enableSchedulerTracing) { // Provide explicit error message when production+profiling bundle of e.g. // react-dom is used with production (non-profiling) bundle of // scheduler/tracing - (function() { - if ( - !( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null - ) - ) { - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) - ); - } - })(); + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + 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" + ); + } } -var fakeCallbackNode = {}; - -// Except for NoPriority, these correspond to Scheduler priorities. We use +var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use // ascending numbers so we can compare them like numbers. They start at 90 to // avoid clashing with Scheduler's priorities. + var ImmediatePriority = 99; var UserBlockingPriority = 98; var NormalPriority = 97; var LowPriority = 96; -var IdlePriority = 95; -// NoPriority is the absence of priority. Also React-only. -var NoPriority = 90; +var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only. +var NoPriority = 90; var shouldYield = Scheduler_shouldYield; -var requestPaint = - // Fall back gracefully if we're running an older version of Scheduler. +var requestPaint = // Fall back gracefully if we're running an older version of Scheduler. Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function() {}; - var syncQueue = null; var immediateQueueCallbackNode = null; var isFlushingSyncQueue = false; -var initialTimeMs = Scheduler_now(); - -// If the initial timestamp is reasonably small, use Scheduler's `now` directly. +var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly. // This will be the case for modern browsers that support `performance.now`. In // older browsers, Scheduler falls back to `Date.now`, which returns a Unix // timestamp. In that case, subtract the module initialization time to simulate // the behavior of performance.now and keep our times small enough to fit // within 32 bits. // TODO: Consider lifting this into Scheduler. + var now = initialTimeMs < 10000 ? Scheduler_now : function() { return Scheduler_now() - initialTimeMs; }; - function getCurrentPriorityLevel() { switch (Scheduler_getCurrentPriorityLevel()) { case Scheduler_ImmediatePriority: return ImmediatePriority; + case Scheduler_UserBlockingPriority: return UserBlockingPriority; + case Scheduler_NormalPriority: return NormalPriority; + case Scheduler_LowPriority: return LowPriority; + case Scheduler_IdlePriority: return IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5567,20 +5596,22 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { switch (reactPriorityLevel) { case ImmediatePriority: return Scheduler_ImmediatePriority; + case UserBlockingPriority: return Scheduler_UserBlockingPriority; + case NormalPriority: return Scheduler_NormalPriority; + case LowPriority: return Scheduler_LowPriority; + case IdlePriority: return Scheduler_IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5588,18 +5619,16 @@ function runWithPriority(reactPriorityLevel, fn) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_runWithPriority(priorityLevel, fn); } - function scheduleCallback(reactPriorityLevel, callback, options) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_scheduleCallback(priorityLevel, callback, options); } - function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { - syncQueue = [callback]; - // Flush the queue in the next tick, at the earliest. + syncQueue = [callback]; // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl @@ -5609,19 +5638,21 @@ function scheduleSyncCallback(callback) { // we already scheduled one when we created the queue. syncQueue.push(callback); } + return fakeCallbackNode; } - function cancelCallback(callbackNode) { if (callbackNode !== fakeCallbackNode) { Scheduler_cancelCallback(callbackNode); } } - function flushSyncCallbackQueue() { if (immediateQueueCallbackNode !== null) { - Scheduler_cancelCallback(immediateQueueCallbackNode); + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); } + flushSyncCallbackQueueImpl(); } @@ -5630,12 +5661,14 @@ function flushSyncCallbackQueueImpl() { // Prevent re-entrancy. isFlushingSyncQueue = true; var i = 0; + try { var _isSync = true; var queue = syncQueue; runWithPriority(ImmediatePriority, function() { for (; i < queue.length; i++) { var callback = queue[i]; + do { callback = callback(_isSync); } while (callback !== null); @@ -5646,8 +5679,8 @@ function flushSyncCallbackQueueImpl() { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); - } - // Resume flushing in the next tick + } // Resume flushing in the next tick + Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueue @@ -5660,9 +5693,9 @@ function flushSyncCallbackQueueImpl() { } var NoMode = 0; -var StrictMode = 1; -// TODO: Remove BatchedMode and ConcurrentMode by reading from the root +var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root // tag instead + var BatchedMode = 2; var ConcurrentMode = 4; var ProfileMode = 8; @@ -5672,20 +5705,27 @@ var ProfileMode = 8; // 0b111111111111111111111111111111 var MAX_SIGNED_31_BIT_INT = 1073741823; -var NoWork = 0; -var Never = 1; +var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that +// Never work can be committed in an inconsistent state without tearing the UI. +// The main example is offscreen content, like a hidden subtree. So one possible +// name is Offscreen. However, it also includes dehydrated Suspense boundaries, +// which are inconsistent in the sense that they haven't finished yet, but +// aren't visibly inconsistent because the server rendered HTML matches what the +// hydrated tree would look like. + +var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in +// order to be consistent. + +var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle var Sync = MAX_SIGNED_31_BIT_INT; var Batched = Sync - 1; - var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = Batched - 1; +var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms. -// 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0); } - function expirationTimeToMs(expirationTime) { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } @@ -5702,13 +5742,11 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { bucketSizeMs / UNIT_SIZE ) ); -} - -// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update +} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update // the names to reflect. + var LOW_PRIORITY_EXPIRATION = 5000; var LOW_PRIORITY_BATCH_SIZE = 250; - function computeAsyncExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -5716,7 +5754,6 @@ function computeAsyncExpiration(currentTime) { LOW_PRIORITY_BATCH_SIZE ); } - function computeSuspenseExpiration(currentTime, timeoutMs) { // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time? return computeExpirationBucket( @@ -5724,9 +5761,7 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { timeoutMs, LOW_PRIORITY_BATCH_SIZE ); -} - -// We intentionally set a higher expiration time for interactive updates in +} // We intentionally set a higher expiration time for interactive updates in // dev than in production. // // If the main thread is being blocked so long that you hit the expiration, @@ -5737,9 +5772,9 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { // // In production we opt for better UX at the risk of masking scheduling // problems, by expiring fast. + var HIGH_PRIORITY_EXPIRATION = 500; var HIGH_PRIORITY_BATCH_SIZE = 100; - function computeInteractiveExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -5752,24 +5787,27 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (expirationTime === Sync) { return ImmediatePriority; } - if (expirationTime === Never) { + + if (expirationTime === Never || expirationTime === Idle) { return IdlePriority; } + var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime); + if (msUntil <= 0) { return ImmediatePriority; } + if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) { return UserBlockingPriority; } + if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) { return NormalPriority; - } - - // TODO: Handle LowPriority - + } // TODO: Handle LowPriority // Assume anything lower has idle priority + return IdlePriority; } @@ -5783,15 +5821,17 @@ function is(x, y) { ); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = typeof Object.is === "function" ? Object.is : is; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ + function shallowEqual(objA, objB) { - if (is(objA, objB)) { + if (is$1(objA, objB)) { return true; } @@ -5809,13 +5849,12 @@ function shallowEqual(objA, objB) { if (keysA.length !== keysB.length) { return false; - } + } // Test for A's keys different from B. - // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if ( !hasOwnProperty.call(objB, keysA[i]) || - !is(objA[keysA[i]], objB[keysA[i]]) + !is$1(objA[keysA[i]], objB[keysA[i]]) ) { return false; } @@ -5837,14 +5876,13 @@ function shallowEqual(objA, objB) { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - -var lowPriorityWarning = function() {}; +var lowPriorityWarningWithoutStack = function() {}; { var printWarning = function(format) { for ( var _len = arguments.length, - args = Array(_len > 1 ? _len - 1 : 0), + args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ @@ -5858,9 +5896,11 @@ var lowPriorityWarning = function() {}; format.replace(/%s/g, function() { return args[argIndex++]; }); + if (typeof console !== "undefined") { console.warn(message); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -5869,17 +5909,18 @@ var lowPriorityWarning = function() {}; } catch (x) {} }; - lowPriorityWarning = function(condition, format) { + lowPriorityWarningWithoutStack = function(condition, format) { if (format === undefined) { throw new Error( - "`lowPriorityWarning(condition, format, ...args)` requires a warning " + + "`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning " + "message argument" ); } + if (!condition) { for ( var _len2 = arguments.length, - args = Array(_len2 > 2 ? _len2 - 2 : 0), + args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++ @@ -5887,12 +5928,12 @@ var lowPriorityWarning = function() {}; args[_key2 - 2] = arguments[_key2]; } - printWarning.apply(undefined, [format].concat(args)); + printWarning.apply(void 0, [format].concat(args)); } }; } -var lowPriorityWarning$1 = lowPriorityWarning; +var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack; var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function(fiber, instance) {}, @@ -5905,12 +5946,13 @@ var ReactStrictModeWarnings = { { var findStrictRoot = function(fiber) { var maybeStrictRoot = null; - var node = fiber; + while (node !== null) { if (node.mode & StrictMode) { maybeStrictRoot = node; } + node = node.return; } @@ -5930,9 +5972,8 @@ var ReactStrictModeWarnings = { var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function( @@ -5945,8 +5986,7 @@ var ReactStrictModeWarnings = { } if ( - typeof instance.componentWillMount === "function" && - // Don't warn about react-lifecycles-compat polyfilled components. + typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true ) { pendingComponentWillMountWarnings.push(fiber); @@ -5991,6 +6031,7 @@ var ReactStrictModeWarnings = { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); + if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function(fiber) { componentWillMountUniqueNames.add( @@ -6002,6 +6043,7 @@ var ReactStrictModeWarnings = { } var UNSAFE_componentWillMountUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { UNSAFE_componentWillMountUniqueNames.add( @@ -6013,6 +6055,7 @@ var ReactStrictModeWarnings = { } var componentWillReceivePropsUniqueNames = new Set(); + if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { componentWillReceivePropsUniqueNames.add( @@ -6020,11 +6063,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add( @@ -6032,11 +6075,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); + if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function(fiber) { componentWillUpdateUniqueNames.add( @@ -6044,11 +6087,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { UNSAFE_componentWillUpdateUniqueNames.add( @@ -6056,18 +6099,16 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - - // Finally, we flush all the warnings + } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' + if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); warningWithoutStack$1( false, "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6078,11 +6119,12 @@ var ReactStrictModeWarnings = { var _sortedNames = setToSortedString( UNSAFE_componentWillReceivePropsUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6096,11 +6138,12 @@ var ReactStrictModeWarnings = { var _sortedNames2 = setToSortedString( UNSAFE_componentWillUpdateUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6110,10 +6153,10 @@ var ReactStrictModeWarnings = { if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillMount has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6129,10 +6172,10 @@ var ReactStrictModeWarnings = { componentWillReceivePropsUniqueNames ); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6149,10 +6192,10 @@ var ReactStrictModeWarnings = { if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6164,9 +6207,8 @@ var ReactStrictModeWarnings = { } }; - var pendingLegacyContextWarning = new Map(); + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function( @@ -6174,6 +6216,7 @@ var ReactStrictModeWarnings = { instance ) { var strictRoot = findStrictRoot(fiber); + if (strictRoot === null) { warningWithoutStack$1( false, @@ -6181,9 +6224,8 @@ var ReactStrictModeWarnings = { "This error is likely caused by a bug in React. Please file an issue." ); return; - } + } // Dedup strategy: Warn once per component. - // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } @@ -6199,6 +6241,7 @@ var ReactStrictModeWarnings = { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } + warningsForRoot.push(fiber); } }; @@ -6210,20 +6253,18 @@ var ReactStrictModeWarnings = { uniqueNames.add(getComponentName(fiber.type) || "Component"); didWarnAboutLegacyContext.add(fiber.type); }); - var sortedNames = setToSortedString(uniqueNames); var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); - warningWithoutStack$1( false, - "Legacy context API has been detected within a strict-mode tree: %s" + + "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:" + - "\nhttps://fb.me/react-legacy-context", - strictRootComponentStack, - sortedNames + "\n\nLearn more about this warning here: https://fb.me/react-legacy-context" + + "%s", + sortedNames, + strictRootComponentStack ); }); }; @@ -6239,47 +6280,43 @@ var ReactStrictModeWarnings = { }; } -// Resolves type to a family. +var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -// Used by React Refresh runtime through DevTools Global Hook. - -var resolveFamily = null; -// $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; - var setRefreshHandler = function(handler) { { resolveFamily = handler; } }; - function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } - function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if ( @@ -6291,24 +6328,27 @@ function resolveForwardRefForHotReloading(type) { // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); + if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; + if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } + return syntheticType; } } + return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { @@ -6317,11 +6357,9 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } var prevType = fiber.elementType; - var nextType = element.type; + var nextType = element.type; // If we got here, we know types aren't === equal. - // If we got here, we know types aren't === equal. var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof @@ -6332,8 +6370,10 @@ function isCompatibleFamilyForHotReloading(fiber, element) { if (typeof nextType === "function") { needsCompareFamilies = true; } + break; } + case FunctionComponent: { if (typeof nextType === "function") { needsCompareFamilies = true; @@ -6344,16 +6384,20 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } + break; } + case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { @@ -6363,13 +6407,14 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + default: return false; - } + } // Check if both types have a family and it's the same one. - // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. @@ -6377,50 +6422,52 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } + return false; } } - function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } + if (typeof WeakSet !== "function") { return; } + if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } + failedBoundaries.add(fiber); } } - var scheduleRefresh = function(root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } - var _staleFamilies = update.staleFamilies, - _updatedFamilies = update.updatedFamilies; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function() { scheduleFibersWithFamiliesRecursively( root.current, - _updatedFamilies, - _staleFamilies + updatedFamilies, + staleFamilies ); }); } }; - var scheduleRoot = function(root, element) { { if (root.context !== emptyContextObject) { @@ -6429,8 +6476,11 @@ var scheduleRoot = function(root, element) { // Just ignore. We'll delete this with _renderSubtree code path later. return; } + flushPassiveEffects(); - updateContainerAtExpirationTime(element, root, null, Sync, null); + syncUpdates(function() { + updateContainer(element, root, null, null); + }); } }; @@ -6445,17 +6495,19 @@ function scheduleFibersWithFamiliesRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } @@ -6466,8 +6518,10 @@ function scheduleFibersWithFamiliesRecursively( var needsRender = false; var needsRemount = false; + if (candidateType !== null) { var family = resolveFamily(candidateType); + if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; @@ -6480,6 +6534,7 @@ function scheduleFibersWithFamiliesRecursively( } } } + if (failedBoundaries !== null) { if ( failedBoundaries.has(fiber) || @@ -6492,9 +6547,11 @@ function scheduleFibersWithFamiliesRecursively( if (needsRemount) { fiber._debugNeedsRemount = true; } + if (needsRemount || needsRender) { scheduleWork(fiber, Sync); } + if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively( child, @@ -6502,6 +6559,7 @@ function scheduleFibersWithFamiliesRecursively( staleFamilies ); } + if (sibling !== null) { scheduleFibersWithFamiliesRecursively( sibling, @@ -6539,22 +6597,25 @@ function findHostInstancesForMatchingFibersRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } var didMatch = false; + if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; @@ -6593,26 +6654,32 @@ function findHostInstancesForFiberShallowly(fiber, hostInstances) { fiber, hostInstances ); + if (foundHostInstances) { return; - } - // If we didn't find any host children, fallback to closest host parent. + } // If we didn't find any host children, fallback to closest host parent. + var node = fiber; + while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; + case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; + case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } + if (node.return === null) { throw new Error("Expected to reach root first."); } + node = node.return; } } @@ -6622,30 +6689,35 @@ function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; + while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; - hostInstances.add(node.stateNode); - // There may still be more, so keep searching. + hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === fiber) { return foundHostInstances; } + while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } + return false; } @@ -6654,78 +6726,31 @@ function resolveDefaultProps(Component, baseProps) { // Resolve default props. Taken from ReactElement var props = Object.assign({}, baseProps); var defaultProps = Component.defaultProps; + for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } + return props; } + return baseProps; } - function readLazyComponentType(lazyComponent) { - var status = lazyComponent._status; - var result = lazyComponent._result; - switch (status) { - case Resolved: { - var Component = result; - return Component; - } - case Rejected: { - var error = result; - throw error; - } - case Pending: { - var thenable = result; - throw thenable; - } - default: { - lazyComponent._status = Pending; - var ctor = lazyComponent._ctor; - var _thenable = ctor(); - _thenable.then( - function(moduleObject) { - if (lazyComponent._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === undefined) { - 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 - ); - } - } - lazyComponent._status = Resolved; - lazyComponent._result = defaultExport; - } - }, - function(error) { - if (lazyComponent._status === Pending) { - lazyComponent._status = Rejected; - lazyComponent._result = error; - } - } - ); - // Handle synchronous thenables. - switch (lazyComponent._status) { - case Resolved: - return lazyComponent._result; - case Rejected: - throw lazyComponent._result; - } - lazyComponent._result = _thenable; - throw _thenable; - } + initializeLazyComponentType(lazyComponent); + + if (lazyComponent._status !== Resolved) { + throw lazyComponent._result; } + + return lazyComponent._result; } var valueCursor = createCursor(null); +var rendererSigil; -var rendererSigil = void 0; { // Use this to detect multiple renderers using the same context rendererSigil = {}; @@ -6734,39 +6759,35 @@ var rendererSigil = void 0; var currentlyRenderingFiber = null; var lastContextDependency = null; var lastContextWithAllBitsObserved = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; + { isDisallowedContextReadInDEV = false; } } - function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } - function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } - function pushProvider(providerFiber, nextValue) { var context = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; + { !( context._currentRenderer === undefined || @@ -6783,8 +6804,8 @@ function pushProvider(providerFiber, nextValue) { } } else { push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; + { !( context._currentRenderer2 === undefined || @@ -6801,22 +6822,19 @@ function pushProvider(providerFiber, nextValue) { } } } - function popProvider(providerFiber) { var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - var context = providerFiber.type._context; + if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } - function calculateChangedBits(context, newValue, oldValue) { - if (is(oldValue, newValue)) { + if (is$1(oldValue, newValue)) { // No change return 0; } else { @@ -6835,18 +6853,21 @@ function calculateChangedBits(context, newValue, oldValue) { ) : void 0; } + return changedBits | 0; } } - function scheduleWorkOnParentPath(parent, renderExpirationTime) { // Update the child expiration time of all the ancestors, including // the alternates. var node = parent; + while (node !== null) { var alternate = node.alternate; + if (node.childExpirationTime < renderExpirationTime) { node.childExpirationTime = renderExpirationTime; + if ( alternate !== null && alternate.childExpirationTime < renderExpirationTime @@ -6863,10 +6884,10 @@ function scheduleWorkOnParentPath(parent, renderExpirationTime) { // ancestor path already has sufficient priority. break; } + node = node.return; } } - function propagateContextChange( workInProgress, context, @@ -6874,19 +6895,21 @@ function propagateContextChange( renderExpirationTime ) { var fiber = workInProgress.child; + if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } + while (fiber !== null) { - var nextFiber = void 0; + var nextFiber = void 0; // Visit this fiber. - // Visit this fiber. var list = fiber.dependencies; + if (list !== null) { nextFiber = fiber.child; - var dependency = list.firstContext; + while (dependency !== null) { // Check if the context matches. if ( @@ -6894,22 +6917,23 @@ function propagateContextChange( (dependency.observedBits & changedBits) !== 0 ) { // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var update = createUpdate(renderExpirationTime, null); - update.tag = ForceUpdate; - // TODO: Because we don't have a work-in-progress, this will add the + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. + enqueueUpdate(fiber, update); } if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } + var alternate = fiber.alternate; + if ( alternate !== null && alternate.expirationTime < renderExpirationTime @@ -6917,17 +6941,16 @@ function propagateContextChange( alternate.expirationTime = renderExpirationTime; } - scheduleWorkOnParentPath(fiber.return, renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. - // Mark the expiration time on the list, too. if (list.expirationTime < renderExpirationTime) { list.expirationTime = renderExpirationTime; - } - - // Since we already found a match, we can stop traversing the + } // Since we already found a match, we can stop traversing the // dependency list. + break; } + dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { @@ -6935,26 +6958,36 @@ function propagateContextChange( nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if ( enableSuspenseServerRenderer && - fiber.tag === DehydratedSuspenseComponent + fiber.tag === DehydratedFragment ) { - // If a dehydrated suspense component is in this subtree, we don't know + // If a dehydrated suspense bounudary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is - // mark it as having updates on its children. - if (fiber.expirationTime < renderExpirationTime) { - fiber.expirationTime = renderExpirationTime; + // mark it as having updates. + var parentSuspense = fiber.return; + + if (!(parentSuspense !== null)) { + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); } - var _alternate = fiber.alternate; + + if (parentSuspense.expirationTime < renderExpirationTime) { + parentSuspense.expirationTime = renderExpirationTime; + } + + var _alternate = parentSuspense.alternate; + if ( _alternate !== null && _alternate.expirationTime < renderExpirationTime ) { _alternate.expirationTime = renderExpirationTime; - } - // This is intentionally passing this fiber as the parent + } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. - scheduleWorkOnParentPath(fiber, renderExpirationTime); + + scheduleWorkOnParentPath(parentSuspense, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. @@ -6967,46 +7000,49 @@ function propagateContextChange( } else { // No child. Traverse to next sibling. nextFiber = fiber; + while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } + var sibling = nextFiber.sibling; + if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; - } - // No more siblings. Traverse up. + } // No more siblings. Traverse up. + nextFiber = nextFiber.return; } } + fiber = nextFiber; } } - function prepareToReadContext(workInProgress, renderExpirationTime) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; - var dependencies = workInProgress.dependencies; + if (dependencies !== null) { var firstContext = dependencies.firstContext; + if (firstContext !== null) { if (dependencies.expirationTime >= renderExpirationTime) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); - } - // Reset the work-in-progress list + } // Reset the work-in-progress list + dependencies.firstContext = null; } } } - function readContext(context, observedBits) { { // This warning would fire if you read context inside a Hook like useMemo. @@ -7027,7 +7063,8 @@ function readContext(context, observedBits) { } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { - var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. + var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types. + if ( typeof observedBits !== "number" || observedBits === MAX_SIGNED_31_BIT_INT @@ -7046,17 +7083,12 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - (function() { - if (!(currentlyRenderingFiber !== null)) { - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) - ); - } - })(); + if (!(currentlyRenderingFiber !== null)) { + 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()." + ); + } // This is the first dependency for this component. Create a new list. - // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { expirationTime: NoWork, @@ -7068,6 +7100,7 @@ function readContext(context, observedBits) { lastContextDependency = lastContextDependency.next = contextItem; } } + return isPrimaryRenderer ? context._currentValue : context._currentValue2; } @@ -7147,19 +7180,16 @@ function readContext(context, observedBits) { // updates when preceding updates are skipped, the final result is deterministic // regardless of priority. Intermediate state may vary according to system // resources, but the final state is always the same. - var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; -var CaptureUpdate = 3; - -// Global state that is reset at the beginning of calling `processUpdateQueue`. +var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. -var hasForceUpdate = false; -var didWarnUpdateInsideUpdate = void 0; -var currentlyProcessingQueue = void 0; +var hasForceUpdate = false; +var didWarnUpdateInsideUpdate; +var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; @@ -7186,15 +7216,12 @@ function cloneUpdateQueue(currentQueue) { baseState: currentQueue.baseState, firstUpdate: currentQueue.firstUpdate, lastUpdate: currentQueue.lastUpdate, - // TODO: With resuming, if we bail out and resuse the child tree, we should // keep these effects. firstCapturedUpdate: null, lastCapturedUpdate: null, - firstEffect: null, lastEffect: null, - firstCapturedEffect: null, lastCapturedEffect: null }; @@ -7205,17 +7232,17 @@ function createUpdate(expirationTime, suspenseConfig) { var update = { expirationTime: expirationTime, suspenseConfig: suspenseConfig, - tag: UpdateState, payload: null, callback: null, - next: null, nextEffect: null }; + { update.priority = getCurrentPriorityLevel(); } + return update; } @@ -7233,12 +7260,14 @@ function appendUpdateToQueue(queue, update) { function enqueueUpdate(fiber, update) { // Update queues are created lazily. var alternate = fiber.alternate; - var queue1 = void 0; - var queue2 = void 0; + var queue1; + var queue2; + if (alternate === null) { // There's only one fiber. queue1 = fiber.updateQueue; queue2 = null; + if (queue1 === null) { queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); } @@ -7246,6 +7275,7 @@ function enqueueUpdate(fiber, update) { // There are two owners. queue1 = fiber.updateQueue; queue2 = alternate.updateQueue; + if (queue1 === null) { if (queue2 === null) { // Neither fiber has an update queue. Create new ones. @@ -7266,6 +7296,7 @@ function enqueueUpdate(fiber, update) { } } } + if (queue2 === null || queue1 === queue2) { // There's only a single queue. appendUpdateToQueue(queue1, update); @@ -7280,8 +7311,8 @@ function enqueueUpdate(fiber, update) { } else { // Both queues are non-empty. The last update is the same in both lists, // because of structural sharing. So, only append to one of the lists. - appendUpdateToQueue(queue1, update); - // But we still need to update the `lastUpdate` pointer of queue2. + appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2. + queue2.lastUpdate = update; } } @@ -7304,11 +7335,11 @@ function enqueueUpdate(fiber, update) { } } } - function enqueueCapturedUpdate(workInProgress, update) { // Captured updates go into a separate list, and only on the work-in- // progress queue. var workInProgressQueue = workInProgress.updateQueue; + if (workInProgressQueue === null) { workInProgressQueue = workInProgress.updateQueue = createUpdateQueue( workInProgress.memoizedState @@ -7321,9 +7352,8 @@ function enqueueCapturedUpdate(workInProgress, update) { workInProgress, workInProgressQueue ); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. if (workInProgressQueue.lastCapturedUpdate === null) { // This is the first render phase update workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update; @@ -7335,6 +7365,7 @@ function enqueueCapturedUpdate(workInProgress, update) { function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { var current = workInProgress.alternate; + if (current !== null) { // If the work-in-progress queue is equal to the current queue, // we need to clone it first. @@ -7342,6 +7373,7 @@ function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { queue = workInProgress.updateQueue = cloneUpdateQueue(queue); } } + return queue; } @@ -7355,68 +7387,82 @@ function getStateFromUpdate( ) { switch (update.tag) { case ReplaceState: { - var _payload = update.payload; - if (typeof _payload === "function") { + var payload = update.payload; + + if (typeof payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload.call(instance, prevState, nextProps); + payload.call(instance, prevState, nextProps); } } - var nextState = _payload.call(instance, prevState, nextProps); + + var nextState = payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } + return nextState; - } - // State object - return _payload; + } // State object + + return payload; } + case CaptureUpdate: { workInProgress.effectTag = (workInProgress.effectTag & ~ShouldCapture) | DidCapture; } // Intentional fallthrough + case UpdateState: { - var _payload2 = update.payload; - var partialState = void 0; - if (typeof _payload2 === "function") { + var _payload = update.payload; + var partialState; + + if (typeof _payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload2.call(instance, prevState, nextProps); + _payload.call(instance, prevState, nextProps); } } - partialState = _payload2.call(instance, prevState, nextProps); + + partialState = _payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } } else { // Partial state object - partialState = _payload2; + partialState = _payload; } + if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + return Object.assign({}, prevState, partialState); } + case ForceUpdate: { hasForceUpdate = true; return prevState; } } + return prevState; } @@ -7428,50 +7474,47 @@ function processUpdateQueue( renderExpirationTime ) { hasForceUpdate = false; - queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue); { currentlyProcessingQueue = queue; - } + } // These values may change as we process the queue. - // These values may change as we process the queue. var newBaseState = queue.baseState; var newFirstUpdate = null; - var newExpirationTime = NoWork; + var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result. - // Iterate through the list of updates to compute the result. var update = queue.firstUpdate; var resultState = newBaseState; + while (update !== null) { var updateExpirationTime = update.expirationTime; + if (updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstUpdate === null) { // This is the first skipped update. It will be the first update in // the new list. - newFirstUpdate = update; - // Since this is the first update that was skipped, the current result + newFirstUpdate = update; // Since this is the first update that was skipped, the current result // is the new base state. + newBaseState = resultState; - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < updateExpirationTime) { newExpirationTime = updateExpirationTime; } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. // TODO: We should skip this update if it was already committed but currently // we have no way of detecting the difference between a committed and suspended // update here. - markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); + markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result. - // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -7480,11 +7523,13 @@ function processUpdateQueue( props, instance ); - var _callback = update.callback; - if (_callback !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var callback = update.callback; + + if (callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastEffect === null) { queue.firstEffect = queue.lastEffect = update; } else { @@ -7492,30 +7537,31 @@ function processUpdateQueue( queue.lastEffect = update; } } - } - // Continue to the next update. + } // Continue to the next update. + update = update.next; - } + } // Separately, iterate though the list of captured updates. - // Separately, iterate though the list of captured updates. var newFirstCapturedUpdate = null; update = queue.firstCapturedUpdate; + while (update !== null) { var _updateExpirationTime = update.expirationTime; + if (_updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstCapturedUpdate === null) { // This is the first skipped captured update. It will be the first // update in the new list. - newFirstCapturedUpdate = update; - // If this is the first update that was skipped, the current result is + newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is // the new base state. + if (newFirstUpdate === null) { newBaseState = resultState; } - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < _updateExpirationTime) { newExpirationTime = _updateExpirationTime; } @@ -7530,11 +7576,13 @@ function processUpdateQueue( props, instance ); - var _callback2 = update.callback; - if (_callback2 !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var _callback = update.callback; + + if (_callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastCapturedEffect === null) { queue.firstCapturedEffect = queue.lastCapturedEffect = update; } else { @@ -7543,17 +7591,20 @@ function processUpdateQueue( } } } + update = update.next; } if (newFirstUpdate === null) { queue.lastUpdate = null; } + if (newFirstCapturedUpdate === null) { queue.lastCapturedUpdate = null; } else { workInProgress.effectTag |= Callback; } + if (newFirstUpdate === null && newFirstCapturedUpdate === null) { // We processed every update, without skipping. That means the new base // state is the same as the result state. @@ -7562,15 +7613,15 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; - queue.firstCapturedUpdate = newFirstCapturedUpdate; - - // Set the remaining expiration time to be whatever is remaining in the queue. + queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. + + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; @@ -7580,27 +7631,22 @@ function processUpdateQueue( } function callCallback(callback, context) { - (function() { - if (!(typeof callback === "function")) { - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - callback - ) - ); - } - })(); + if (!(typeof callback === "function")) { + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } - function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } - function commitUpdateQueue( finishedWork, finishedQueue, @@ -7616,53 +7662,50 @@ function commitUpdateQueue( if (finishedQueue.lastUpdate !== null) { finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate; finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate; - } - // Clear the list of captured updates. + } // Clear the list of captured updates. + finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null; - } + } // Commit the effects - // Commit the effects commitUpdateEffects(finishedQueue.firstEffect, instance); finishedQueue.firstEffect = finishedQueue.lastEffect = null; - commitUpdateEffects(finishedQueue.firstCapturedEffect, instance); finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null; } function commitUpdateEffects(effect, instance) { while (effect !== null) { - var _callback3 = effect.callback; - if (_callback3 !== null) { + var callback = effect.callback; + + if (callback !== null) { effect.callback = null; - callCallback(_callback3, instance); + callCallback(callback, instance); } + effect = effect.nextEffect; } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - function requestCurrentSuspenseConfig() { return ReactCurrentBatchConfig.suspense; } var fakeInternalInstance = {}; -var isArray$1 = Array.isArray; - -// React.Component uses a shared frozen object by default. +var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. -var emptyRefsObject = new React.Component().refs; -var didWarnAboutStateAssignmentForComponent = void 0; -var didWarnAboutUninitializedState = void 0; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; -var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; -var didWarnAboutUndefinedDerivedState = void 0; -var warnOnUndefinedDerivedState = void 0; -var warnOnInvalidCallback = void 0; -var didWarnAboutDirectlyAssigningPropsToState = void 0; -var didWarnAboutContextTypeAndContextTypes = void 0; -var didWarnAboutInvalidateContextType = void 0; +var emptyRefsObject = new React.Component().refs; +var didWarnAboutStateAssignmentForComponent; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; { didWarnAboutStateAssignmentForComponent = new Set(); @@ -7673,14 +7716,15 @@ var didWarnAboutInvalidateContextType = void 0; didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function(callback, callerName) { if (callback === null || typeof callback === "function") { return; } + var key = callerName + "_" + callback; + if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); warningWithoutStack$1( @@ -7696,6 +7740,7 @@ var didWarnAboutInvalidateContextType = void 0; warnOnUndefinedDerivedState = function(type, partialState) { if (partialState === undefined) { var componentName = getComponentName(type) || "Component"; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); warningWithoutStack$1( @@ -7706,25 +7751,20 @@ var didWarnAboutInvalidateContextType = void 0; ); } } - }; - - // This is so gross but it's at least non-critical and can be removed if + }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. + Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - (function() { - { - throw ReactError( - Error( - "_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)." - ) - ); - } - })(); + { + 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)." + ); + } } }); Object.freeze(fakeInternalInstance); @@ -7753,22 +7793,21 @@ function applyDerivedStateFromProps( { warnOnUndefinedDerivedState(ctor, partialState); - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + var memoizedState = partialState === null || partialState === undefined ? prevState : Object.assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; - - // Once the update queue is empty, persist the derived state onto the + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. + var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null && workInProgress.expirationTime === NoWork) { updateQueue.baseState = memoizedState; } } - var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { @@ -7780,19 +7819,17 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.payload = payload; + if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, "setState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -7805,7 +7842,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ReplaceState; update.payload = payload; @@ -7814,12 +7850,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "replaceState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -7832,7 +7866,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ForceUpdate; @@ -7840,12 +7873,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "forceUpdate"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); } @@ -7861,6 +7892,7 @@ function checkShouldComponentUpdate( nextContext ) { var instance = workInProgress.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { startPhaseTimer(workInProgress, "shouldComponentUpdate"); var shouldUpdate = instance.shouldComponentUpdate( @@ -7895,6 +7927,7 @@ function checkShouldComponentUpdate( function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; + { var name = getComponentName(ctor) || "Component"; var renderPresent = instance.render; @@ -7970,6 +8003,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (ctor.contextTypes) { warningWithoutStack$1( false, @@ -8016,6 +8050,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ) : void 0; + if ( ctor.prototype && ctor.prototype.isPureReactComponent && @@ -8029,6 +8064,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { getComponentName(ctor) || "A pure component" ); } + var noComponentDidUnmount = typeof instance.componentDidUnmount !== "function"; !noComponentDidUnmount @@ -8139,6 +8175,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { ) : void 0; var _state = instance.state; + if (_state && (typeof _state !== "object" || isArray$1(_state))) { warningWithoutStack$1( false, @@ -8146,6 +8183,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (typeof instance.getChildContext === "function") { !(typeof ctor.childContextTypes === "object") ? warningWithoutStack$1( @@ -8161,9 +8199,10 @@ function checkClassInstance(workInProgress, ctor, newProps) { function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates + set(instance, workInProgress); + { instance._reactInternalInstance = fakeInternalInstance; } @@ -8182,8 +8221,7 @@ function constructClassInstance( { if ("contextType" in ctor) { - var isValid = - // Allow null for conditional declaration + var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && @@ -8191,8 +8229,8 @@ function constructClassInstance( if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + if (contextType === undefined) { addendum = " However, it is set to undefined. " + @@ -8212,6 +8250,7 @@ function constructClassInstance( Object.keys(contextType).join(", ") + "}."; } + warningWithoutStack$1( false, "%s defines an invalid contextType. " + @@ -8233,9 +8272,8 @@ function constructClassInstance( context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } + } // Instantiate twice to help detect side-effects. - // Instantiate twice to help detect side-effects. { if ( debugRenderPhaseSideEffects || @@ -8256,6 +8294,7 @@ function constructClassInstance( { if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); warningWithoutStack$1( @@ -8269,11 +8308,10 @@ function constructClassInstance( componentName ); } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. + } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. + if ( typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function" @@ -8281,6 +8319,7 @@ function constructClassInstance( var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; + if ( typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true @@ -8289,6 +8328,7 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillMount === "function") { foundWillMountName = "UNSAFE_componentWillMount"; } + if ( typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true @@ -8299,6 +8339,7 @@ function constructClassInstance( ) { foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; } + if ( typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true @@ -8307,16 +8348,19 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { foundWillUpdateName = "UNSAFE_componentWillUpdate"; } + if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { var _componentName = getComponentName(ctor) || "Component"; + var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); warningWithoutStack$1( @@ -8324,7 +8368,7 @@ function constructClassInstance( "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://fb.me/react-async-component-lifecycle-hooks", + "https://fb.me/react-unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -8336,10 +8380,9 @@ function constructClassInstance( } } } - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. + if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } @@ -8354,6 +8397,7 @@ function callComponentWillMount(workInProgress, instance) { if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } @@ -8370,6 +8414,7 @@ function callComponentWillMount(workInProgress, instance) { getComponentName(workInProgress.type) || "Component" ); } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } @@ -8382,17 +8427,21 @@ function callComponentWillReceiveProps( ) { var oldState = instance.state; startPhaseTimer(workInProgress, "componentWillReceiveProps"); + if (typeof instance.componentWillReceiveProps === "function") { instance.componentWillReceiveProps(newProps, nextContext); } + if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } + stopPhaseTimer(); if (instance.state !== oldState) { { var componentName = getComponentName(workInProgress.type) || "Component"; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); warningWithoutStack$1( @@ -8404,11 +8453,11 @@ function callComponentWillReceiveProps( ); } } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } -} +} // Invokes the mount life-cycles on a previously never rendered instance. -// Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance( workInProgress, ctor, @@ -8423,8 +8472,8 @@ function mountClassInstance( instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; - var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else if (disableLegacyContext) { @@ -8437,6 +8486,7 @@ function mountClassInstance( { if (instance.state === newProps) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); warningWithoutStack$1( @@ -8465,6 +8515,7 @@ function mountClassInstance( } var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8477,6 +8528,7 @@ function mountClassInstance( } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -8485,20 +8537,20 @@ function mountClassInstance( newProps ); instance.state = workInProgress.memoizedState; - } - - // In order to support react-lifecycles-compat polyfilled components, + } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function") ) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. + updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8523,13 +8575,12 @@ function resumeMountClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = oldProps; - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8544,14 +8595,12 @@ function resumeMountClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8568,10 +8617,10 @@ function resumeMountClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8582,6 +8631,7 @@ function resumeMountClassInstance( ); newState = workInProgress.memoizedState; } + if ( oldProps === newProps && oldState === newState && @@ -8593,6 +8643,7 @@ function resumeMountClassInstance( if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } + return false; } @@ -8627,14 +8678,18 @@ function resumeMountClassInstance( typeof instance.componentWillMount === "function") ) { startPhaseTimer(workInProgress, "componentWillMount"); + if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } + stopPhaseTimer(); } + if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } @@ -8643,24 +8698,20 @@ function resumeMountClassInstance( // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; -} +} // Invokes the update life-cycles and returns false if it shouldn't rerender. -// Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance( current, workInProgress, @@ -8669,16 +8720,15 @@ function updateClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8689,14 +8739,12 @@ function updateClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8713,10 +8761,10 @@ function updateClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8744,6 +8792,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -8752,6 +8801,7 @@ function updateClassInstance( workInProgress.effectTag |= Snapshot; } } + return false; } @@ -8786,17 +8836,22 @@ function updateClassInstance( typeof instance.componentWillUpdate === "function") ) { startPhaseTimer(workInProgress, "componentWillUpdate"); + if (typeof instance.componentWillUpdate === "function") { instance.componentWillUpdate(newProps, newState, nextContext); } + if (typeof instance.UNSAFE_componentWillUpdate === "function") { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } + stopPhaseTimer(); } + if (typeof instance.componentDidUpdate === "function") { workInProgress.effectTag |= Update; } + if (typeof instance.getSnapshotBeforeUpdate === "function") { workInProgress.effectTag |= Snapshot; } @@ -8811,6 +8866,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -8818,40 +8874,38 @@ function updateClassInstance( ) { workInProgress.effectTag |= Snapshot; } - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; } -var didWarnAboutMaps = void 0; -var didWarnAboutGenerators = void 0; -var didWarnAboutStringRefs = void 0; -var ownerHasKeyUseWarning = void 0; -var ownerHasFunctionTypeWarning = void 0; +var didWarnAboutMaps; +var didWarnAboutGenerators; +var didWarnAboutStringRefs; +var ownerHasKeyUseWarning; +var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; - /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ + ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; @@ -8859,30 +8913,29 @@ var warnForMissingKey = function(child) {}; if (child === null || typeof child !== "object") { return; } + if (!child._store || child._store.validated || child.key != null) { return; } - (function() { - if (!(typeof child._store === "object")) { - throw ReactError( - Error( - "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - child._store.validated = true; + if (!(typeof child._store === "object")) { + throw Error( + "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." + ); + } + + child._store.validated = true; var currentComponentErrorInfo = "Each child in a list should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information." + getCurrentFiberStackInDev(); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning$1( false, "Each child in a list should have a unique " + @@ -8896,6 +8949,7 @@ var isArray = Array.isArray; function coerceRef(returnFiber, current$$1, element) { var mixedRef = element.ref; + if ( mixedRef !== null && typeof mixedRef !== "function" && @@ -8906,16 +8960,16 @@ function coerceRef(returnFiber, current$$1, element) { // everyone, because the strict mode case will no longer be relevant if (returnFiber.mode & StrictMode || warnAboutStringRefs) { var componentName = getComponentName(returnFiber.type) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { if (warnAboutStringRefs) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://fb.me/react-strict-mode-string-ref%s", componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber) @@ -8925,14 +8979,14 @@ function coerceRef(returnFiber, current$$1, element) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "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) ); } + didWarnAboutStringRefs[componentName] = true; } } @@ -8940,33 +8994,30 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { var owner = element._owner; - var inst = void 0; + var inst; + if (owner) { var ownerFiber = owner; - (function() { - if (!(ownerFiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) - ); - } - })(); - inst = ownerFiber.stateNode; - } - (function() { - if (!inst) { - throw ReactError( - Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a bug in React. Please file an issue." - ) + + if (!(ownerFiber.tag === ClassComponent)) { + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); } - })(); - var stringRef = "" + mixedRef; - // Check if previous string ref matches new string ref + + inst = ownerFiber.stateNode; + } + + if (!inst) { + throw Error( + "Missing owner for string ref " + + mixedRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + } + + var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + if ( current$$1 !== null && current$$1.ref !== null && @@ -8975,69 +9026,65 @@ function coerceRef(returnFiber, current$$1, element) { ) { return current$$1.ref; } + var ref = function(value) { var refs = inst.refs; + if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = inst.refs = {}; } + if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; + ref._stringRef = stringRef; return ref; } else { - (function() { - if (!(typeof mixedRef === "string")) { - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) - ); - } - })(); - (function() { - if (!element._owner) { - throw ReactError( - Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information." - ) - ); - } - })(); + if (!(typeof mixedRef === "string")) { + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + + if (!element._owner) { + 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." + ); + } } } + return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { if (returnFiber.type !== "textarea") { var addendum = ""; + { addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentFiberStackInDev(); } - (function() { - { - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - (Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." + - addendum - ) - ); - } - })(); + + { + 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 + ); + } } } @@ -9051,38 +9098,39 @@ function warnOnFunctionType() { if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } - ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; + ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning$1( false, "Functions are not valid as a React child. This may happen if " + "you return a Component instead of from render. " + "Or maybe you meant to call this function rather than return it." ); -} - -// This wrapper function exists because I expect to clone the code in each path +} // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. + function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; - } - // Deletions are added in reversed order so we add it to the front. + } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } + childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } @@ -9091,32 +9139,36 @@ function ChildReconciler(shouldTrackSideEffects) { if (!shouldTrackSideEffects) { // Noop. return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by + } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. + var childToDelete = currentFirstChild; + while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } + return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index + // instead. var existingChildren = new Map(); - var existingChild = currentFirstChild; + while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } + existingChild = existingChild.sibling; } + return existingChildren; } @@ -9131,13 +9183,17 @@ function ChildReconciler(shouldTrackSideEffects) { function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; + if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } + var current$$1 = newFiber.alternate; + if (current$$1 !== null) { var oldIndex = current$$1.index; + if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; @@ -9159,6 +9215,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } + return newFiber; } @@ -9188,18 +9245,19 @@ function ChildReconciler(shouldTrackSideEffects) { function updateElement(returnFiber, current$$1, element, expirationTime) { if ( current$$1 !== null && - (current$$1.elementType === element.type || - // Keep this check inline so it only runs on the false path: + (current$$1.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current$$1, element)) ) { // Move based on index var existing = useFiber(current$$1, element.props, expirationTime); existing.ref = coerceRef(returnFiber, current$$1, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { // Insert @@ -9288,16 +9346,19 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } + case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal( newChild, returnFiber.mode, expirationTime ); + _created2.return = returnFiber; return _created2; } @@ -9310,6 +9371,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime, null ); + _created3.return = returnFiber; return _created3; } @@ -9328,7 +9390,6 @@ function ChildReconciler(shouldTrackSideEffects) { function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === "string" || typeof newChild === "number") { @@ -9338,6 +9399,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (key !== null) { return null; } + return updateTextNode( returnFiber, oldFiber, @@ -9359,6 +9421,7 @@ function ChildReconciler(shouldTrackSideEffects) { key ); } + return updateElement( returnFiber, oldFiber, @@ -9369,6 +9432,7 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } } + case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal( @@ -9435,6 +9499,7 @@ function ChildReconciler(shouldTrackSideEffects) { existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment( returnFiber, @@ -9444,6 +9509,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChild.key ); } + return updateElement( returnFiber, _matchedFiber, @@ -9451,11 +9517,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ); } + case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + return updatePortal( returnFiber, _matchedFiber2, @@ -9467,6 +9535,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; + return updateFragment( returnFiber, _matchedFiber3, @@ -9487,32 +9556,37 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } - /** * Warns if there is a duplicate or missing key */ + function warnOnInvalidKey(child, knownKeys) { { if (typeof child !== "object" || child === null) { return knownKeys; } + switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); var key = child.key; + if (typeof key !== "string") { break; } + if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } + if (!knownKeys.has(key)) { knownKeys.add(key); break; } + warning$1( false, "Encountered two children with the same key, `%s`. " + @@ -9523,10 +9597,12 @@ function ChildReconciler(shouldTrackSideEffects) { key ); break; + default: break; } } + return knownKeys; } @@ -9540,7 +9616,6 @@ function ChildReconciler(shouldTrackSideEffects) { // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. - // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in @@ -9548,16 +9623,14 @@ function ChildReconciler(shouldTrackSideEffects) { // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. - { // First, validate keys. var knownKeys = null; + for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9566,11 +9639,11 @@ function ChildReconciler(shouldTrackSideEffects) { var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; @@ -9578,12 +9651,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, newChildren[newIdx], expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -9592,8 +9667,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -9601,7 +9678,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -9612,6 +9691,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -9631,25 +9711,28 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber === null) { continue; } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } + previousNewFiber = _newFiber; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( existingChildren, @@ -9658,6 +9741,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { @@ -9670,12 +9754,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } + previousNewFiber = _newFiber2; } } @@ -9699,24 +9786,19 @@ function ChildReconciler(shouldTrackSideEffects) { ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - (function() { - if (!(typeof iteratorFn === "function")) { - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof iteratorFn === "function")) { + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); + } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if ( - typeof Symbol === "function" && - // $FlowFixMe Flow doesn't know about toStringTag + typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === "Generator" ) { !didWarnAboutGenerators @@ -9730,9 +9812,8 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutGenerators = true; - } + } // Warn about using Maps as children - // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { !didWarnAboutMaps ? warning$1( @@ -9743,14 +9824,16 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutMaps = true; - } - - // First, validate keys. + } // First, validate keys. // We'll get a different iterator later for the main pass. + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) { var knownKeys = null; + var _step = _newChildren.next(); + for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9759,21 +9842,19 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - (function() { - if (!(newChildren != null)) { - throw ReactError(Error("An iterable object provided no iterator.")); - } - })(); + + if (!(newChildren != null)) { + throw Error("An iterable object provided no iterator."); + } var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; - var step = newChildren.next(); + for ( ; oldFiber !== null && !step.done; @@ -9785,12 +9866,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, step.value, expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -9799,8 +9882,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -9808,7 +9893,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -9819,6 +9906,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -9834,25 +9922,28 @@ function ChildReconciler(shouldTrackSideEffects) { // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, expirationTime); + if (_newFiber3 === null) { continue; } + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } + previousNewFiber = _newFiber3; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( existingChildren, @@ -9861,6 +9952,7 @@ function ChildReconciler(shouldTrackSideEffects) { step.value, expirationTime ); + if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { @@ -9873,12 +9965,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } + previousNewFiber = _newFiber4; } } @@ -9909,9 +10004,9 @@ function ChildReconciler(shouldTrackSideEffects) { var existing = useFiber(currentFirstChild, textContent, expirationTime); existing.return = returnFiber; return existing; - } - // The existing first child is not a text node so we need to create one + } // The existing first child is not a text node so we need to create one // and delete the existing ones. + deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText( textContent, @@ -9930,6 +10025,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = element.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -9937,8 +10033,7 @@ function ChildReconciler(shouldTrackSideEffects) { 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: + : child.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) { deleteRemainingChildren(returnFiber, child.sibling); @@ -9951,10 +10046,12 @@ function ChildReconciler(shouldTrackSideEffects) { ); existing.ref = coerceRef(returnFiber, child, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { deleteRemainingChildren(returnFiber, child); @@ -9963,6 +10060,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -9981,6 +10079,7 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; @@ -9995,6 +10094,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = portal.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10015,6 +10115,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10025,11 +10126,10 @@ function ChildReconciler(shouldTrackSideEffects) { ); created.return = returnFiber; return created; - } - - // This API will tag the children with the side-effect of the reconciliation + } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. + function reconcileChildFibers( returnFiber, currentFirstChild, @@ -10040,7 +10140,6 @@ function ChildReconciler(shouldTrackSideEffects) { // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]} and <>.... // We treat the ambiguous cases above the same. @@ -10049,11 +10148,11 @@ function ChildReconciler(shouldTrackSideEffects) { newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; - } + } // Handle object types - // Handle object types var isObject = typeof newChild === "object" && newChild !== null; if (isObject) { @@ -10067,6 +10166,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) ); + case REACT_PORTAL_TYPE: return placeSingleChild( reconcileSinglePortal( @@ -10117,6 +10217,7 @@ function ChildReconciler(shouldTrackSideEffects) { warnOnFunctionType(); } } + if (typeof newChild === "undefined" && !isUnkeyedTopLevelFragment) { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, @@ -10125,6 +10226,7 @@ function ChildReconciler(shouldTrackSideEffects) { case ClassComponent: { { var instance = returnFiber.stateNode; + if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; @@ -10134,23 +10236,20 @@ function ChildReconciler(shouldTrackSideEffects) { // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough + case FunctionComponent: { var Component = returnFiber.type; - (function() { - { - throw ReactError( - Error( - (Component.displayName || Component.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) - ); - } - })(); + + { + 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." + ); + } } } - } + } // Remaining cases are all treated as empty. - // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } @@ -10159,13 +10258,10 @@ function ChildReconciler(shouldTrackSideEffects) { var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current$$1, workInProgress) { - (function() { - if (!(current$$1 === null || workInProgress.child === current$$1.child)) { - throw ReactError(Error("Resuming work not yet implemented.")); - } - })(); + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw Error("Resuming work not yet implemented."); + } if (workInProgress.child === null) { return; @@ -10178,8 +10274,8 @@ function cloneChildFibers(current$$1, workInProgress) { currentChild.expirationTime ); workInProgress.child = newChild; - newChild.return = workInProgress; + while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress( @@ -10189,12 +10285,13 @@ function cloneChildFibers(current$$1, workInProgress) { ); newChild.return = workInProgress; } + newChild.sibling = null; -} +} // Reset a workInProgress child set to prepare it for a second pass. -// Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, renderExpirationTime) { var child = workInProgress.child; + while (child !== null) { resetWorkInProgress(child, renderExpirationTime); child = child.sibling; @@ -10202,21 +10299,17 @@ function resetChildFibers(workInProgress, renderExpirationTime) { } var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - (function() { - if (!(c !== NO_CONTEXT)) { - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(c !== NO_CONTEXT)) { + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + return c; } @@ -10228,19 +10321,18 @@ function getRootHostContainer() { function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - // Finally, we need to push the host context to the stack. + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. + push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. + pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } @@ -10259,15 +10351,13 @@ function getHostContext() { function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; - } - - // Track the context and the Fiber that provided it. + } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. + push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } @@ -10283,98 +10373,100 @@ function popHostContext(fiber) { pop(contextFiberStackCursor, fiber); } -var DefaultSuspenseContext = 0; - -// The Suspense Context is split into two parts. The lower bits is +var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. -var SubtreeSuspenseContextMask = 1; - -// Subtree Flags: +var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. -var InvisibleParentSuspenseContext = 1; - -// Shallow Flags: +var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. -var ForceSuspenseFallback = 2; +var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } - function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } - function setShallowSuspenseContext(parentContext, shallowContext) { return (parentContext & SubtreeSuspenseContextMask) | shallowContext; } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } - function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } - function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } -// TODO: This is now an empty object. Should we switch this to a boolean? -// Alternatively we can make this use an effect tag similar to SuspenseList. - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } + return false; } - var props = workInProgress.memoizedProps; - // In order to capture, the Suspense component must have a fallback prop. + + var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop. + if (props.fallback === undefined) { return false; - } - // Regular boundaries always capture. + } // Regular boundaries always capture. + if (props.unstable_avoidThisFallback !== true) { return true; - } - // If it's a boundary we should avoid, then we prefer to bubble up to the + } // If it's a boundary we should avoid, then we prefer to bubble up to the // parent boundary if it is currently invisible. + if (hasInvisibleParent) { return false; - } - // If the parent is not able to handle it, we must handle it. + } // If the parent is not able to handle it, we must handle it. + return true; } - function findFirstSuspended(row) { var node = row; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - return node; + var dehydrated = state.dehydrated; + + if ( + dehydrated === null || + isSuspenseInstancePending(dehydrated) || + isSuspenseInstanceFallback(dehydrated) + ) { + return node; + } } } else if ( - node.tag === SuspenseListComponent && - // revealOrder undefined can't be trusted because it don't + node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { var didSuspend = (node.effectTag & DidCapture) !== NoEffect; + if (didSuspend) { return node; } @@ -10383,37 +10475,32 @@ function findFirstSuspended(row) { node = node.child; continue; } + if (node === row) { return null; } + while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - return null; -} -function createResponderListener(responder, props) { - var eventResponderListener = { - responder: responder, - props: props - }; - { - Object.freeze(eventResponderListener); - } - return eventResponderListener; + return null; } +var emptyObject$1 = {}; +var isArray$2 = Array.isArray; function createResponderInstance( responder, responderProps, responderState, - target, fiber ) { return { @@ -10421,75 +10508,263 @@ function createResponderInstance( props: responderProps, responder: responder, rootEventTypes: null, - state: responderState, - target: target + state: responderState + }; +} + +function mountEventResponder( + responder, + responderProps, + fiber, + respondersMap, + rootContainerInstance +) { + var responderState = emptyObject$1; + var getInitialState = responder.getInitialState; + + if (getInitialState !== null) { + responderState = getInitialState(responderProps); + } + + var responderInstance = createResponderInstance( + responder, + responderProps, + responderState, + fiber + ); + + if (!rootContainerInstance) { + var node = fiber; + + while (node !== null) { + var tag = node.tag; + + if (tag === HostComponent) { + rootContainerInstance = node.stateNode; + break; + } else if (tag === HostRoot) { + rootContainerInstance = node.stateNode.containerInfo; + break; + } + + node = node.return; + } + } + + mountResponderInstance( + responder, + responderInstance, + responderProps, + responderState, + rootContainerInstance + ); + respondersMap.set(responder, responderInstance); +} + +function updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance +) { + var responder; + var props; + + if (listener) { + responder = listener.responder; + props = listener.props; + } + + if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { + throw Error( + "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()." + ); + } + + var listenerProps = props; + + if (visistedResponders.has(responder)) { + // show warning + { + 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 + ); + } + + return; + } + + visistedResponders.add(responder); + var responderInstance = respondersMap.get(responder); + + if (responderInstance === undefined) { + // Mount (happens in either complete or commit phase) + mountEventResponder( + responder, + listenerProps, + fiber, + respondersMap, + rootContainerInstance + ); + } else { + // Update (happens during commit phase only) + responderInstance.props = listenerProps; + responderInstance.fiber = fiber; + } +} + +function updateEventListeners(listeners, fiber, rootContainerInstance) { + var visistedResponders = new Set(); + var dependencies = fiber.dependencies; + + if (listeners != null) { + if (dependencies === null) { + dependencies = fiber.dependencies = { + expirationTime: NoWork, + firstContext: null, + responders: new Map() + }; + } + + var respondersMap = dependencies.responders; + + if (respondersMap === null) { + respondersMap = new Map(); + } + + if (isArray$2(listeners)) { + for (var i = 0, length = listeners.length; i < length; i++) { + var listener = listeners[i]; + updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } else { + updateEventListener( + listeners, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } + + if (dependencies !== null) { + var _respondersMap = dependencies.responders; + + if (_respondersMap !== null) { + // Unmount + var mountedResponders = Array.from(_respondersMap.keys()); + + for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { + var mountedResponder = mountedResponders[_i]; + + if (!visistedResponders.has(mountedResponder)) { + var responderInstance = _respondersMap.get(mountedResponder); + + unmountResponderInstance(responderInstance); + + _respondersMap.delete(mountedResponder); + } + } + } + } +} +function createResponderListener(responder, props) { + var eventResponderListener = { + responder: responder, + props: props }; + + { + Object.freeze(eventResponderListener); + } + + return eventResponderListener; } -var NoEffect$1 = /* */ 0; -var UnmountSnapshot = /* */ 2; -var UnmountMutation = /* */ 4; -var MountMutation = /* */ 8; -var UnmountLayout = /* */ 16; -var MountLayout = /* */ 32; -var MountPassive = /* */ 64; -var UnmountPassive = /* */ 128; +var NoEffect$1 = + /* */ + 0; +var UnmountSnapshot = + /* */ + 2; +var UnmountMutation = + /* */ + 4; +var MountMutation = + /* */ + 8; +var UnmountLayout = + /* */ + 16; +var MountLayout = + /* */ + 32; +var MountPassive = + /* */ + 64; +var UnmountPassive = + /* */ + 128; var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var didWarnAboutMismatchedHooksForComponent; -var didWarnAboutMismatchedHooksForComponent = void 0; { didWarnAboutMismatchedHooksForComponent = new Set(); } // These are set right before calling the component. -var renderExpirationTime$1 = NoWork; -// The work-in-progress fiber. I've named it differently to distinguish it from +var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. -var currentlyRenderingFiber$1 = null; -// Hooks are stored as a linked list on the fiber's memoizedState field. The +var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. + var currentHook = null; var nextCurrentHook = null; var firstWorkInProgressHook = null; var workInProgressHook = null; var nextWorkInProgressHook = null; - var remainingExpirationTime = NoWork; var componentUpdateQueue = null; -var sideEffectTag = 0; - -// Updates scheduled during render will trigger an immediate re-render at the +var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the // end of the current pass. We can't store these updates on the normal queue, // because if the work is aborted, they should be discarded. Because this is // a relatively rare case, we also don't want to add an additional field to // either the hook or queue object types. So we store them in a lazily create // map of queue -> render-phase updates, which are discarded once the component // completes without re-rendering. - // Whether an update was scheduled during the currently executing render pass. -var didScheduleRenderPhaseUpdate = false; -// Lazily created map of render-phase updates -var renderPhaseUpdates = null; -// Counter to prevent infinite loops. -var numberOfReRenders = 0; -var RE_RENDER_LIMIT = 25; -// In DEV, this is the name of the currently executing primitive hook -var currentHookNameInDev = null; +var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook -// In DEV, this list ensures that hooks are called in the same order between renders. +var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. -var hookTypesDev = null; -var hookTypesUpdateIndexDev = -1; -// In DEV, this tracks whether currently rendering component needs to ignore +var hookTypesDev = null; +var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. + var ignorePreviousDependencies = false; function mountHookTypesDev() { @@ -10510,6 +10785,7 @@ function updateHookTypesDev() { if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } @@ -10536,29 +10812,26 @@ function checkDepsAreArrayDev(deps) { function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentName(currentlyRenderingFiber$1.type); + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ""; - var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - - var row = i + 1 + ". " + oldHookName; - - // Extra space so second column lines up + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { row += " "; } row += newHookName + "\n"; - table += row; } @@ -10580,15 +10853,11 @@ function warnOnHookMismatchInDev(currentHookName) { } function throwInvalidHookError() { - (function() { - { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) - ); - } - })(); + { + 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." + ); + } } function areHookInputsEqual(nextDeps, prevDeps) { @@ -10609,6 +10878,7 @@ function areHookInputsEqual(nextDeps, prevDeps) { currentHookNameInDev ); } + return false; } @@ -10628,12 +10898,15 @@ function areHookInputsEqual(nextDeps, prevDeps) { ); } } + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (is(nextDeps[i], prevDeps[i])) { + if (is$1(nextDeps[i], prevDeps[i])) { continue; } + return false; } + return true; } @@ -10651,31 +10924,26 @@ function renderWithHooks( { hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: + hookTypesUpdateIndexDev = -1; // Used for hot reloading: + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - // The following should have already been reset + } // The following should have already been reset // currentHook = null; // workInProgressHook = null; - // remainingExpirationTime = NoWork; // componentUpdateQueue = null; - // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; // sideEffectTag = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because nextCurrentHook === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so nextCurrentHook would be null during updates and mounts. + { if (nextCurrentHook !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; @@ -10697,16 +10965,15 @@ function renderWithHooks( do { didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; + { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; - } + } // Start over from the beginning of the list - // Start over from the beginning of the list nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; - currentHook = null; workInProgressHook = null; componentUpdateQueue = null; @@ -10717,20 +10984,16 @@ function renderWithHooks( } ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - children = Component(props, refOrContext); } while (didScheduleRenderPhaseUpdate); renderPhaseUpdates = null; numberOfReRenders = 0; - } - - // We can assume the previous dispatcher is always this one, since we set it + } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; var renderedWork = currentlyRenderingFiber$1; - renderedWork.memoizedState = firstWorkInProgressHook; renderedWork.expirationTime = remainingExpirationTime; renderedWork.updateQueue = componentUpdateQueue; @@ -10738,15 +11001,12 @@ function renderWithHooks( { renderedWork._debugHookTypes = hookTypesDev; - } - - // This check uses currentHook so that it works the same in DEV and prod bundles. + } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -10761,45 +11021,36 @@ function renderWithHooks( remainingExpirationTime = NoWork; componentUpdateQueue = null; - sideEffectTag = 0; - - // These were reset above + sideEffectTag = 0; // These were reset above // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; - (function() { - if (!!didRenderTooFewHooks) { - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) - ); - } - })(); + if (!!didRenderTooFewHooks) { + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } return children; } - function bailoutHooks(current, workInProgress, expirationTime) { workInProgress.updateQueue = current.updateQueue; workInProgress.effectTag &= ~(Passive | Update); + if (current.expirationTime <= expirationTime) { current.expirationTime = NoWork; } } - function resetHooks() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - // This is used to reset the state of this module when a component throws. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws. // It's also called inside mountIndeterminateComponent if we determine the // component is a module-style component. + renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -10809,14 +11060,12 @@ function resetHooks() { { hookTypesDev = null; hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -10825,11 +11074,9 @@ function resetHooks() { function mountWorkInProgressHook() { var hook = { memoizedState: null, - baseState: null, queue: null, baseUpdate: null, - next: null }; @@ -10840,6 +11087,7 @@ function mountWorkInProgressHook() { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } + return workInProgressHook; } @@ -10853,27 +11101,20 @@ function updateWorkInProgressHook() { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - (function() { - if (!(nextCurrentHook !== null)) { - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); - } - })(); - currentHook = nextCurrentHook; + if (!(nextCurrentHook !== null)) { + throw Error("Rendered more hooks than during the previous render."); + } + currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, queue: currentHook.queue, baseUpdate: currentHook.baseUpdate, - next: null }; @@ -10884,8 +11125,10 @@ function updateWorkInProgressHook() { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } + nextCurrentHook = currentHook.next; } + return workInProgressHook; } @@ -10901,12 +11144,14 @@ function basicStateReducer(state, action) { function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); - var initialState = void 0; + var initialState; + if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -10915,8 +11160,7 @@ function mountReducer(reducer, initialArg, init) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -10926,68 +11170,67 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - (function() { - if (!(queue !== null)) { - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(queue !== null)) { + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + } queue.lastRenderedReducer = reducer; if (numberOfReRenders > 0) { // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. var _dispatch = queue.dispatch; + if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = hook.memoizedState; var update = firstRenderPhaseUpdate; + do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. - var _action = update.action; - newState = reducer(newState, _action); + var action = update.action; + newState = reducer(newState, action); update = update.next; - } while (update !== null); - - // Mark that the fiber performed work, but only if the new state is + } while (update !== null); // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(newState, hook.memoizedState)) { + + if (!is$1(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } - hook.memoizedState = newState; - // Don't persist the state accumulated from the render phase updates to + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. + if (hook.baseUpdate === queue.last) { hook.baseState = newState; } queue.lastRenderedState = newState; - return [newState, _dispatch]; } } + return [hook.memoizedState, _dispatch]; - } + } // The last update in the entire queue + + var last = queue.last; // The last update that is part of the base state. - // The last update in the entire queue - var last = queue.last; - // The last update that is part of the base state. var baseUpdate = hook.baseUpdate; - var baseState = hook.baseState; + var baseState = hook.baseState; // Find the first unprocessed update. + + var first; - // Find the first unprocessed update. - var first = void 0; if (baseUpdate !== null) { if (last !== null) { // For the first update, the queue is a circular linked list where @@ -10995,10 +11238,12 @@ function updateReducer(reducer, initialArg, init) { // the `baseUpdate` is no longer empty, we can unravel the list. last.next = null; } + first = baseUpdate.next; } else { first = last !== null ? last.next : null; } + if (first !== null) { var _newState = baseState; var newBaseState = null; @@ -11006,8 +11251,10 @@ function updateReducer(reducer, initialArg, init) { var prevUpdate = baseUpdate; var _update = first; var didSkip = false; + do { var updateExpirationTime = _update.expirationTime; + if (updateExpirationTime < renderExpirationTime$1) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base @@ -11016,14 +11263,14 @@ function updateReducer(reducer, initialArg, init) { didSkip = true; newBaseUpdate = prevUpdate; newBaseState = _newState; - } - // Update the remaining priority in the queue. + } // Update the remaining priority in the queue. + if (updateExpirationTime > remainingExpirationTime) { remainingExpirationTime = updateExpirationTime; + markUnprocessedUpdateTime(remainingExpirationTime); } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. @@ -11033,18 +11280,18 @@ function updateReducer(reducer, initialArg, init) { markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig - ); + ); // Process this update. - // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the // current reducer, we can use the eagerly computed state. _newState = _update.eagerState; } else { - var _action2 = _update.action; - _newState = reducer(_newState, _action2); + var _action = _update.action; + _newState = reducer(_newState, _action); } } + prevUpdate = _update; _update = _update.next; } while (_update !== null && _update !== first); @@ -11052,18 +11299,16 @@ function updateReducer(reducer, initialArg, init) { if (!didSkip) { newBaseUpdate = prevUpdate; newBaseState = _newState; - } - - // Mark that the fiber performed work, but only if the new state is + } // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(_newState, hook.memoizedState)) { + + if (!is$1(_newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = _newState; hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.lastRenderedState = _newState; } @@ -11073,9 +11318,11 @@ function updateReducer(reducer, initialArg, init) { function mountState(initialState) { var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { initialState = initialState(); } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11084,8 +11331,7 @@ function mountState(initialState) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11105,29 +11351,36 @@ function pushEffect(tag, create, destroy, deps) { // Circular next: null }; + if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); componentUpdateQueue.lastEffect = effect.next = effect; } else { - var _lastEffect = componentUpdateQueue.lastEffect; - if (_lastEffect === null) { + var lastEffect = componentUpdateQueue.lastEffect; + + if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { - var firstEffect = _lastEffect.next; - _lastEffect.next = effect; + var firstEffect = lastEffect.next; + lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } + return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); - var ref = { current: initialValue }; + var ref = { + current: initialValue + }; + { Object.seal(ref); } + hook.memoizedState = ref; return ref; } @@ -11152,8 +11405,10 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; + if (nextDeps !== null) { var prevDeps = prevEffect.deps; + if (areHookInputsEqual(nextDeps, prevDeps)) { pushEffect(NoEffect$1, create, destroy, nextDeps); return; @@ -11172,6 +11427,7 @@ function mountEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return mountEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11187,6 +11443,7 @@ function updateEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return updateEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11206,13 +11463,16 @@ function updateLayoutEffect(create, deps) { function imperativeHandleEffect(create, ref) { if (typeof ref === "function") { var refCallback = ref; + var _inst = create(); + refCallback(_inst); return function() { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; + { !refObject.hasOwnProperty("current") ? warning$1( @@ -11223,7 +11483,9 @@ function imperativeHandleEffect(create, ref) { ) : void 0; } + var _inst2 = create(); + refObject.current = _inst2; return function() { refObject.current = null; @@ -11241,12 +11503,10 @@ function mountImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return mountEffectImpl( Update, UnmountMutation | MountLayout, @@ -11265,12 +11525,10 @@ function updateImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl( Update, UnmountMutation | MountLayout, @@ -11298,14 +11556,17 @@ function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + hook.memoizedState = [callback, nextDeps]; return callback; } @@ -11322,33 +11583,32 @@ function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function dispatchAction(fiber, queue, action) { - (function() { - if (!(numberOfReRenders < RE_RENDER_LIMIT)) { - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) - ); - } - })(); + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } { - !(arguments.length <= 3) + !(typeof arguments[3] !== "function") ? warning$1( false, "State updates from the useState() and useReducer() Hooks don't support the " + @@ -11359,6 +11619,7 @@ function dispatchAction(fiber, queue, action) { } var alternate = fiber.alternate; + if ( fiber === currentlyRenderingFiber$1 || (alternate !== null && alternate === currentlyRenderingFiber$1) @@ -11375,39 +11636,40 @@ function dispatchAction(fiber, queue, action) { eagerState: null, next: null }; + { update.priority = getCurrentPriorityLevel(); } + if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } + lastRenderPhaseUpdate.next = update; } } else { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } - var currentTime = requestCurrentTime(); - var _suspenseConfig = requestCurrentSuspenseConfig(); - var _expirationTime = computeExpirationForFiber( + var suspenseConfig = requestCurrentSuspenseConfig(); + var expirationTime = computeExpirationForFiber( currentTime, fiber, - _suspenseConfig + suspenseConfig ); - var _update2 = { - expirationTime: _expirationTime, - suspenseConfig: _suspenseConfig, + expirationTime: expirationTime, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, @@ -11416,21 +11678,24 @@ function dispatchAction(fiber, queue, action) { { _update2.priority = getCurrentPriorityLevel(); - } + } // Append the update to the end of the list. + + var last = queue.last; - // Append the update to the end of the list. - var _last = queue.last; - if (_last === null) { + if (last === null) { // This is the first update. Create a circular list. _update2.next = _update2; } else { - var first = _last.next; + var first = last.next; + if (first !== null) { // Still circular. _update2.next = first; } - _last.next = _update2; + + last.next = _update2; } + queue.last = _update2; if ( @@ -11440,23 +11705,27 @@ function dispatchAction(fiber, queue, action) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. - var _lastRenderedReducer = queue.lastRenderedReducer; - if (_lastRenderedReducer !== null) { - var prevDispatcher = void 0; + var lastRenderedReducer = queue.lastRenderedReducer; + + if (lastRenderedReducer !== null) { + var prevDispatcher; + { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } + try { var currentState = queue.lastRenderedState; - var _eagerState = _lastRenderedReducer(currentState, action); - // Stash the eagerly computed state, and the reducer used to compute + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. - _update2.eagerReducer = _lastRenderedReducer; - _update2.eagerState = _eagerState; - if (is(_eagerState, currentState)) { + + _update2.eagerReducer = lastRenderedReducer; + _update2.eagerState = eagerState; + + if (is$1(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that @@ -11472,6 +11741,7 @@ function dispatchAction(fiber, queue, action) { } } } + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -11479,13 +11749,13 @@ function dispatchAction(fiber, queue, action) { warnIfNotCurrentlyActingUpdatesInDev(fiber); } } - scheduleWork(fiber, _expirationTime); + + scheduleWork(fiber, expirationTime); } } var ContextOnlyDispatcher = { readContext: readContext, - useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, @@ -11498,7 +11768,6 @@ var ContextOnlyDispatcher = { useDebugValue: throwInvalidHookError, useResponder: throwInvalidHookError }; - var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; @@ -11565,6 +11834,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11576,6 +11846,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11592,6 +11863,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11609,7 +11881,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -11644,6 +11915,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11655,6 +11927,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11671,6 +11944,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11688,7 +11962,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -11723,6 +11996,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -11734,6 +12008,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -11750,6 +12025,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -11767,7 +12043,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -11809,6 +12084,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11821,6 +12097,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11839,6 +12116,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11858,7 +12136,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -11900,6 +12177,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -11912,6 +12190,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -11930,6 +12209,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -11951,10 +12231,9 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }; } -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. -var now$1 = Scheduler.unstable_now; +var now$1 = Scheduler.unstable_now; var commitTime = 0; var profilerStartTime = -1; @@ -11966,6 +12245,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } + commitTime = now$1(); } @@ -11985,6 +12265,7 @@ function stopProfilerTimerIfRunning(fiber) { if (!enableProfilerTimer) { return; } + profilerStartTime = -1; } @@ -11996,15 +12277,17 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } + profilerStartTime = -1; } } -// The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. + var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; @@ -12032,12 +12315,14 @@ function enterHydrationState(fiber) { return true; } -function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) { +function reenterHydrationStateFromDehydratedSuspenseInstance( + fiber, + suspenseInstance +) { if (!supportsHydration) { return false; } - var suspenseInstance = fiber.stateNode; nextHydratableInstance = getNextHydratableSibling(suspenseInstance); popToNextHostParent(fiber); isHydrating = true; @@ -12053,6 +12338,7 @@ function deleteHydratableInstance(returnFiber, instance) { instance ); break; + case HostComponent: didNotHydrateInstance( returnFiber.type, @@ -12067,13 +12353,12 @@ function deleteHydratableInstance(returnFiber, instance) { var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; - childToDelete.effectTag = Deletion; - - // This might seem like it belongs on progressedFirstDeletion. However, + childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However, // these children are not part of the reconciliation list of children. // Even if we abort and rereconcile the children, that will try to hydrate // again and the nodes are still in the host tree so these will be // recreated. + if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; @@ -12083,31 +12368,38 @@ function deleteHydratableInstance(returnFiber, instance) { } function insertNonHydratedInstance(returnFiber, fiber) { - fiber.effectTag |= Placement; + fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement; + { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; + switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableContainerInstance(parentContainer, type, props); break; + case HostText: var text = fiber.pendingProps; didNotFindHydratableContainerTextInstance(parentContainer, text); break; + case SuspenseComponent: didNotFindHydratableContainerSuspenseInstance(parentContainer); break; } + break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; + switch (fiber.tag) { case HostComponent: var _type = fiber.type; @@ -12120,6 +12412,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _props ); break; + case HostText: var _text = fiber.pendingProps; didNotFindHydratableTextInstance( @@ -12129,6 +12422,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _text ); break; + case SuspenseComponent: didNotFindHydratableSuspenseInstance( parentType, @@ -12137,8 +12431,10 @@ function insertNonHydratedInstance(returnFiber, fiber) { ); break; } + break; } + default: return; } @@ -12151,33 +12447,53 @@ function tryHydrate(fiber, nextInstance) { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type, props); + if (instance !== null) { fiber.stateNode = instance; return true; } + return false; } + case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); + if (textInstance !== null) { fiber.stateNode = textInstance; return true; } + return false; } + case SuspenseComponent: { if (enableSuspenseServerRenderer) { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); + if (suspenseInstance !== null) { - // Downgrade the tag to a dehydrated component until we've hydrated it. - fiber.tag = DehydratedSuspenseComponent; - fiber.stateNode = suspenseInstance; + var suspenseState = { + dehydrated: suspenseInstance, + retryTime: Never + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. + + var dehydratedFragment = createFiberFromDehydratedFragment( + suspenseInstance + ); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; return true; } } + return false; } + default: return false; } @@ -12187,7 +12503,9 @@ function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } + var nextInstance = nextHydratableInstance; + if (!nextInstance) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); @@ -12195,25 +12513,29 @@ function tryToClaimNextHydratableInstance(fiber) { hydrationParentFiber = fiber; return; } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; - } - // We matched the next one, we'll now assume that the first one was + } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. + deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance); } + hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(nextInstance); } @@ -12224,15 +12546,11 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var instance = fiber.stateNode; @@ -12243,38 +12561,37 @@ function prepareToHydrateHostInstance( rootContainerInstance, hostContext, fiber - ); - // TODO: Type this specific to this type of component. - fiber.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. + if (updatePayload !== null) { return true; } + return false; } function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); + { if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { @@ -12286,6 +12603,7 @@ function prepareToHydrateHostTextInstance(fiber) { ); break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; @@ -12303,46 +12621,66 @@ function prepareToHydrateHostTextInstance(fiber) { } } } + return shouldUpdate; } -function skipPastDehydratedSuspenseInstance(fiber) { +function prepareToHydrateHostSuspenseInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } - var suspenseInstance = fiber.stateNode; - (function() { - if (!suspenseInstance) { - throw ReactError( - Error( - "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." - ) + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + hydrateSuspenseInstance(suspenseInstance, fiber); +} + +function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + { + throw Error( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." ); } - })(); - nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( - suspenseInstance - ); + } + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; + while ( parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && - parent.tag !== DehydratedSuspenseComponent + parent.tag !== SuspenseComponent ) { parent = parent.return; } + hydrationParentFiber = parent; } @@ -12350,11 +12688,13 @@ function popHydrationState(fiber) { if (!supportsHydration) { return false; } + if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } + if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our @@ -12364,13 +12704,12 @@ function popHydrationState(fiber) { return false; } - var type = fiber.type; - - // If we have any remaining hydratable nodes, we need to delete them now. + var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. // TODO: Better heuristic. + if ( fiber.tag !== HostComponent || (type !== "head" && @@ -12378,6 +12717,7 @@ function popHydrationState(fiber) { !shouldSetTextContent(type, fiber.memoizedProps)) ) { var nextInstance = nextHydratableInstance; + while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); @@ -12385,9 +12725,15 @@ function popHydrationState(fiber) { } popToNextHostParent(fiber); - nextHydratableInstance = hydrationParentFiber - ? getNextHydratableSibling(fiber.stateNode) - : null; + + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber + ? getNextHydratableSibling(fiber.stateNode) + : null; + } + return true; } @@ -12402,19 +12748,17 @@ function resetHydrationState() { } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - -var didWarnAboutBadClass = void 0; -var didWarnAboutModulePatternComponent = void 0; -var didWarnAboutContextTypeOnFunctionComponent = void 0; -var didWarnAboutGetDerivedStateOnFunctionComponent = void 0; -var didWarnAboutFunctionRefs = void 0; -var didWarnAboutReassigningProps = void 0; -var didWarnAboutMaxDuration = void 0; -var didWarnAboutRevealOrder = void 0; -var didWarnAboutTailOptions = void 0; -var didWarnAboutDefaultPropsOnFunctionComponent = void 0; +var didWarnAboutBadClass; +var didWarnAboutModulePatternComponent; +var didWarnAboutContextTypeOnFunctionComponent; +var didWarnAboutGetDerivedStateOnFunctionComponent; +var didWarnAboutFunctionRefs; +var didWarnAboutReassigningProps; +var didWarnAboutMaxDuration; +var didWarnAboutRevealOrder; +var didWarnAboutTailOptions; +var didWarnAboutDefaultPropsOnFunctionComponent; { didWarnAboutBadClass = {}; @@ -12450,7 +12794,6 @@ function reconcileChildren( // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers( @@ -12481,11 +12824,11 @@ function forceUnmountCurrentAndReconcile( current$$1.child, null, renderExpirationTime - ); - // In the second pass, we mount the new children. The trick here is that we + ); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their their // identity matches. + workInProgress.child = reconcileChildFibers( workInProgress, null, @@ -12504,12 +12847,12 @@ function updateForwardRef( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12523,11 +12866,11 @@ function updateForwardRef( } var render = Component.render; - var ref = workInProgress.ref; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - // The rest is a fork of updateFunctionComponent - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12539,6 +12882,7 @@ function updateForwardRef( ref, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12556,6 +12900,7 @@ function updateForwardRef( ); } } + setCurrentPhase(null); } @@ -12566,9 +12911,8 @@ function updateForwardRef( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -12589,24 +12933,27 @@ function updateMemoComponent( ) { if (current$$1 === null) { var type = Component.type; + if ( isSimpleFunctionComponent(type) && - Component.compare === null && - // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined ) { var resolvedType = type; + { resolvedType = resolveFunctionForHotReloading(type); - } - // If this is a plain function component without default props, + } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. + workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; + { validateFunctionComponentInDev(workInProgress, type); } + return updateSimpleMemoComponent( current$$1, workInProgress, @@ -12616,8 +12963,10 @@ function updateMemoComponent( renderExpirationTime ); } + { var innerPropTypes = type.propTypes; + if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -12630,6 +12979,7 @@ function updateMemoComponent( ); } } + var child = createFiberFromTypeAndProps( Component.type, null, @@ -12643,9 +12993,11 @@ function updateMemoComponent( workInProgress.child = child; return child; } + { var _type = Component.type; var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -12658,14 +13010,17 @@ function updateMemoComponent( ); } } + var currentChild = current$$1.child; // This is always exactly one child + if (updateExpirationTime < renderExpirationTime) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; - // Default to shallow comparison + var prevProps = currentChild.memoizedProps; // Default to shallow comparison + var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; + if ( compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref @@ -12676,8 +13031,8 @@ function updateMemoComponent( renderExpirationTime ); } - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; var newChild = createWorkInProgress( currentChild, @@ -12701,19 +13056,21 @@ function updateSimpleMemoComponent( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. outerMemoType = refineResolvedLazyComponent(outerMemoType); } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -12722,19 +13079,20 @@ function updateSimpleMemoComponent( getComponentName(outerMemoType), getCurrentFiberStackInDev ); - } - // Inner propTypes will be validated in the function component path. + } // Inner propTypes will be validated in the function component path. } } + if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; + if ( shallowEqual(prevProps, nextProps) && - current$$1.ref === workInProgress.ref && - // Prevent bailout if the implementation changed due to hot reload: + current$$1.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload: workInProgress.type === current$$1.type ) { didReceiveUpdate = false; + if (updateExpirationTime < renderExpirationTime) { return bailoutOnAlreadyFinishedWork( current$$1, @@ -12744,6 +13102,7 @@ function updateSimpleMemoComponent( } } } + return updateFunctionComponent( current$$1, workInProgress, @@ -12779,6 +13138,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren( @@ -12792,6 +13152,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { function markRef(current$$1, workInProgress) { var ref = workInProgress.ref; + if ( (current$$1 === null && ref !== null) || (current$$1 !== null && current$$1.ref !== ref) @@ -12813,6 +13174,7 @@ function updateFunctionComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12825,14 +13187,16 @@ function updateFunctionComponent( } } - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12844,6 +13208,7 @@ function updateFunctionComponent( context, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12861,6 +13226,7 @@ function updateFunctionComponent( ); } } + setCurrentPhase(null); } @@ -12871,9 +13237,8 @@ function updateFunctionComponent( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -12896,6 +13261,7 @@ function updateClassComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12906,22 +13272,23 @@ function updateClassComponent( ); } } - } - - // Push context providers early to prevent context stack mismatches. + } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); var instance = workInProgress.stateNode; - var shouldUpdate = void 0; + var shouldUpdate; + if (instance === null) { if (current$$1 !== null) { // An class component without an instance only mounts if it suspended @@ -12929,11 +13296,11 @@ function updateClassComponent( // tree it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current$$1.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; - } - // In the initial pass we might need to construct the instance. + } // In the initial pass we might need to construct the instance. + constructClassInstance( workInProgress, Component, @@ -12964,6 +13331,7 @@ function updateClassComponent( renderExpirationTime ); } + var nextUnitOfWork = finishClassComponent( current$$1, workInProgress, @@ -12972,8 +13340,10 @@ function updateClassComponent( hasContext, renderExpirationTime ); + { var inst = workInProgress.stateNode; + if (inst.props !== nextProps) { !didWarnAboutReassigningProps ? warning$1( @@ -12986,6 +13356,7 @@ function updateClassComponent( didWarnAboutReassigningProps = true; } } + return nextUnitOfWork; } @@ -12999,7 +13370,6 @@ function finishClassComponent( ) { // Refs should update even if shouldComponentUpdate returns false markRef(current$$1, workInProgress); - var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect; if (!shouldUpdate && !didCaptureError) { @@ -13015,11 +13385,11 @@ function finishClassComponent( ); } - var instance = workInProgress.stateNode; + var instance = workInProgress.stateNode; // Rerender - // Rerender ReactCurrentOwner$3.current = workInProgress; - var nextChildren = void 0; + var nextChildren; + if ( didCaptureError && typeof Component.getDerivedStateFromError !== "function" @@ -13038,6 +13408,7 @@ function finishClassComponent( { setCurrentPhase("render"); nextChildren = instance.render(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13045,12 +13416,13 @@ function finishClassComponent( ) { instance.render(); } + setCurrentPhase(null); } - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; + if (current$$1 !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children @@ -13069,13 +13441,11 @@ function finishClassComponent( nextChildren, renderExpirationTime ); - } - - // Memoize state using the values we just used to render. + } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. - workInProgress.memoizedState = instance.state; - // The context might have changed so we need to recalculate it. + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } @@ -13085,6 +13455,7 @@ function finishClassComponent( function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; + if (root.pendingContext) { pushTopLevelContextObject( workInProgress, @@ -13095,21 +13466,20 @@ function pushHostRootContext(workInProgress) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } + pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - (function() { - if (!(updateQueue !== null)) { - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(updateQueue !== null)) { + 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." + ); + } + var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState !== null ? prevState.element : null; @@ -13120,10 +13490,11 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { null, renderExpirationTime ); - var nextState = workInProgress.memoizedState; - // Caution: React DevTools currently depends on this property + var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property // being called "element". + var nextChildren = nextState.element; + if (nextChildren === prevChildren) { // If the state is the same as before, that's a bailout because we had // no work that expires at this time. @@ -13134,32 +13505,33 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + var root = workInProgress.stateNode; - if ( - (current$$1 === null || current$$1.child === null) && - root.hydrate && - enterHydrationState(workInProgress) - ) { + + if (root.hydrate && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. - - // This is a bit of a hack. We track the host root as a placement to - // know that we're currently in a mounting state. That way isMounted - // works as expected. We must reset this before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag |= Placement; - - // Ensure that children mount into this root without tracking - // side-effects. This ensures that we don't store Placement effects on - // nodes that will be hydrated. - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + workInProgress.child = child; + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag = (node.effectTag & ~Placement) | Hydrating; + node = node.sibling; + } } else { // Otherwise reset hydration state in case we aborted and resumed another // root. @@ -13171,6 +13543,7 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { ); resetHydrationState(); } + return workInProgress.child; } @@ -13184,7 +13557,6 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current$$1 !== null ? current$$1.memoizedProps : null; - var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); @@ -13200,9 +13572,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { workInProgress.effectTag |= ContentReset; } - markRef(current$$1, workInProgress); + markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden. - // Check the host config to see if the children are offscreen/hidden. if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -13210,8 +13581,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } @@ -13228,9 +13599,9 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { function updateHostText(current$$1, workInProgress) { if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); - } - // Nothing to do here. This is terminal. We'll do the completion step + } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. + return null; } @@ -13247,22 +13618,23 @@ function mountLazyComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } - var props = workInProgress.pendingProps; - // We can't start a User Timing measurement with correct label yet. + var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet. // Cancel and resume right after we know the tag. + cancelWorkTimer(workInProgress); - var Component = readLazyComponentType(elementType); - // Store the unwrapped component in the type. + var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type. + workInProgress.type = Component; var resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); startWorkTimer(workInProgress); var resolvedProps = resolveDefaultProps(Component, props); - var child = void 0; + var child; + switch (resolvedTag) { case FunctionComponent: { { @@ -13271,6 +13643,7 @@ function mountLazyComponent( Component ); } + child = updateFunctionComponent( null, workInProgress, @@ -13280,12 +13653,14 @@ function mountLazyComponent( ); break; } + case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading( Component ); } + child = updateClassComponent( null, workInProgress, @@ -13295,12 +13670,14 @@ function mountLazyComponent( ); break; } + case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading( Component ); } + child = updateForwardRef( null, workInProgress, @@ -13310,10 +13687,12 @@ function mountLazyComponent( ); break; } + case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13325,6 +13704,7 @@ function mountLazyComponent( } } } + child = updateMemoComponent( null, workInProgress, @@ -13335,8 +13715,10 @@ function mountLazyComponent( ); break; } + default: { var hint = ""; + { if ( Component !== null && @@ -13345,24 +13727,21 @@ function mountLazyComponent( ) { hint = " Did you wrap a component in React.lazy() more than once?"; } - } - // This message intentionally doesn't mention ForwardRef or MemoComponent + } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - (function() { - { - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." + - hint - ) - ); - } - })(); + + { + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } } } + return child; } @@ -13379,28 +13758,26 @@ function mountIncompleteClassComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect - workInProgress.effectTag |= Placement; - } + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - // Promote the fiber to a class and try rendering again. - workInProgress.tag = ClassComponent; - - // The rest of this function is a fork of `updateClassComponent` + workInProgress.effectTag |= Placement; + } // Promote the fiber to a class and try rendering again. + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); constructClassInstance( workInProgress, Component, @@ -13413,7 +13790,6 @@ function mountIncompleteClassComponent( nextProps, renderExpirationTime ); - return finishClassComponent( null, workInProgress, @@ -13436,20 +13812,21 @@ function mountIndeterminateComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderExpirationTime); - var value = void 0; + var value; { if ( @@ -13483,8 +13860,8 @@ function mountIndeterminateComponent( context, renderExpirationTime ); - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; if ( @@ -13495,6 +13872,7 @@ function mountIndeterminateComponent( ) { { var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { warningWithoutStack$1( false, @@ -13509,18 +13887,16 @@ function mountIndeterminateComponent( ); didWarnAboutModulePatternComponent[_componentName] = true; } - } - - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; + } // Proceed under the assumption that this is a class instance - // Throw out any hooks that were used. - resetHooks(); + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - // Push context providers early to prevent context stack mismatches. + resetHooks(); // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. + var hasContext = false; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); @@ -13530,8 +13906,8 @@ function mountIndeterminateComponent( workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - var getDerivedStateFromProps = Component.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -13554,6 +13930,7 @@ function mountIndeterminateComponent( } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { if (disableLegacyContext && Component.contextTypes) { warningWithoutStack$1( @@ -13582,10 +13959,13 @@ function mountIndeterminateComponent( } } } + reconcileChildren(null, workInProgress, value, renderExpirationTime); + { validateFunctionComponentInDev(workInProgress, Component); } + return workInProgress.child; } } @@ -13600,18 +13980,22 @@ function validateFunctionComponentInDev(workInProgress, Component) { ) : void 0; } + if (workInProgress.ref !== null) { var info = ""; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } var warningKey = ownerName || workInProgress._debugID || ""; var debugSource = workInProgress._debugSource; + if (debugSource) { warningKey = debugSource.fileName + ":" + debugSource.lineNumber; } + if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; warning$1( @@ -13671,8 +14055,10 @@ function validateFunctionComponentInDev(workInProgress, Component) { } } -// TODO: This is now an empty object. Should we just make it a boolean? -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { + dehydrated: null, + retryTime: NoWork +}; function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) { // If the context is telling us that we should show a fallback, and we're not @@ -13689,9 +14075,8 @@ function updateSuspenseComponent( renderExpirationTime ) { var mode = workInProgress.mode; - var nextProps = workInProgress.pendingProps; + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.effectTag |= DidCapture; @@ -13699,17 +14084,15 @@ function updateSuspenseComponent( } var suspenseContext = suspenseStackCursor.current; - - var nextState = null; var nextDidTimeout = false; + var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect; if ( - (workInProgress.effectTag & DidCapture) !== NoEffect || + didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) ) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. - nextState = SUSPENDED_MARKER; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } else { @@ -13733,7 +14116,6 @@ function updateSuspenseComponent( } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); { @@ -13747,9 +14129,7 @@ function updateSuspenseComponent( ); } } - } - - // This next part is a bit confusing. If the children timeout, we switch to + } // This next part is a bit confusing. If the children timeout, we switch to // showing the fallback children in place of the "primary" children. // However, we don't want to delete the primary children because then their // state will be lost (both the React state and the host state, e.g. @@ -13771,35 +14151,30 @@ function updateSuspenseComponent( // custom reconciliation logic to preserve the state of the primary // children. It's essentially a very basic form of re-parenting. - // `child` points to the child fiber. In the normal case, this is the first - // fiber of the primary children set. In the timed-out case, it's a - // a fragment fiber containing the primary children. - var child = void 0; - // `next` points to the next fiber React should render. In the normal case, - // it's the same as `child`: the first fiber of the primary children set. - // In the timed-out case, it's a fragment fiber containing the *fallback* - // children -- we skip over the primary children entirely. - var next = void 0; if (current$$1 === null) { - if (enableSuspenseServerRenderer) { - // If we're currently hydrating, try to hydrate this boundary. - // But only if this has a fallback. - if (nextProps.fallback !== undefined) { - tryToClaimNextHydratableInstance(workInProgress); - // This could've changed the tag if this was a dehydrated suspense component. - if (workInProgress.tag === DehydratedSuspenseComponent) { - popSuspenseContext(workInProgress); - return updateDehydratedSuspenseComponent( - null, - workInProgress, - renderExpirationTime - ); + // If we're currently hydrating, try to hydrate this boundary. + // But only if this has a fallback. + if (nextProps.fallback !== undefined) { + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. + + if (enableSuspenseServerRenderer) { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent( + workInProgress, + dehydrated, + renderExpirationTime + ); + } } } - } - - // This is the initial mount. This branch is pretty simple because there's + } // This is the initial mount. This branch is pretty simple because there's // no previous state that needs to be preserved. + if (nextDidTimeout) { // Mount separate fragments for primary and fallback children. var nextFallbackChildren = nextProps.fallback; @@ -13813,6 +14188,7 @@ function updateSuspenseComponent( if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var progressedState = workInProgress.memoizedState; var progressedPrimaryChild = progressedState !== null @@ -13820,6 +14196,7 @@ function updateSuspenseComponent( : workInProgress.child; primaryChildFragment.child = progressedPrimaryChild; var progressedChild = progressedPrimaryChild; + while (progressedChild !== null) { progressedChild.return = primaryChildFragment; progressedChild = progressedChild.sibling; @@ -13833,85 +14210,192 @@ function updateSuspenseComponent( null ); fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - child = primaryChildFragment; - // Skip the primary children, and continue working on the + primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the // fallback children. - next = fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; } else { // Mount the primary children without an intermediate fragment fiber. var nextPrimaryChildren = nextProps.children; - child = next = mountChildFibers( + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( workInProgress, null, nextPrimaryChildren, renderExpirationTime - ); + )); } } else { // This is an update. This branch is more complicated because we need to // ensure the state of the primary children is preserved. var prevState = current$$1.memoizedState; - var prevDidTimeout = prevState !== null; - if (prevDidTimeout) { - // The current tree already timed out. That means each child set is + + if (prevState !== null) { + if (enableSuspenseServerRenderer) { + var _dehydrated = prevState.dehydrated; + + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent( + current$$1, + workInProgress, + _dehydrated, + prevState, + renderExpirationTime + ); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. + + workInProgress.effectTag |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. Wrap the children + // in a fragment fiber to keep them separate from the fallback + // children. + var _nextFallbackChildren = nextProps.fallback; + + var _primaryChildFragment = createFiberFromFragment( + // It shouldn't matter what the pending props are because we aren't + // going to render this fragment. + null, + mode, + NoWork, + null + ); + + _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child + // that we're not going to hydrate. + + _primaryChildFragment.child = null; + + if ((workInProgress.mode & BatchedMode) === NoMode) { + // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. + var _progressedChild = (_primaryChildFragment.child = + workInProgress.child); + + while (_progressedChild !== null) { + _progressedChild.return = _primaryChildFragment; + _progressedChild = _progressedChild.sibling; + } + } else { + // We will have dropped the effect list which contains the deletion. + // We need to reconcile to delete the current child. + reconcileChildFibers( + workInProgress, + current$$1.child, + null, + renderExpirationTime + ); + } // Because primaryChildFragment is a new fiber that we're inserting as the + // parent of a new tree, we need to set its treeBaseDuration. + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // treeBaseDuration is the sum of all the child tree base durations. + var treeBaseDuration = 0; + var hiddenChild = _primaryChildFragment.child; + + while (hiddenChild !== null) { + treeBaseDuration += hiddenChild.treeBaseDuration; + hiddenChild = hiddenChild.sibling; + } + + _primaryChildFragment.treeBaseDuration = treeBaseDuration; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment = createFiberFromFragment( + _nextFallbackChildren, + mode, + renderExpirationTime, + null + ); + + _fallbackChildFragment.return = workInProgress; + _primaryChildFragment.sibling = _fallbackChildFragment; + _fallbackChildFragment.effectTag |= Placement; + _primaryChildFragment.childExpirationTime = NoWork; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the + // fallback children. + + return _fallbackChildFragment; + } + } + } // The current tree already timed out. That means each child set is + // wrapped in a fragment fiber. + var currentPrimaryChildFragment = current$$1.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + if (nextDidTimeout) { // Still timed out. Reuse the current primary children by cloning // its fragment. We're going to skip over these entirely. - var _nextFallbackChildren = nextProps.fallback; - var _primaryChildFragment = createWorkInProgress( + var _nextFallbackChildren2 = nextProps.fallback; + + var _primaryChildFragment2 = createWorkInProgress( currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork ); - _primaryChildFragment.return = workInProgress; + + _primaryChildFragment2.return = workInProgress; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState = workInProgress.memoizedState; + var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child; + if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) { - _primaryChildFragment.child = _progressedPrimaryChild; - var _progressedChild = _progressedPrimaryChild; - while (_progressedChild !== null) { - _progressedChild.return = _primaryChildFragment; - _progressedChild = _progressedChild.sibling; + _primaryChildFragment2.child = _progressedPrimaryChild; + var _progressedChild2 = _progressedPrimaryChild; + + while (_progressedChild2 !== null) { + _progressedChild2.return = _primaryChildFragment2; + _progressedChild2 = _progressedChild2.sibling; } } - } - - // Because primaryChildFragment is a new fiber that we're inserting as the + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var treeBaseDuration = 0; - var hiddenChild = _primaryChildFragment.child; - while (hiddenChild !== null) { - treeBaseDuration += hiddenChild.treeBaseDuration; - hiddenChild = hiddenChild.sibling; + var _treeBaseDuration = 0; + var _hiddenChild = _primaryChildFragment2.child; + + while (_hiddenChild !== null) { + _treeBaseDuration += _hiddenChild.treeBaseDuration; + _hiddenChild = _hiddenChild.sibling; } - _primaryChildFragment.treeBaseDuration = treeBaseDuration; - } - // Clone the fallback child fragment, too. These we'll continue + _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; + } // Clone the fallback child fragment, too. These we'll continue // working on. - var _fallbackChildFragment = createWorkInProgress( + + var _fallbackChildFragment2 = createWorkInProgress( currentFallbackChildFragment, - _nextFallbackChildren, + _nextFallbackChildren2, currentFallbackChildFragment.expirationTime ); - _fallbackChildFragment.return = workInProgress; - _primaryChildFragment.sibling = _fallbackChildFragment; - child = _primaryChildFragment; - _primaryChildFragment.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment2.return = workInProgress; + _primaryChildFragment2.sibling = _fallbackChildFragment2; + _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment2; + return _fallbackChildFragment2; } else { // No longer suspended. Switch back to showing the primary children, // and remove the intermediate fragment fiber. @@ -13922,26 +14406,27 @@ function updateSuspenseComponent( currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime - ); - - // If this render doesn't suspend, we need to delete the fallback + ); // If this render doesn't suspend, we need to delete the fallback // children. Wait until the complete phase, after we've confirmed the // fallback is no longer needed. // TODO: Would it be better to store the fallback fragment on // the stateNode? - // Continue rendering the children, like we normally do. - child = next = primaryChild; + + workInProgress.memoizedState = null; + return (workInProgress.child = primaryChild); } } else { // The current tree has not already timed out. That means the primary // children are not wrapped in a fragment fiber. var _currentPrimaryChild = current$$1.child; + if (nextDidTimeout) { // Timed out. Wrap the children in a fragment fiber to keep them // separate from the fallback children. - var _nextFallbackChildren2 = nextProps.fallback; - var _primaryChildFragment2 = createFiberFromFragment( + var _nextFallbackChildren3 = nextProps.fallback; + + var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't // going to render this fragment. null, @@ -13949,78 +14434,80 @@ function updateSuspenseComponent( NoWork, null ); - _primaryChildFragment2.return = workInProgress; - _primaryChildFragment2.child = _currentPrimaryChild; - if (_currentPrimaryChild !== null) { - _currentPrimaryChild.return = _primaryChildFragment2; - } - // Even though we're creating a new fiber, there are no new children, + _primaryChildFragment3.return = workInProgress; + _primaryChildFragment3.child = _currentPrimaryChild; + + if (_currentPrimaryChild !== null) { + _currentPrimaryChild.return = _primaryChildFragment3; + } // Even though we're creating a new fiber, there are no new children, // because we're reusing an already mounted tree. So we don't need to // schedule a placement. // primaryChildFragment.effectTag |= Placement; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState2 = workInProgress.memoizedState; + var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child; - _primaryChildFragment2.child = _progressedPrimaryChild2; - var _progressedChild2 = _progressedPrimaryChild2; - while (_progressedChild2 !== null) { - _progressedChild2.return = _primaryChildFragment2; - _progressedChild2 = _progressedChild2.sibling; - } - } - // Because primaryChildFragment is a new fiber that we're inserting as the + _primaryChildFragment3.child = _progressedPrimaryChild2; + var _progressedChild3 = _progressedPrimaryChild2; + + while (_progressedChild3 !== null) { + _progressedChild3.return = _primaryChildFragment3; + _progressedChild3 = _progressedChild3.sibling; + } + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var _treeBaseDuration = 0; - var _hiddenChild = _primaryChildFragment2.child; - while (_hiddenChild !== null) { - _treeBaseDuration += _hiddenChild.treeBaseDuration; - _hiddenChild = _hiddenChild.sibling; + var _treeBaseDuration2 = 0; + var _hiddenChild2 = _primaryChildFragment3.child; + + while (_hiddenChild2 !== null) { + _treeBaseDuration2 += _hiddenChild2.treeBaseDuration; + _hiddenChild2 = _hiddenChild2.sibling; } - _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; - } - // Create a fragment from the fallback children, too. - var _fallbackChildFragment2 = createFiberFromFragment( - _nextFallbackChildren2, + _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment3 = createFiberFromFragment( + _nextFallbackChildren3, mode, renderExpirationTime, null ); - _fallbackChildFragment2.return = workInProgress; - _primaryChildFragment2.sibling = _fallbackChildFragment2; - _fallbackChildFragment2.effectTag |= Placement; - child = _primaryChildFragment2; - _primaryChildFragment2.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment3.return = workInProgress; + _primaryChildFragment3.sibling = _fallbackChildFragment3; + _fallbackChildFragment3.effectTag |= Placement; + _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment2; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment3; + return _fallbackChildFragment3; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. + workInProgress.memoizedState = null; var _nextPrimaryChildren2 = nextProps.children; - next = child = reconcileChildFibers( + return (workInProgress.child = reconcileChildFibers( workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime - ); + )); } } - workInProgress.stateNode = current$$1.stateNode; } - - workInProgress.memoizedState = nextState; - workInProgress.child = child; - return next; } function retrySuspenseComponentWithoutHydrating( @@ -14028,90 +14515,95 @@ function retrySuspenseComponentWithoutHydrating( workInProgress, renderExpirationTime ) { - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; + // We're now not suspended nor dehydrated. + workInProgress.memoizedState = null; // Retry with the full children. - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - (function() { - if (!(returnFiber !== null)) { - throw ReactError( - Error( - "Suspense boundaries are never on the root. This is probably a bug in React." - ) + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and + // that the old child gets a Deletion effect. + // We could also call forceUnmountCurrentAndReconcile. + + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} + +function mountDehydratedSuspenseComponent( + workInProgress, + suspenseInstance, + renderExpirationTime +) { + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & BatchedMode) === NoMode) { + { + warning$1( + false, + "Cannot hydrate Suspense in legacy mode. Switch from " + + "ReactDOM.hydrate(element, container) to " + + "ReactDOM.unstable_createSyncRoot(container, { hydrate: true })" + + ".render(element) or remove the Suspense components from " + + "the server rendered components." ); } - })(); - var last = returnFiber.lastEffect; - if (last !== null) { - last.nextEffect = current$$1; - returnFiber.lastEffect = current$$1; + + workInProgress.expirationTime = Sync; + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content. + + var newExpirationTime = computeAsyncExpiration(serverDisplayTime); + + if (enableSchedulerTracing) { + markSpawnedWork(newExpirationTime); + } + + workInProgress.expirationTime = newExpirationTime; } else { - returnFiber.firstEffect = returnFiber.lastEffect = current$$1; - } - current$$1.nextEffect = null; - current$$1.effectTag = Deletion; + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.expirationTime = Never; - popSuspenseContext(workInProgress); + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + } - // Upgrade this work in progress to a real Suspense component. - workInProgress.tag = SuspenseComponent; - workInProgress.stateNode = null; - workInProgress.memoizedState = null; - // This is now an insertion. - workInProgress.effectTag |= Placement; - // Retry as a real Suspense component. - return updateSuspenseComponent(null, workInProgress, renderExpirationTime); + return null; } function updateDehydratedSuspenseComponent( current$$1, workInProgress, + suspenseInstance, + suspenseState, renderExpirationTime ) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - var suspenseInstance = workInProgress.stateNode; - if (current$$1 === null) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - var serverDisplayTime = requestCurrentTime(); - // Schedule a normal pri update to render this content. - workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.expirationTime = Never; - } - return null; - } - - if ((workInProgress.effectTag & DidCapture) !== NoEffect) { - // Something suspended. Leave the existing children in place. - // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far? - workInProgress.child = null; - return null; - } - // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); + if ((workInProgress.mode & BatchedMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime + ); + } + if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the @@ -14121,18 +14613,38 @@ function updateDehydratedSuspenseComponent( workInProgress, renderExpirationTime ); - } - // We use childExpirationTime to indicate that a child might depend on context, so if + } // We use childExpirationTime to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. + var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime; + if (didReceiveUpdate || hasContextChanged$$1) { // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using an earlier expiration time but - // during this render we can't. Instead, we're going to delete the whole subtree and - // instead inject a new real Suspense boundary to take its place, which may render content - // or fallback. The real Suspense boundary will suspend for a while so we have some time - // to ensure it can produce real content, but all state and pending events will be lost. + // hydrate it. We might still be able to hydrate it using an earlier expiration time, if + // we are rendering at lower expiration than sync. + if (renderExpirationTime < Sync) { + if (suspenseState.retryTime <= renderExpirationTime) { + // This render is even higher pri than we've seen before, let's try again + // at even higher pri. + var attemptHydrationAtExpirationTime = renderExpirationTime + 1; + suspenseState.retryTime = attemptHydrationAtExpirationTime; + scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render. + } else { + // We have already tried to ping at a higher priority than we're rendering with + // so if we got here, we must have failed to hydrate at those levels. We must + // now give up. Instead, we're going to delete the whole subtree and instead inject + // a new real Suspense boundary to take its place, which may render content + // or fallback. This might suspend for a while and if it does we might still have + // an opportunity to hydrate before this pass commits. + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. + + renderDidSuspendDelayIfPossible(); return retrySuspenseComponentWithoutHydrating( current$$1, workInProgress, @@ -14148,30 +14660,61 @@ function updateDehydratedSuspenseComponent( // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). - workInProgress.effectTag |= DidCapture; - // Leave the children in place. I.e. empty. - workInProgress.child = null; - // Register a callback to retry this boundary once the server has sent the result. + workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. + + workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result. + registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryDehydratedSuspenseBoundary.bind(null, current$$1) ); return null; } else { // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress); + reenterHydrationStateFromDehydratedSuspenseInstance( + workInProgress, + suspenseInstance + ); var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag |= Hydrating; + node = node.sibling; + } + + workInProgress.child = child; return workInProgress.child; } } +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + if (fiber.expirationTime < renderExpirationTime) { + fiber.expirationTime = renderExpirationTime; + } + + var alternate = fiber.alternate; + + if (alternate !== null && alternate.expirationTime < renderExpirationTime) { + alternate.expirationTime = renderExpirationTime; + } + + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); +} + function propagateSuspenseContextChange( workInProgress, firstChild, @@ -14181,36 +14724,39 @@ function propagateSuspenseContextChange( // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - if (node.expirationTime < renderExpirationTime) { - node.expirationTime = renderExpirationTime; - } - var alternate = node.alternate; - if ( - alternate !== null && - alternate.expirationTime < renderExpirationTime - ) { - alternate.expirationTime = renderExpirationTime; - } - scheduleWorkOnParentPath(node.return, renderExpirationTime); - } + scheduleWorkOnFiber(node, renderExpirationTime); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleWorkOnFiber(node, renderExpirationTime); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -14226,14 +14772,17 @@ function findLastContentRow(firstChild) { // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } + row = row.sibling; } + return lastContentRow; } @@ -14247,6 +14796,7 @@ function validateRevealOrder(revealOrder) { !didWarnAboutRevealOrder[revealOrder] ) { didWarnAboutRevealOrder[revealOrder] = true; + if (typeof revealOrder === "string") { switch (revealOrder.toLowerCase()) { case "together": @@ -14261,6 +14811,7 @@ function validateRevealOrder(revealOrder) { ); break; } + case "forward": case "backward": { warning$1( @@ -14272,6 +14823,7 @@ function validateRevealOrder(revealOrder) { ); break; } + default: warning$1( false, @@ -14322,6 +14874,7 @@ function validateSuspenseListNestedChild(childSlot, index) { { var isArray = Array.isArray(childSlot); var isIterable = !isArray && typeof getIteratorFn(childSlot) === "function"; + if (isArray || isIterable) { var type = isArray ? "array" : "iterable"; warning$1( @@ -14338,6 +14891,7 @@ function validateSuspenseListNestedChild(childSlot, index) { return false; } } + return true; } @@ -14357,15 +14911,19 @@ function validateSuspenseListChildren(children, revealOrder) { } } else { var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { var childrenIterator = iteratorFn.call(children); + if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; + for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } + _i++; } } @@ -14388,9 +14946,11 @@ function initSuspenseListRenderState( isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; + if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, @@ -14398,7 +14958,8 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }; } else { // We can reuse the existing object from previous renders. @@ -14408,16 +14969,16 @@ function initSuspenseListRenderState( renderState.tail = tail; renderState.tailExpiration = 0; renderState.tailMode = tailMode; + renderState.lastEffect = lastEffectBeforeRendering; } -} - -// This can end up rendering this component multiple passes. +} // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. + function updateSuspenseListComponent( current$$1, workInProgress, @@ -14427,24 +14988,21 @@ function updateSuspenseListComponent( var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; - validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren( current$$1, workInProgress, newChildren, renderExpirationTime ); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext( suspenseContext, ForceSuspenseFallback ); + if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -14454,6 +15012,7 @@ function updateSuspenseListComponent( } else { var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect; + if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render @@ -14464,8 +15023,10 @@ function updateSuspenseListComponent( renderExpirationTime ); } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } + pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & BatchedMode) === NoMode) { @@ -14476,7 +15037,8 @@ function updateSuspenseListComponent( switch (revealOrder) { case "forwards": { var lastContentRow = findLastContentRow(workInProgress.child); - var tail = void 0; + var tail; + if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. @@ -14488,15 +15050,18 @@ function updateSuspenseListComponent( tail = lastContentRow.sibling; lastContentRow.sibling = null; } + initSuspenseListRenderState( workInProgress, false, // isBackwards tail, lastContentRow, - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "backwards": { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything @@ -14505,39 +15070,45 @@ function updateSuspenseListComponent( var _tail = null; var row = workInProgress.child; workInProgress.child = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } + var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; - } - // TODO: If workInProgress.child is null, we can continue on the tail immediately. + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. + initSuspenseListRenderState( workInProgress, true, // isBackwards _tail, null, // last - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "together": { initSuspenseListRenderState( workInProgress, false, // isBackwards null, // tail null, // last - undefined + undefined, + workInProgress.lastEffect ); break; } + default: { // The default reveal order is the same as not having // a boundary. @@ -14545,6 +15116,7 @@ function updateSuspenseListComponent( } } } + return workInProgress.child; } @@ -14555,6 +15127,7 @@ function updatePortalComponent( ) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; + if (current$$1 === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal @@ -14575,6 +15148,7 @@ function updatePortalComponent( renderExpirationTime ); } + return workInProgress.child; } @@ -14585,10 +15159,8 @@ function updateContextProvider( ) { var providerType = workInProgress.type; var context = providerType._context; - var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; { @@ -14610,6 +15182,7 @@ function updateContextProvider( if (oldProps !== null) { var oldValue = oldProps.value; var changedBits = calculateChangedBits(context, newValue, oldValue); + if (changedBits === 0) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { @@ -14648,14 +15221,14 @@ function updateContextConsumer( workInProgress, renderExpirationTime ) { - var context = workInProgress.type; - // The logic below for Context differs depending on PROD or DEV mode. In + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. + { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). @@ -14675,6 +15248,7 @@ function updateContextConsumer( context = context._context; } } + var newProps = workInProgress.pendingProps; var render = newProps.children; @@ -14692,15 +15266,15 @@ function updateContextConsumer( prepareToReadContext(workInProgress, renderExpirationTime); var newValue = readContext(context, newProps.unstable_observedBits); - var newChildren = void 0; + var newChildren; + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); newChildren = render(newValue); setCurrentPhase(null); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -14717,12 +15291,29 @@ function updateFundamentalComponent$1( renderExpirationTime ) { var fundamentalImpl = workInProgress.type.impl; + if (fundamentalImpl.reconcileChildren === false) { return null; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} +function updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; reconcileChildren( current$$1, workInProgress, @@ -14753,8 +15344,14 @@ function bailoutOnAlreadyFinishedWork( stopProfilerTimerIfRunning(workInProgress); } - // Check if the children have any pending work. + var updateExpirationTime = workInProgress.expirationTime; + + if (updateExpirationTime !== NoWork) { + markUnprocessedUpdateTime(updateExpirationTime); + } // Check if the children have any pending work. + var childExpirationTime = workInProgress.childExpirationTime; + if (childExpirationTime < renderExpirationTime) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are @@ -14771,53 +15368,54 @@ function bailoutOnAlreadyFinishedWork( function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { throw new Error("Cannot swap the root fiber."); - } - - // Disconnect from the old current. + } // Disconnect from the old current. // It will get deleted. + current$$1.alternate = null; - oldWorkInProgress.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; + if (prevSibling === null) { throw new Error("Expected parent to have a child."); } + while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; + if (prevSibling === null) { throw new Error("Expected to find the previous sibling."); } } - prevSibling.sibling = newWorkInProgress; - } - // Delete the old fiber and place the new one. + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = current$$1; returnFiber.lastEffect = current$$1; } else { returnFiber.firstEffect = returnFiber.lastEffect = current$$1; } + current$$1.nextEffect = null; current$$1.effectTag = Deletion; + newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber. - newWorkInProgress.effectTag |= Placement; - - // Restart work from the new fiber. return newWorkInProgress; } } @@ -14849,25 +15447,26 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { if ( oldProps !== newProps || - hasContextChanged() || - // Force a re-render if the implementation changed due to hot reload: + hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current$$1.type ) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else if (updateExpirationTime < renderExpirationTime) { - didReceiveUpdate = false; - // This fiber does not have any pending work. Bailout without entering + didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); resetHydrationState(); break; + case HostComponent: pushHostContext(workInProgress); + if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -14875,45 +15474,69 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } + break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { pushContextProvider(workInProgress); } + break; } + case HostPortal: pushHostContainer( workInProgress, workInProgress.stateNode.containerInfo ); break; + case ContextProvider: { var newValue = workInProgress.memoizedProps.value; pushProvider(workInProgress, newValue); break; } + case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + break; + case SuspenseComponent: { var state = workInProgress.memoizedState; - var didTimeout = state !== null; - if (didTimeout) { - // If this boundary is currently timed out, we need to decide + + if (state !== null) { + if (enableSuspenseServerRenderer) { + if (state.dehydrated !== null) { + pushSuspenseContext( + workInProgress, + setDefaultShallowSuspenseContext(suspenseStackCursor.current) + ); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. + + workInProgress.effectTag |= DidCapture; + break; + } + } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary + // child fragment. + var primaryChildFragment = workInProgress.child; var primaryChildExpirationTime = primaryChildFragment.childExpirationTime; + if ( primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime @@ -14929,14 +15552,15 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // The primary children do not have pending work with sufficient + ); // The primary children do not have pending work with sufficient // priority. Bailout. + var child = bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. @@ -14951,25 +15575,13 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { setDefaultShallowSuspenseContext(suspenseStackCursor.current) ); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // We know that this component will suspend again because if it has - // been unsuspended it has committed as a regular Suspense component. - // If it needs to be retried, it should have work scheduled on it. - workInProgress.effectTag |= DidCapture; - } - break; - } + case SuspenseListComponent: { var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect; - var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime; @@ -14985,23 +15597,24 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { workInProgress, renderExpirationTime ); - } - // If none of the children had any work, that means that none of + } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. - workInProgress.effectTag |= DidCapture; - } - // If nothing suspended before and we're rendering the same children, + workInProgress.effectTag |= DidCapture; + } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. + var renderState = workInProgress.memoizedState; + if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (hasChildWork) { @@ -15014,17 +15627,23 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + return bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; } } else { didReceiveUpdate = false; - } + } // Before entering the begin phase, clear the expiration time. - // Before entering the begin phase, clear the expiration time. workInProgress.expirationTime = NoWork; switch (workInProgress.tag) { @@ -15036,6 +15655,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent( @@ -15046,6 +15666,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FunctionComponent: { var _Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; @@ -15061,13 +15682,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case ClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; + var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps); + return updateClassComponent( current$$1, workInProgress, @@ -15076,35 +15700,43 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case HostRoot: return updateHostRoot(current$$1, workInProgress, renderExpirationTime); + case HostComponent: return updateHostComponent( current$$1, workInProgress, renderExpirationTime ); + case HostText: return updateHostText(current$$1, workInProgress); + case SuspenseComponent: return updateSuspenseComponent( current$$1, workInProgress, renderExpirationTime ); + case HostPortal: return updatePortalComponent( current$$1, workInProgress, renderExpirationTime ); + case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef( current$$1, workInProgress, @@ -15113,32 +15745,40 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case Fragment: return updateFragment(current$$1, workInProgress, renderExpirationTime); + case Mode: return updateMode(current$$1, workInProgress, renderExpirationTime); + case Profiler: return updateProfiler(current$$1, workInProgress, renderExpirationTime); + case ContextProvider: return updateContextProvider( current$$1, workInProgress, renderExpirationTime ); + case ContextConsumer: return updateContextConsumer( current$$1, workInProgress, renderExpirationTime ); + case MemoComponent: { var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; - // Resolve outer props first, then resolve inner props. + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -15150,6 +15790,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent( current$$1, @@ -15160,6 +15801,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case SimpleMemoComponent: { return updateSimpleMemoComponent( current$$1, @@ -15170,13 +15812,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case IncompleteClassComponent: { var _Component3 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; + var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4); + return mountIncompleteClassComponent( current$$1, workInProgress, @@ -15185,16 +15830,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - return updateDehydratedSuspenseComponent( - current$$1, - workInProgress, - renderExpirationTime - ); - } - break; - } + case SuspenseListComponent: { return updateSuspenseListComponent( current$$1, @@ -15202,6 +15838,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FundamentalComponent: { if (enableFundamentalAPI) { return updateFundamentalComponent$1( @@ -15210,18 +15847,30 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + break; } - } - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + return updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime + ); + } + + break; } - })(); + } + + { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); + } } function createFundamentalStateInstance(currentFiber, props, impl, state) { @@ -15235,8 +15884,212 @@ function createFundamentalStateInstance(currentFiber, props, impl, state) { }; } -var emptyObject$1 = {}; -var isArray$2 = Array.isArray; +function isFiberSuspenseAndTimedOut(fiber) { + return fiber.tag === SuspenseComponent && fiber.memoizedState !== null; +} + +function getSuspenseFallbackChild(fiber) { + return fiber.child.sibling.child; +} + +function collectScopedNodes(node, fn, scopedNodes) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type, memoizedProps) === true) { + scopedNodes.push(getPublicInstance(node.stateNode)); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + } +} + +function collectFirstScopedNode(node, fn) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type2 = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type2, memoizedProps) === true) { + return getPublicInstance(node.stateNode); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + } + + return null; +} + +function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) { + var child = startingChild; + + while (child !== null) { + collectScopedNodes(child, fn, scopedNodes); + child = child.sibling; + } +} + +function collectFirstScopedNodeFromChildren(startingChild, fn) { + var child = startingChild; + + while (child !== null) { + var scopedNode = collectFirstScopedNode(child, fn); + + if (scopedNode !== null) { + return scopedNode; + } + + child = child.sibling; + } + + return null; +} + +function collectNearestScopeMethods(node, scope, childrenScopes) { + if (isValidScopeNode(node, scope)) { + childrenScopes.push(node.stateNode.methods); + } else { + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + } +} + +function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) { + var child = startingChild; + + while (child !== null) { + collectNearestScopeMethods(child, scope, childrenScopes); + child = child.sibling; + } +} + +function isValidScopeNode(node, scope) { + return ( + node.tag === ScopeComponent && + node.type === scope && + node.stateNode !== null + ); +} + +function createScopeMethods(scope, instance) { + return { + getChildren: function() { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var childrenScopes = []; + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getChildrenFromRoot: function() { + var currentFiber = instance.fiber; + var node = currentFiber; + + while (node !== null) { + var parent = node.return; + + if (parent === null) { + break; + } + + node = parent; + + if (node.tag === ScopeComponent && node.type === scope) { + break; + } + } + + var childrenScopes = []; + collectNearestChildScopeMethods(node.child, scope, childrenScopes); + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getParent: function() { + var node = instance.fiber.return; + + while (node !== null) { + if (node.tag === ScopeComponent && node.type === scope) { + return node.stateNode.methods; + } + + node = node.return; + } + + return null; + }, + getProps: function() { + var currentFiber = instance.fiber; + return currentFiber.memoizedProps; + }, + queryAllNodes: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var scopedNodes = []; + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + + return scopedNodes.length === 0 ? null : scopedNodes; + }, + queryFirstNode: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + + return null; + }, + containsNode: function(node) { + var fiber = getInstanceFromNode$1(node); + + while (fiber !== null) { + if ( + fiber.tag === ScopeComponent && + fiber.type === scope && + fiber.stateNode === instance + ) { + return true; + } + + fiber = fiber.return; + } + + return false; + } + }; +} function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into @@ -15248,13 +16101,13 @@ function markRef$1(workInProgress) { workInProgress.effectTag |= Ref; } -var appendAllChildren = void 0; -var updateHostContainer = void 0; -var updateHostComponent$1 = void 0; -var updateHostText$1 = void 0; +var appendAllChildren; +var updateHostContainer; +var updateHostComponent$1; +var updateHostText$1; + if (supportsMutation) { // Mutation mode - appendAllChildren = function( parent, workInProgress, @@ -15264,6 +16117,7 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); @@ -15278,15 +16132,19 @@ if (supportsMutation) { node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -15295,6 +16153,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15305,21 +16164,21 @@ if (supportsMutation) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; + if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; - } - - // If we get updated because one of our children updated, we don't + } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. + var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. + var updatePayload = prepareUpdate( instance, type, @@ -15327,15 +16186,16 @@ if (supportsMutation) { newProps, rootContainerInstance, currentHostContext - ); - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. + if (updatePayload) { markUpdate(workInProgress); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { @@ -15344,7 +16204,6 @@ if (supportsMutation) { }; } else if (supportsPersistence) { // Persistent host tree mode - appendAllChildren = function( parent, workInProgress, @@ -15354,33 +16213,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance = cloneHiddenTextInstance(_instance, text, node); } + appendInitialChild(parent, _instance); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance2 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props = node.memoizedProps; var _type = node.type; _instance2 = cloneHiddenInstance(_instance2, _type, _props, node); } + appendInitialChild(parent, _instance2); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15390,8 +16256,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15402,7 +16270,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15411,6 +16281,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15421,24 +16292,27 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - }; + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - // An unfortunate fork of appendAllChildren because we have two different parent types. var appendAllChildrenToContainer = function( containerChildSet, workInProgress, @@ -15448,33 +16322,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance3 = cloneHiddenTextInstance(_instance3, text, node); } + appendChildToContainerChildSet(containerChildSet, _instance3); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance4 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props2 = node.memoizedProps; var _type2 = node.type; _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node); } + appendChildToContainerChildSet(containerChildSet, _instance4); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15484,8 +16365,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15496,7 +16379,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15505,6 +16390,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15515,38 +16401,45 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } }; + updateHostContainer = function(workInProgress) { var portalOrRoot = workInProgress.stateNode; var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged) { // No changes, just reuse the existing instance. } else { var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. + markUpdate(workInProgress); finalizeContainerChildren(container, newChildSet); } }; + updateHostComponent$1 = function( current, workInProgress, @@ -15555,19 +16448,22 @@ if (supportsMutation) { rootContainerInstance ) { var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; - // If there are no effects associated with this node, then none of our children had any updates. + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. // This guarantees that we can reuse all of them. + var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged && oldProps === newProps) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var recyclableInstance = workInProgress.stateNode; var currentHostContext = getHostContext(); var updatePayload = null; + if (oldProps !== newProps) { updatePayload = prepareUpdate( recyclableInstance, @@ -15578,12 +16474,14 @@ if (supportsMutation) { currentHostContext ); } + if (childrenUnchanged && updatePayload === null) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var newInstance = cloneInstance( currentInstance, updatePayload, @@ -15594,6 +16492,7 @@ if (supportsMutation) { childrenUnchanged, recyclableInstance ); + if ( finalizeInitialChildren( newInstance, @@ -15605,7 +16504,9 @@ if (supportsMutation) { ) { markUpdate(workInProgress); } + workInProgress.stateNode = newInstance; + if (childrenUnchanged) { // If there are no other effects in this tree, we need to flag this node as having one. // Even though we're not going to use it for anything. @@ -15616,6 +16517,7 @@ if (supportsMutation) { appendAllChildren(newInstance, workInProgress, false, false); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { if (oldText !== newText) { // If the text content differs, we'll create a new text instance for it. @@ -15626,9 +16528,9 @@ if (supportsMutation) { rootContainerInstance, currentHostContext, workInProgress - ); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. + ); // We'll have to mark it as having an effect, even though we won't use the effect for anything. // This lets the parents know that at least one of their children has changed. + markUpdate(workInProgress); } }; @@ -15637,6 +16539,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15646,6 +16549,7 @@ if (supportsMutation) { ) { // Noop }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // Noop }; @@ -15661,14 +16565,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var tailNode = renderState.tail; var lastTailNode = null; + while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } + tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; @@ -15677,8 +16583,10 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. lastTailNode.sibling = null; } + break; } + case "collapsed": { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries @@ -15687,14 +16595,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; + while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } + _tailNode = _tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { @@ -15709,6 +16619,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. _lastTailNode.sibling = null; } + break; } } @@ -15720,41 +16631,55 @@ function completeWork(current, workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case IndeterminateComponent: break; + case LazyComponent: break; + case SimpleMemoComponent: case FunctionComponent: break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + break; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var fiberRoot = workInProgress.stateNode; + if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } + if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. - popHydrationState(workInProgress); - // This resets the hacky state to fix isMounted before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag &= ~Placement; + var wasHydrated = popHydrationState(workInProgress); + + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } } + updateHostContainer(workInProgress); break; } + case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; + if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1( current, @@ -15767,14 +16692,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableFlareAPI) { var prevListeners = current.memoizedProps.listeners; var nextListeners = newProps.listeners; - var instance = workInProgress.stateNode; + if (prevListeners !== nextListeners) { - updateEventListeners( - nextListeners, - instance, - rootContainerInstance, - workInProgress - ); + markUpdate(workInProgress); } } @@ -15783,26 +16703,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. + break; } - var currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on we want to add then top->down or // bottom->up. Top->down is faster in IE11. - var wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { + + var _wasHydrated = popHydrationState(workInProgress); + + if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if ( @@ -15816,47 +16733,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { // commit-phase we mark this as such. markUpdate(workInProgress); } + if (enableFlareAPI) { - var _instance5 = workInProgress.stateNode; var listeners = newProps.listeners; + if (listeners != null) { updateEventListeners( listeners, - _instance5, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } } } else { - var _instance6 = createInstance( + var instance = createInstance( type, newProps, rootContainerInstance, currentHostContext, workInProgress ); + appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners - appendAllChildren(_instance6, workInProgress, false, false); + workInProgress.stateNode = instance; if (enableFlareAPI) { var _listeners = newProps.listeners; + if (_listeners != null) { updateEventListeners( _listeners, - _instance6, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } - } - - // Certain renderers require commit-time effects for initial mount. + } // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. + if ( finalizeInitialChildren( - _instance6, + instance, type, newProps, rootContainerInstance, @@ -15865,7 +16782,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { ) { markUpdate(workInProgress); } - workInProgress.stateNode = _instance6; } if (workInProgress.ref !== null) { @@ -15873,32 +16789,34 @@ function completeWork(current, workInProgress, renderExpirationTime) { markRef$1(workInProgress); } } + break; } + case HostText: { var newText = newProps; + if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. + updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress); - if (_wasHydrated) { + + var _wasHydrated2 = popHydrationState(workInProgress); + + if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } @@ -15911,38 +16829,86 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); } } + break; } + case ForwardRef: break; + case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; + + if (enableSuspenseServerRenderer) { + if (nextState !== null && nextState.dehydrated !== null) { + if (current === null) { + var _wasHydrated3 = popHydrationState(workInProgress); + + if (!_wasHydrated3) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + + prepareToHydrateHostSuspenseInstance(workInProgress); + + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + + return null; + } else { + // We should never have been in a hydration state if we didn't have a current. + // However, in some of those paths, we might have reentered a hydration state + // and then we might be inside a hydration state. In that case, we'll need to + // exit out of it. + resetHydrationState(); + + if ((workInProgress.effectTag & DidCapture) === NoEffect) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. + + workInProgress.effectTag |= Update; + return null; + } + } + } + if ((workInProgress.effectTag & DidCapture) !== NoEffect) { // Something suspended. Re-render with the fallback children. - workInProgress.expirationTime = renderExpirationTime; - // Do not reset the effect list. + workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list. + return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = false; + if (current === null) { - // In cases where we didn't find a suitable hydration boundary we never - // downgraded this to a DehydratedSuspenseComponent, but we still need to - // pop the hydration state since we might be inside the insertion tree. - popHydrationState(workInProgress); + if (workInProgress.memoizedProps.fallback !== undefined) { + popHydrationState(workInProgress); + } } else { var prevState = current.memoizedState; prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { // We just switched from the fallback to the normal children. // Delete the fallback. // TODO: Would it be better to store the fallback fragment on + // the stateNode during the begin phase? var currentFallbackChild = current.child.sibling; + if (currentFallbackChild !== null) { // Deletions go at the beginning of the return fiber's effect list var first = workInProgress.firstEffect; + if (first !== null) { workInProgress.firstEffect = currentFallbackChild; currentFallbackChild.nextEffect = first; @@ -15950,6 +16916,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; currentFallbackChild.nextEffect = null; } + currentFallbackChild.effectTag = Deletion; } } @@ -15972,6 +16939,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true; + if ( hasInvisibleChildContext || hasSuspenseContext( @@ -15999,6 +16967,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if (supportsMutation) { // TODO: Only schedule updates if these values are non equal, i.e. it changed. if (nextDidTimeout || prevDidTimeout) { @@ -16010,6 +16979,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if ( enableSuspenseCallback && workInProgress.updateQueue !== null && @@ -16018,76 +16988,49 @@ function completeWork(current, workInProgress, renderExpirationTime) { // Always notify the callback workInProgress.effectTag |= Update; } + break; } + case Fragment: break; + case Mode: break; + case Profiler: break; + case HostPortal: popHostContainer(workInProgress); updateHostContainer(workInProgress); break; + case ContextProvider: // Pop provider fiber popProvider(workInProgress); break; + case ContextConsumer: break; + case MemoComponent: break; + case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; + if (isContextProvider(_Component)) { popContext(workInProgress); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (current === null) { - var _wasHydrated2 = popHydrationState(workInProgress); - (function() { - if (!_wasHydrated2) { - throw ReactError( - Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ) - ); - } - })(); - if (enableSchedulerTracing) { - markSpawnedWork(Never); - } - skipPastDehydratedSuspenseInstance(workInProgress); - } else { - // We should never have been in a hydration state if we didn't have a current. - // However, in some of those paths, we might have reentered a hydration state - // and then we might be inside a hydration state. In that case, we'll need to - // exit out of it. - resetHydrationState(); - if ((workInProgress.effectTag & DidCapture) === NoEffect) { - // This boundary did not suspend so it's now hydrated. - // To handle any future suspense cases, we're going to now upgrade it - // to a Suspense component. We detach it from the existing current fiber. - current.alternate = null; - workInProgress.alternate = null; - workInProgress.tag = SuspenseComponent; - workInProgress.memoizedState = null; - workInProgress.stateNode = null; - } - } - } - break; - } + case SuspenseListComponent: { popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; if (renderState === null) { @@ -16098,18 +17041,16 @@ function completeWork(current, workInProgress, renderExpirationTime) { var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect; - var renderedTail = renderState.rendering; + if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. - // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to @@ -16117,16 +17058,17 @@ function completeWork(current, workInProgress, renderExpirationTime) { var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect); + if (!cannotBeSuspended) { var row = workInProgress.child; + while (row !== null) { var suspended = findFirstSuspended(row); + if (suspended !== null) { didSuspendAlready = true; workInProgress.effectTag |= DidCapture; - cutOffTailIfNeeded(renderState, false); - - // If this is a newly suspended tree, it might not get committed as + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thennables. Instead, we'll transfer its thennables to the // SuspenseList so that it can retry if they resolve. @@ -16138,21 +17080,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. + var newThennables = suspended.updateQueue; + if (newThennables !== null) { workInProgress.updateQueue = newThennables; workInProgress.effectTag |= Update; - } - - // Rerender the whole list, but this time, we'll force fallbacks + } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect list before doing the second pass since that's now invalid. - workInProgress.firstEffect = workInProgress.lastEffect = null; - // Reset the child fibers to their original state. - resetChildFibers(workInProgress, renderExpirationTime); - // Set up the Suspense Context to force suspense and immediately + if (renderState.lastEffect === null) { + workInProgress.firstEffect = null; + } + + workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state. + + resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately // rerender the children. + pushSuspenseContext( workInProgress, setShallowSuspenseContext( @@ -16162,42 +17108,46 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); return workInProgress.child; } + row = row.sibling; } } } else { cutOffTailIfNeeded(renderState, false); - } - // Next we're going to render the tail. + } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { workInProgress.effectTag |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, true); - // This might have been modified. + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. + + var _newThennables = _suspended.updateQueue; + + if (_newThennables !== null) { + workInProgress.updateQueue = _newThennables; + workInProgress.effectTag |= Update; + } + + cutOffTailIfNeeded(renderState, true); // This might have been modified. + if ( renderState.tail === null && renderState.tailMode === "hidden" ) { // We need to delete the row we just rendered. - // Ensure we transfer the update queue to the parent. - var _newThennables = _suspended.updateQueue; - if (_newThennables !== null) { - workInProgress.updateQueue = _newThennables; - workInProgress.effectTag |= Update; - } // Reset the effect list to what it w as before we rendered this // child. The nested children have already appended themselves. var lastEffect = (workInProgress.lastEffect = - renderState.lastEffect); - // Remove any effects that were appended after this point. + renderState.lastEffect); // Remove any effects that were appended after this point. + if (lastEffect !== null) { lastEffect.nextEffect = null; - } - // We're done. + } // We're done. + return null; } } else if ( @@ -16209,10 +17159,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { // The assumption is that this is usually faster. workInProgress.effectTag |= DidCapture; didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. If we can show // them, then they really have the same priority as this render. // So we'll pick it back up the very next render pass once we've had @@ -16220,11 +17167,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { var nextPriority = renderExpirationTime - 1; workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority; + if (enableSchedulerTracing) { markSpawnedWork(nextPriority); } } } + if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in @@ -16235,11 +17184,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; + if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } + renderState.last = renderedTail; } } @@ -16251,18 +17202,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { // until we just give up and show what we have so far. var TAIL_EXPIRATION_TIMEOUT_MS = 500; renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; - } - // Pop a row. + } // Pop a row. + var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.lastEffect = workInProgress.lastEffect; - next.sibling = null; - - // Restore the context. + next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -16271,12 +17222,15 @@ function completeWork(current, workInProgress, renderExpirationTime) { } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } - pushSuspenseContext(workInProgress, suspenseContext); - // Do a pass over the next row. + + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + return next; } + break; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalImpl = workInProgress.type.impl; @@ -16284,22 +17238,28 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (fundamentalInstance === null) { var getInitialState = fundamentalImpl.getInitialState; - var fundamentalState = void 0; + var fundamentalState; + if (getInitialState !== undefined) { fundamentalState = getInitialState(newProps); } + fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( workInProgress, newProps, fundamentalImpl, fundamentalState || {} ); - var _instance7 = getFundamentalComponentInstance(fundamentalInstance); - fundamentalInstance.instance = _instance7; + + var _instance5 = getFundamentalComponentInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance5; + if (fundamentalImpl.reconcileChildren === false) { return null; } - appendAllChildren(_instance7, workInProgress, false, false); + + appendAllChildren(_instance5, workInProgress, false, false); mountFundamentalComponent(fundamentalInstance); } else { // We fire update in commit phase @@ -16307,259 +17267,177 @@ function completeWork(current, workInProgress, renderExpirationTime) { fundamentalInstance.prevProps = prevProps; fundamentalInstance.props = newProps; fundamentalInstance.currentFiber = workInProgress; + if (supportsPersistence) { - var _instance8 = cloneFundamentalInstance(fundamentalInstance); - fundamentalInstance.instance = _instance8; - appendAllChildren(_instance8, workInProgress, false, false); + var _instance6 = cloneFundamentalInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance6; + appendAllChildren(_instance6, workInProgress, false, false); } + var shouldUpdate = shouldUpdateFundamentalComponent( fundamentalInstance ); + if (shouldUpdate) { markUpdate(workInProgress); } } } + break; } - default: - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - return null; -} + case ScopeComponent: { + if (enableScopeAPI) { + if (current === null) { + var _type3 = workInProgress.type; + var scopeInstance = { + fiber: workInProgress, + methods: null + }; + workInProgress.stateNode = scopeInstance; + scopeInstance.methods = createScopeMethods(_type3, scopeInstance); -function mountEventResponder( - responder, - responderProps, - instance, - rootContainerInstance, - fiber, - respondersMap -) { - var responderState = emptyObject$1; - var getInitialState = responder.getInitialState; - if (getInitialState !== null) { - responderState = getInitialState(responderProps); - } - var responderInstance = createResponderInstance( - responder, - responderProps, - responderState, - instance, - fiber - ); - mountResponderInstance( - responder, - responderInstance, - responderProps, - responderState, - instance, - rootContainerInstance - ); - respondersMap.set(responder, responderInstance); -} + if (enableFlareAPI) { + var _listeners2 = newProps.listeners; -function updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance -) { - var responder = void 0; - var props = void 0; + if (_listeners2 != null) { + var _rootContainerInstance2 = getRootHostContainer(); - if (listener) { - responder = listener.responder; - props = listener.props; - } - (function() { - if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { - throw ReactError( - Error( - "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponer()." - ) - ); + updateEventListeners( + _listeners2, + workInProgress, + _rootContainerInstance2 + ); + } + } + + if (workInProgress.ref !== null) { + markRef$1(workInProgress); + markUpdate(workInProgress); + } + } else { + if (enableFlareAPI) { + var _prevListeners = current.memoizedProps.listeners; + var _nextListeners = newProps.listeners; + + if ( + _prevListeners !== _nextListeners || + workInProgress.ref !== null + ) { + markUpdate(workInProgress); + } + } else { + if (workInProgress.ref !== null) { + markUpdate(workInProgress); + } + } + + if (current.ref !== workInProgress.ref) { + markRef$1(workInProgress); + } + } + } + + break; } - })(); - var listenerProps = props; - if (visistedResponders.has(responder)) { - // show warning - { - 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 + + default: { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } - return; } - visistedResponders.add(responder); - var responderInstance = respondersMap.get(responder); - if (responderInstance === undefined) { - // Mount - mountEventResponder( - responder, - listenerProps, - instance, - rootContainerInstance, - fiber, - respondersMap - ); - } else { - // Update - responderInstance.props = listenerProps; - responderInstance.fiber = fiber; - } -} - -function updateEventListeners( - listeners, - instance, - rootContainerInstance, - fiber -) { - var visistedResponders = new Set(); - var dependencies = fiber.dependencies; - if (listeners != null) { - if (dependencies === null) { - dependencies = fiber.dependencies = { - expirationTime: NoWork, - firstContext: null, - responders: new Map() - }; - } - var respondersMap = dependencies.responders; - if (respondersMap === null) { - respondersMap = new Map(); - } - if (isArray$2(listeners)) { - for (var i = 0, length = listeners.length; i < length; i++) { - var listener = listeners[i]; - updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } else { - updateEventListener( - listeners, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } - if (dependencies !== null) { - var _respondersMap = dependencies.responders; - if (_respondersMap !== null) { - // Unmount - var mountedResponders = Array.from(_respondersMap.keys()); - for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { - var mountedResponder = mountedResponders[_i]; - if (!visistedResponders.has(mountedResponder)) { - var responderInstance = _respondersMap.get(mountedResponder); - unmountResponderInstance(responderInstance); - _respondersMap.delete(mountedResponder); - } - } - } - } + return null; } function unwindWork(workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + var effectTag = workInProgress.effectTag; + if (effectTag & ShouldCapture) { workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + return null; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - (function() { - if (!((_effectTag & DidCapture) === NoEffect)) { - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!((_effectTag & DidCapture) === NoEffect)) { + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." + ); + } + workInProgress.effectTag = (_effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } + case SuspenseComponent: { popSuspenseContext(workInProgress); - var _effectTag2 = workInProgress.effectTag; - if (_effectTag2 & ShouldCapture) { - workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } - return null; - } - case DehydratedSuspenseComponent: { + if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (workInProgress.alternate === null) { - // TODO: popHydrationState - } else { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (!(workInProgress.alternate !== null)) { + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + } + resetHydrationState(); } - var _effectTag3 = workInProgress.effectTag; - if (_effectTag3 & ShouldCapture) { - workInProgress.effectTag = - (_effectTag3 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } } + + var _effectTag2 = workInProgress.effectTag; + + if (_effectTag2 & ShouldCapture) { + workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; // Captured a suspense effect. Re-render the boundary. + + return workInProgress; + } + return null; } + case SuspenseListComponent: { - popSuspenseContext(workInProgress); - // SuspenseList doesn't actually catch anything. It should've been + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. + return null; } + case HostPortal: popHostContainer(workInProgress); return null; + case ContextProvider: popProvider(workInProgress); return null; + default: return null; } @@ -16569,37 +17447,41 @@ function unwindInterruptedWork(interruptedWork) { switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } + break; } + case HostRoot: { popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); break; } + case HostComponent: { popHostContext(interruptedWork); break; } + case HostPortal: popHostContainer(interruptedWork); break; + case SuspenseComponent: popSuspenseContext(interruptedWork); break; - case DehydratedSuspenseComponent: - if (enableSuspenseServerRenderer) { - popSuspenseContext(interruptedWork); - } - break; + case SuspenseListComponent: popSuspenseContext(interruptedWork); break; + case ContextProvider: popProvider(interruptedWork); break; + default: break; } @@ -16616,18 +17498,16 @@ function createCapturedValue(value, source) { } // Module provided by RN: -(function() { - if ( - !( - typeof ReactNativePrivateInterface.ReactFiberErrorDialog - .showErrorDialog === "function" - ) - ) { - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") - ); - } -})(); +if ( + !( + typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog === + "function" + ) +) { + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." + ); +} function showErrorDialog(capturedError) { return ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog( @@ -16636,23 +17516,21 @@ function showErrorDialog(capturedError) { } function logCapturedError(capturedError) { - var logError = showErrorDialog(capturedError); - - // Allow injected showErrorDialog() to prevent default console.error logging. + var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. + if (logError === false) { return; } var error = capturedError.error; + { var componentName = capturedError.componentName, componentStack = capturedError.componentStack, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, - willRetry = capturedError.willRetry; - - // Browsers support silencing uncaught errors by calling + willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. @@ -16662,22 +17540,20 @@ function logCapturedError(capturedError) { // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; - } - // The error is fatal. Since the silencing might have + } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. - console.error(error); - // For a more detailed description of this block, see: + + console.error(error); // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; + var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - var errorBoundaryMessage = void 0; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. if (errorBoundaryFound && errorBoundaryName) { if (willRetry) { errorBoundaryMessage = @@ -16695,31 +17571,32 @@ function logCapturedError(capturedError) { "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."; } + var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + - ("" + errorBoundaryMessage); - - // In development, we provide our own message with just the component stack. + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. + console.error(combinedMessage); } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } -var PossiblyWeakSet$1 = typeof WeakSet === "function" ? WeakSet : Set; - +var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source; var stack = errorInfo.stack; + if (stack === null && source !== null) { stack = getStackByFiberInDevAndProd(source); } @@ -16760,9 +17637,8 @@ var callComponentWillUnmountWithTimer = function(current$$1, instance) { instance.state = current$$1.memoizedState; instance.componentWillUnmount(); stopPhaseTimer(); -}; +}; // Capture errors so they don't interrupt unmounting. -// Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback( @@ -16772,6 +17648,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { current$$1, instance ); + if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); @@ -16781,10 +17658,12 @@ function safelyCallComponentWillUnmount(current$$1, instance) { function safelyDetachRef(current$$1) { var ref = current$$1.ref; + if (ref !== null) { if (typeof ref === "function") { { invokeGuardedCallback(null, ref, null, null); + if (hasCaughtError()) { var refError = clearCaughtError(); captureCommitPhaseError(current$$1, refError); @@ -16799,6 +17678,7 @@ function safelyDetachRef(current$$1) { function safelyCallDestroy(current$$1, destroy) { { invokeGuardedCallback(null, destroy, null); + if (hasCaughtError()) { var error = clearCaughtError(); captureCommitPhaseError(current$$1, error); @@ -16814,16 +17694,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); return; } + case ClassComponent: { if (finishedWork.effectTag & Snapshot) { if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, "getSnapshotBeforeUpdate"); - var instance = finishedWork.stateNode; - // We could update instance props and state here, + var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -16853,14 +17734,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { : void 0; } } + var snapshot = instance.getSnapshotBeforeUpdate( finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState ); + { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); warningWithoutStack$1( @@ -16871,12 +17755,15 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { ); } } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; stopPhaseTimer(); } } + return; } + case HostRoot: case HostComponent: case HostText: @@ -16884,16 +17771,13 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case IncompleteClassComponent: // Nothing to do for these component types return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -16901,18 +17785,22 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { function commitHookEffectList(unmountTag, mountTag, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; + do { if ((effect.tag & unmountTag) !== NoEffect$1) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; + if (destroy !== undefined) { destroy(); } } + if ((effect.tag & mountTag) !== NoEffect$1) { // Mount var create = effect.create; @@ -16920,8 +17808,10 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { { var _destroy = effect.destroy; + if (_destroy !== undefined && typeof _destroy !== "function") { var addendum = void 0; + if (_destroy === null) { addendum = " You returned null. If your effect does not require clean " + @@ -16943,6 +17833,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else { addendum = " You returned: " + _destroy; } + warningWithoutStack$1( false, "An effect function must not return anything besides a function, " + @@ -16953,6 +17844,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } } } + effect = effect.next; } while (effect !== firstEffect); } @@ -16968,6 +17860,7 @@ function commitPassiveHookEffects(finishedWork) { commitHookEffectList(NoEffect$1, MountPassive, finishedWork); break; } + default: break; } @@ -16987,14 +17880,16 @@ function commitLifeCycles( commitHookEffectList(UnmountLayout, MountLayout, finishedWork); break; } + case ClassComponent: { var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update) { if (current$$1 === null) { - startPhaseTimer(finishedWork, "componentDidMount"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidMount"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17024,6 +17919,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidMount(); stopPhaseTimer(); } else { @@ -17035,10 +17931,10 @@ function commitLifeCycles( current$$1.memoizedProps ); var prevState = current$$1.memoizedState; - startPhaseTimer(finishedWork, "componentDidUpdate"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidUpdate"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17068,6 +17964,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidUpdate( prevProps, prevState, @@ -17076,7 +17973,9 @@ function commitLifeCycles( stopPhaseTimer(); } } + var updateQueue = finishedWork.updateQueue; + if (updateQueue !== null) { { if ( @@ -17106,10 +18005,10 @@ function commitLifeCycles( ) : void 0; } - } - // We could update instance props and state here, + } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + commitUpdateQueue( finishedWork, updateQueue, @@ -17117,22 +18016,28 @@ function commitLifeCycles( committedExpirationTime ); } + return; } + case HostRoot: { var _updateQueue = finishedWork.updateQueue; + if (_updateQueue !== null) { var _instance = null; + if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; + case ClassComponent: _instance = finishedWork.child.stateNode; break; } } + commitUpdateQueue( finishedWork, _updateQueue, @@ -17140,15 +18045,16 @@ function commitLifeCycles( committedExpirationTime ); } + return; } - case HostComponent: { - var _instance2 = finishedWork.stateNode; - // Renderers may schedule work to be done after host components are mounted + case HostComponent: { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. + if (current$$1 === null && finishedWork.effectTag & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; @@ -17156,14 +18062,17 @@ function commitLifeCycles( return; } + case HostText: { // We have no life-cycles associated with text. return; } + case HostPortal: { // We have no life-cycles associated with portals. return; } + case Profiler: { if (enableProfilerTimer) { var onRender = finishedWork.memoizedProps.onRender; @@ -17191,23 +18100,27 @@ function commitLifeCycles( } } } + return; } - case SuspenseComponent: + + case SuspenseComponent: { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + return; + } + case SuspenseListComponent: case IncompleteClassComponent: case FundamentalComponent: + case ScopeComponent: return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17215,10 +18128,13 @@ function commitLifeCycles( function hideOrUnhideAllChildren(finishedWork, isHidden) { if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. var node = finishedWork; + while (true) { if (node.tag === HostComponent) { var instance = node.stateNode; + if (isHidden) { hideInstance(instance); } else { @@ -17226,6 +18142,7 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (isHidden) { hideTextInstance(_instance3); } else { @@ -17233,9 +18150,11 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if ( node.tag === SuspenseComponent && - node.memoizedState !== null + node.memoizedState !== null && + node.memoizedState.dehydrated === null ) { // Found a nested Suspense component that timed out. Skip over the + // primary child fragment, which should remain hidden. var fallbackChildFragment = node.child.sibling; fallbackChildFragment.return = node; node = fallbackChildFragment; @@ -17245,15 +18164,19 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -17262,16 +18185,24 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { function commitAttachRef(finishedWork) { var ref = finishedWork.ref; + if (ref !== null) { var instance = finishedWork.stateNode; - var instanceToUse = void 0; + var instanceToUse; + switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; + default: instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag + + if (enableScopeAPI && finishedWork.tag === ScopeComponent) { + instanceToUse = instance.methods; } + if (typeof ref === "function") { ref(instanceToUse); } else { @@ -17294,6 +18225,7 @@ function commitAttachRef(finishedWork) { function commitDetachRef(current$$1) { var currentRef = current$$1.ref; + if (currentRef !== null) { if (typeof currentRef === "function") { currentRef(null); @@ -17301,12 +18233,11 @@ function commitDetachRef(current$$1) { currentRef.current = null; } } -} - -// User-originating errors (lifecycles and refs) should not interrupt +} // User-originating errors (lifecycles and refs) should not interrupt // deletion, so don't let them throw. Host-originating errors should // interrupt deletion, so it's okay -function commitUnmount(current$$1, renderPriorityLevel) { + +function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) { onCommitUnmount(current$$1); switch (current$$1.tag) { @@ -17315,12 +18246,12 @@ function commitUnmount(current$$1, renderPriorityLevel) { case MemoComponent: case SimpleMemoComponent: { var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - // When the owner fiber is deleted, the destroy function of a passive + if (lastEffect !== null) { + var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive // effect hook is called during the synchronous commit phase. This is // a concession to implementation complexity. Calling it in the // passive effect phase (like they usually are, when dependencies @@ -17332,40 +18263,51 @@ function commitUnmount(current$$1, renderPriorityLevel) { // the priority. // // TODO: Reconsider this implementation trade off. + var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; runWithPriority(priorityLevel, function() { var effect = firstEffect; + do { var destroy = effect.destroy; + if (destroy !== undefined) { safelyCallDestroy(current$$1, destroy); } + effect = effect.next; } while (effect !== firstEffect); }); } } + break; } + case ClassComponent: { safelyDetachRef(current$$1); var instance = current$$1.stateNode; + if (typeof instance.componentWillUnmount === "function") { safelyCallComponentWillUnmount(current$$1, instance); } + return; } + case HostComponent: { if (enableFlareAPI) { var dependencies = current$$1.dependencies; if (dependencies !== null) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for ( var i = 0, length = responderInstances.length; i < length; @@ -17374,49 +18316,80 @@ function commitUnmount(current$$1, renderPriorityLevel) { var responderInstance = responderInstances[i]; unmountResponderInstance(responderInstance); } + dependencies.responders = null; } } } + safelyDetachRef(current$$1); return; } + case HostPortal: { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if (supportsMutation) { - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else if (supportsPersistence) { emptyPortalContainer(current$$1); } + return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = current$$1.stateNode; + if (fundamentalInstance !== null) { unmountFundamentalComponent(fundamentalInstance); current$$1.stateNode = null; } } + + return; } - } -} -function commitNestedUnmounts(root, renderPriorityLevel) { - // While we're inside a removed host node we don't want to call + case DehydratedFragment: { + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(current$$1.stateNode); + } + } + } + + return; + } + + case ScopeComponent: { + if (enableScopeAPI) { + safelyDetachRef(current$$1); + } + } + } +} + +function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) { + // While we're inside a removed host node we don't want to call // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. var node = root; + while (true) { - commitUnmount(node, renderPriorityLevel); - // Visit children because they may contain more composite or host nodes. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes. // Skip portals because commitUnmount() currently visits them recursively. + if ( - node.child !== null && - // If we use mutation we drill down into portals using commitUnmount above. + node.child !== null && // If we use mutation we drill down into portals using commitUnmount above. // If we don't use mutation we drill down into portals here instead. (!supportsMutation || node.tag !== HostPortal) ) { @@ -17424,27 +18397,31 @@ function commitNestedUnmounts(root, renderPriorityLevel) { node = node.child; continue; } + if (node === root) { return; } + while (node.sibling === null) { if (node.return === null || node.return === root) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } function detachFiber(current$$1) { - var alternate = current$$1.alternate; - // Cut off the return pointers to disconnect it from the tree. Ideally, we + var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. This child // itself will be GC:ed when the parent updates the next time. + current$$1.return = null; current$$1.child = null; current$$1.memoizedState = null; @@ -17455,6 +18432,7 @@ function detachFiber(current$$1) { current$$1.lastEffect = null; current$$1.pendingProps = null; current$$1.memoizedProps = null; + if (alternate !== null) { detachFiber(alternate); } @@ -17467,7 +18445,6 @@ function emptyPortalContainer(current$$1) { var portal = current$$1.stateNode; var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); replaceContainerChildren(containerInfo, emptyChildSet); } @@ -17484,46 +18461,42 @@ function commitContainer(finishedWork) { case FundamentalComponent: { return; } + case HostRoot: case HostPortal: { var portalOrRoot = finishedWork.stateNode; var containerInfo = portalOrRoot.containerInfo, - _pendingChildren = portalOrRoot.pendingChildren; - - replaceContainerChildren(containerInfo, _pendingChildren); + pendingChildren = portalOrRoot.pendingChildren; + replaceContainerChildren(containerInfo, pendingChildren); return; } + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } function getHostParentFiber(fiber) { var parent = fiber.return; + while (parent !== null) { if (isHostParent(parent)) { return parent; } + parent = parent.return; } - (function() { - { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } function isHostParent(fiber) { @@ -17538,7 +18511,9 @@ function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. var node = fiber; + siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { @@ -17547,31 +18522,34 @@ function getHostSibling(fiber) { // last sibling. return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; + while ( node.tag !== HostComponent && node.tag !== HostText && - node.tag !== DehydratedSuspenseComponent + node.tag !== DehydratedFragment ) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.effectTag & Placement) { // If we don't have a child, try the siblings instead. continue siblings; - } - // If we don't have a child, try the siblings instead. + } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. + if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } - } - // Check if this host node is stable or about to be placed. + } // Check if this host node is stable or about to be placed. + if (!(node.effectTag & Placement)) { // Found it! return node.stateNode; @@ -17582,58 +18560,61 @@ function getHostSibling(fiber) { function commitPlacement(finishedWork) { if (!supportsMutation) { return; - } + } // Recursively insert all host nodes into the parent. - // Recursively insert all host nodes into the parent. - var parentFiber = getHostParentFiber(finishedWork); + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - // Note: these two variables *must* always be updated together. - var parent = void 0; - var isContainer = void 0; + var parent; + var isContainer; var parentStateNode = parentFiber.stateNode; + switch (parentFiber.tag) { case HostComponent: parent = parentStateNode; isContainer = false; break; + case HostRoot: parent = parentStateNode.containerInfo; isContainer = true; break; + case HostPortal: parent = parentStateNode.containerInfo; isContainer = true; break; + case FundamentalComponent: if (enableFundamentalAPI) { parent = parentStateNode.instance; isContainer = false; } + // eslint-disable-next-line-no-fallthrough - default: - (function() { - { - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + default: { + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } } + if (parentFiber.effectTag & ContentReset) { // Reset the text content of the parent before doing any insertions parentFiber.effectTag &= ~ContentReset; } - var before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. + var node = finishedWork; + while (true) { var isHost = node.tag === HostComponent || node.tag === HostText; + if (isHost || (enableFundamentalAPI && node.tag === FundamentalComponent)) { var stateNode = isHost ? node.stateNode : node.stateNode.instance; + if (before) { if (isContainer) { insertInContainerBefore(parent, stateNode, before); @@ -17656,85 +18637,91 @@ function commitPlacement(finishedWork) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel) { +function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) { // We only have the top Fiber that was deleted but we need to recurse down its - var node = current$$1; - - // Each iteration, currentParent is populated with node's host parent if not + // children to find all the terminal nodes. + var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not // currentParentIsValid. - var currentParentIsValid = false; - // Note: these two variables *must* always be updated together. - var currentParent = void 0; - var currentParentIsContainer = void 0; + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. + + var currentParent; + var currentParentIsContainer; while (true) { if (!currentParentIsValid) { var parent = node.return; + findParent: while (true) { - (function() { - if (!(parent !== null)) { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(parent !== null)) { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + var parentStateNode = parent.stateNode; + switch (parent.tag) { case HostComponent: currentParent = parentStateNode; currentParentIsContainer = false; break findParent; + case HostRoot: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case HostPortal: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case FundamentalComponent: if (enableFundamentalAPI) { currentParent = parentStateNode.instance; currentParentIsContainer = false; } } + parent = parent.return; } + currentParentIsValid = true; } if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, node.stateNode); } else { removeChild(currentParent, node.stateNode); - } - // Don't visit children because we already visited them. + } // Don't visit children because we already visited them. } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var fundamentalNode = node.stateNode.instance; - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, fundamentalNode); } else { @@ -17742,9 +18729,20 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { } } else if ( enableSuspenseServerRenderer && - node.tag === DehydratedSuspenseComponent + node.tag === DehydratedFragment ) { - // Delete the dehydrated suspense boundary and all of its content. + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(node.stateNode); + } + } + } // Delete the dehydrated suspense boundary and all of its content. + if (currentParentIsContainer) { clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); } else { @@ -17755,49 +18753,55 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { // When we go into a portal, it becomes the parent to remove from. // We will reassign it back when we pop the portal on the way up. currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; - // Visit children because portals might contain host components. + currentParentIsContainer = true; // Visit children because portals might contain host components. + node.child.return = node; node = node.child; continue; } } else { - commitUnmount(node, renderPriorityLevel); - // Visit children because we may find more host components below. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below. + if (node.child !== null) { node.child.return = node; node = node.child; continue; } } + if (node === current$$1) { return; } + while (node.sibling === null) { if (node.return === null || node.return === current$$1) { return; } + node = node.return; + if (node.tag === HostPortal) { // When we go out of the portal, we need to restore the parent. // Since we don't keep a stack of them, we will search for it. currentParentIsValid = false; } } + node.sibling.return = node.return; node = node.sibling; } } -function commitDeletion(current$$1, renderPriorityLevel) { +function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) { if (supportsMutation) { // Recursively delete all host nodes from the parent. // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else { // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(current$$1, renderPriorityLevel); + commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel); } + detachFiber(current$$1); } @@ -17813,18 +18817,35 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + + case HostRoot: { + if (supportsHydration) { + var root = finishedWork.stateNode; + + if (root.hydrate) { + // We've just hydrated. No need to hydrate again. + root.hydrate = false; + commitHydratedContainer(root.containerInfo); + } + } + + break; + } } commitContainer(finishedWork); @@ -17841,23 +18862,27 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case ClassComponent: { return; } + case HostComponent: { var instance = finishedWork.stateNode; + if (instance != null) { // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps; - var type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; + if (updatePayload !== null) { commitUpdate( instance, @@ -17868,72 +18893,117 @@ function commitWork(current$$1, finishedWork) { finishedWork ); } + + if (enableFlareAPI) { + var prevListeners = oldProps.listeners; + var nextListeners = newProps.listeners; + + if (prevListeners !== nextListeners) { + updateEventListeners(nextListeners, finishedWork, null); + } + } } + return; } + case HostText: { - (function() { - if (!(finishedWork.stateNode !== null)) { - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(finishedWork.stateNode !== null)) { + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldText = current$$1 !== null ? current$$1.memoizedProps : newText; commitTextUpdate(textInstance, oldText, newText); return; } + case HostRoot: { + if (supportsHydration) { + var _root = finishedWork.stateNode; + + if (_root.hydrate) { + // We've just hydrated. No need to hydrate again. + _root.hydrate = false; + commitHydratedContainer(_root.containerInfo); + } + } + return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + case IncompleteClassComponent: { return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = finishedWork.stateNode; updateFundamentalComponent(fundamentalInstance); } + return; } - default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + var scopeInstance = finishedWork.stateNode; + scopeInstance.fiber = finishedWork; + + if (enableFlareAPI) { + var _newProps = finishedWork.memoizedProps; + + var _oldProps = + current$$1 !== null ? current$$1.memoizedProps : _newProps; + + var _prevListeners = _oldProps.listeners; + var _nextListeners = _newProps.listeners; + + if (_prevListeners !== _nextListeners) { + updateEventListeners(_nextListeners, finishedWork, null); + } } - })(); + } + + return; + } + + default: { + { + 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." + ); + } } } } function commitSuspenseComponent(finishedWork) { var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; + var newDidTimeout; var primaryChildParent = finishedWork; + if (newState === null) { newDidTimeout = false; } else { @@ -17948,8 +19018,10 @@ function commitSuspenseComponent(finishedWork) { if (enableSuspenseCallback && newState !== null) { var suspenseCallback = finishedWork.memoizedProps.suspenseCallback; + if (typeof suspenseCallback === "function") { var thenables = finishedWork.updateQueue; + if (thenables !== null) { suspenseCallback(new Set(thenables)); } @@ -17961,23 +19033,67 @@ function commitSuspenseComponent(finishedWork) { } } +function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } + + var newState = finishedWork.memoizedState; + + if (newState === null) { + var current$$1 = finishedWork.alternate; + + if (current$$1 !== null) { + var prevState = current$$1.memoizedState; + + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onHydrated = hydrationCallbacks.onHydrated; + + if (onHydrated) { + onHydrated(suspenseInstance); + } + } + } + } + } + } + } +} + function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of thenables. // For each thenable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. var thenables = finishedWork.updateQueue; + if (thenables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; + if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet$1(); + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } + thenables.forEach(function(thenable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryThenable.bind(null, finishedWork, thenable); + if (!retryCache.has(thenable)) { if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); + if (thenable.__reactDoNotTraceInteractions !== true) { + retry = tracing.unstable_wrap(retry); + } } + retryCache.add(thenable); thenable.then(retry, retry); } @@ -17989,24 +19105,28 @@ function commitResetTextContent(current$$1) { if (!supportsMutation) { return; } + resetTextContent(current$$1.stateNode); } -var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { - var update = createUpdate(expirationTime, null); - // Unmount the root by rendering null. - update.tag = CaptureUpdate; - // Caution: React DevTools currently depends on this property + var update = createUpdate(expirationTime, null); // Unmount the root by rendering null. + + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". - update.payload = { element: null }; + + update.payload = { + element: null + }; var error = errorInfo.value; + update.callback = function() { onUncaughtError(error); logError(fiber, errorInfo); }; + return update; } @@ -18014,8 +19134,10 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime, null); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; + if (typeof getDerivedStateFromError === "function") { var error = errorInfo.value; + update.payload = function() { logError(fiber, errorInfo); return getDerivedStateFromError(error); @@ -18023,27 +19145,30 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { } var inst = fiber.stateNode; + if (inst !== null && typeof inst.componentDidCatch === "function") { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } + if (typeof getDerivedStateFromError !== "function") { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined - // Only log here if componentDidCatch is the only error boundary method defined logError(fiber, errorInfo); } + var error = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error, { componentStack: stack !== null ? stack : "" }); + { if (typeof getDerivedStateFromError !== "function") { // If componentDidCatch is the only error boundary method defined, @@ -18065,6 +19190,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { markFailedErrorBoundaryForHotReloading(fiber); }; } + return update; } @@ -18073,18 +19199,21 @@ function attachPingListener(root, renderExpirationTime, thenable) { // only if one does not already exist for the current render expiration // time (which acts like a "thread ID" here). var pingCache = root.pingCache; - var threadIDs = void 0; + var threadIDs; + if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); threadIDs = new Set(); pingCache.set(thenable, threadIDs); } else { threadIDs = pingCache.get(thenable); + if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(thenable, threadIDs); } } + if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); @@ -18094,9 +19223,6 @@ function attachPingListener(root, renderExpirationTime, thenable) { thenable, renderExpirationTime ); - if (enableSchedulerTracing) { - ping = tracing.unstable_wrap(ping); - } thenable.then(ping, ping); } } @@ -18109,8 +19235,8 @@ function throwException( renderExpirationTime ) { // The source fiber did not complete. - sourceFiber.effectTag |= Incomplete; - // Its effect list is no longer valid. + sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid. + sourceFiber.firstEffect = sourceFiber.lastEffect = null; if ( @@ -18120,34 +19246,31 @@ function throwException( ) { // This is a thenable. var thenable = value; - checkForWrongSuspensePriorityInDEV(sourceFiber); - var hasInvisibleParentBoundary = hasSuspenseContext( suspenseStackCursor.current, InvisibleParentSuspenseContext - ); + ); // Schedule the nearest Suspense to re-render the timed out view. - // Schedule the nearest Suspense to re-render the timed out view. var _workInProgress = returnFiber; + do { if ( _workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary) ) { // Found the nearest boundary. - // Stash the promise on the boundary fiber. If the boundary times out, we'll + // attach another listener to flip the boundary back to its normal state. var thenables = _workInProgress.updateQueue; + if (thenables === null) { var updateQueue = new Set(); updateQueue.add(thenable); _workInProgress.updateQueue = updateQueue; } else { thenables.add(thenable); - } - - // If the boundary is outside of batched mode, we should *not* + } // If the boundary is outside of batched mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. In the commit phase, we'll schedule a // subsequent synchronous update to re-render the Suspense. @@ -18155,16 +19278,17 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a batched mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & BatchedMode) === NoMode) { - _workInProgress.effectTag |= DidCapture; - // We're going to commit this fiber even though it didn't complete. + if ((_workInProgress.mode & BatchedMode) === NoMode) { + _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. + sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call @@ -18178,17 +19302,13 @@ function throwException( update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update); } - } - - // The source fiber did not complete. Mark it with Sync priority to + } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. - sourceFiber.expirationTime = Sync; - // Exit without suspending. - return; - } + sourceFiber.expirationTime = Sync; // Exit without suspending. - // Confirmed that the boundary is in a concurrent mode tree. Continue + return; + } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this @@ -18203,7 +19323,6 @@ function throwException( // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, @@ -18231,56 +19350,16 @@ function throwException( // ensure that new initial loading states can commit as soon as possible. attachPingListener(root, renderExpirationTime, thenable); - _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; - return; - } else if ( - enableSuspenseServerRenderer && - _workInProgress.tag === DehydratedSuspenseComponent - ) { - attachPingListener(root, renderExpirationTime, thenable); + } // This boundary already captured during this render. Continue to the next + // boundary. - // Since we already have a current fiber, we can eagerly add a retry listener. - var retryCache = _workInProgress.memoizedState; - if (retryCache === null) { - retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var current$$1 = _workInProgress.alternate; - (function() { - if (!current$$1) { - throw ReactError( - Error( - "A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React." - ) - ); - } - })(); - current$$1.memoizedState = retryCache; - } - // Memoize using the boundary fiber to prevent redundant listeners. - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - var retry = resolveRetryThenable.bind( - null, - _workInProgress, - thenable - ); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - thenable.then(retry, retry); - } - _workInProgress.effectTag |= ShouldCapture; - _workInProgress.expirationTime = renderExpirationTime; - return; - } - // This boundary already captured during this render. Continue to the next - // boundary. _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // No boundary was found. Fallthrough to error mode. + } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode. // TODO: Use invariant so the message is stripped in prod? + value = new Error( (getComponentName(sourceFiber.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n" + @@ -18289,33 +19368,37 @@ function throwException( "provide a loading indicator or placeholder to display." + getStackByFiberInDevAndProd(sourceFiber) ); - } - - // We didn't find a boundary that could handle this type of exception. Start + } // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. + renderDidError(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; + do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; + var _update = createRootErrorUpdate( workInProgress, _errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update); return; } + case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; + if ( (workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === "function" || @@ -18324,142 +19407,153 @@ function throwException( !isAlreadyFailedLegacyErrorBoundary(instance))) ) { workInProgress.effectTag |= ShouldCapture; - workInProgress.expirationTime = renderExpirationTime; - // Schedule the error boundary to re-render using updated state + workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state + var _update2 = createClassErrorUpdate( workInProgress, errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update2); return; } + break; + default: break; } + workInProgress = workInProgress.return; } while (workInProgress !== null); } -// The scheduler is imported here *only* to detect whether it's been mocked -// DEV stuff var ceil = Math.ceil; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; +var NoContext = + /* */ + 0; +var BatchedContext = + /* */ + 1; +var EventContext = + /* */ + 2; +var DiscreteEventContext = + /* */ + 4; +var LegacyUnbatchedContext = + /* */ + 8; +var RenderContext = + /* */ + 16; +var CommitContext = + /* */ + 32; +var RootIncomplete = 0; +var RootFatalErrored = 1; +var RootErrored = 2; +var RootSuspended = 3; +var RootSuspendedWithDelay = 4; +var RootCompleted = 5; +// Describes where we are in the React execution stack +var executionContext = NoContext; // The root we're working on -var NoContext = /* */ 0; -var BatchedContext = /* */ 1; -var EventContext = /* */ 2; -var DiscreteEventContext = /* */ 4; -var LegacyUnbatchedContext = /* */ 8; -var RenderContext = /* */ 16; -var CommitContext = /* */ 32; +var workInProgressRoot = null; // The fiber we're working on -var RootIncomplete = 0; -var RootErrored = 1; -var RootSuspended = 2; -var RootSuspendedWithDelay = 3; -var RootCompleted = 4; +var workInProgress = null; // The expiration time we're rendering -// Describes where we are in the React execution stack -var executionContext = NoContext; -// The root we're working on -var workInProgressRoot = null; -// The fiber we're working on -var workInProgress = null; -// The expiration time we're rendering -var renderExpirationTime = NoWork; -// Whether to root completed, errored, suspended, etc. -var workInProgressRootExitStatus = RootIncomplete; -// Most recent event time among processed updates during this render. +var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc. + +var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown + +var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render. // This is conceptually a time stamp but expressed in terms of an ExpirationTime // because we deal mostly with expiration times in the hot path, so this avoids // the conversion happening in the hot path. + var workInProgressRootLatestProcessedExpirationTime = Sync; var workInProgressRootLatestSuspenseTimeout = Sync; -var workInProgressRootCanSuspendUsingConfig = null; -// If we're pinged while rendering we don't always restart immediately. +var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only +// includes unprocessed updates, not work in bailed out children. + +var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately. // This flag determines if it might be worthwhile to restart if an opportunity // happens latere. -var workInProgressRootHasPendingPing = false; -// The most recent time we committed a fallback. This lets us ensure a train + +var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. + var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; - var nextEffect = null; var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; - var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsRenderPriority = NoPriority; var pendingPassiveEffectsExpirationTime = NoWork; +var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates -var rootsWithPendingDiscreteUpdates = null; - -// Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; - -var interruptedBy = null; - -// Marks the need to reschedule pending interactions at these expiration times +var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times // during the commit phase. This enables them to be traced across components // that spawn new work during render. E.g. hidden boundaries, suspended SSR // hydration or SuspenseList. -var spawnedWorkDuringRender = null; -// Expiration times are computed by adding to the current time (the start +var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start // time). However, if two updates are scheduled within the same event, we // should treat their start times as simultaneous, even if the actual clock // time has advanced between the first and second call. - // In other words, because expiration times determine how updates are batched, // we want all updates of like priority that occur within the same event to // receive the same expiration time. Otherwise we get tearing. -var currentEventTime = NoWork; +var currentEventTime = NoWork; function requestCurrentTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return msToExpirationTime(now()); - } - // We're not inside React, so we may be in the middle of a browser event. + } // We're not inside React, so we may be in the middle of a browser event. + if (currentEventTime !== NoWork) { // Use the same start time for all updates until we enter React again. return currentEventTime; - } - // This is the first update since React yielded. Compute a new start time. + } // This is the first update since React yielded. Compute a new start time. + currentEventTime = msToExpirationTime(now()); return currentEventTime; } - function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { var mode = fiber.mode; + if ((mode & BatchedMode) === NoMode) { return Sync; } var priorityLevel = getCurrentPriorityLevel(); + if ((mode & ConcurrentMode) === NoMode) { return priorityLevel === ImmediatePriority ? Sync : Batched; } if ((executionContext & RenderContext) !== NoContext) { // Use whatever time we're already rendering + // TODO: Should there be a way to opt out, like with `runWithPriority`? return renderExpirationTime; } - var expirationTime = void 0; + var expirationTime; + if (suspenseConfig !== null) { // Compute an expiration time based on the Suspense timeout. expirationTime = computeSuspenseExpiration( @@ -18472,33 +19566,33 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { case ImmediatePriority: expirationTime = Sync; break; + case UserBlockingPriority: // TODO: Rename this to computeUserBlockingExpiration expirationTime = computeInteractiveExpiration(currentTime); break; + case NormalPriority: case LowPriority: // TODO: Handle LowPriority // TODO: Rename this to... something better. expirationTime = computeAsyncExpiration(currentTime); break; + case IdlePriority: - expirationTime = Never; + expirationTime = Idle; break; - default: - (function() { - { - throw ReactError(Error("Expected a valid priority level")); - } - })(); - } - } - // If we're in the middle of rendering a tree, do not update at the same + default: { + throw Error("Expected a valid priority level"); + } + } + } // If we're in the middle of rendering a tree, do not update at the same // expiration time that is already rendering. // TODO: We shouldn't have to do this if the update is on a different root. // Refactor computeExpirationForFiber + scheduleUpdate so we have access to // the root when we check for this condition. + if (workInProgressRoot !== null && expirationTime === renderExpirationTime) { // This is a trick to move this update into a separate batch expirationTime -= 1; @@ -18506,47 +19600,40 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { return expirationTime; } - function scheduleUpdateOnFiber(fiber, expirationTime) { checkForNestedUpdates(); warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber); - var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime); + if (root === null) { warnAboutUpdateOnUnmountedFiberInDEV(fiber); return; } - root.pingTime = NoWork; - checkForInterruption(fiber, expirationTime); - recordScheduleUpdate(); - - // TODO: computeExpirationForFiber also reads the priority. Pass the + recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); if (expirationTime === Sync) { if ( // Check if we're inside unbatchedUpdates - (executionContext & LegacyUnbatchedContext) !== NoContext && - // Check if we're not already rendering + (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering (executionContext & (RenderContext | CommitContext)) === NoContext ) { // Register pending interactions on the root to avoid losing traced interaction data. - schedulePendingInteractions(root, expirationTime); - - // This is a legacy edge case. The initial mount of a ReactDOM.render-ed + schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed // root inside of batchedUpdates should be synchronous, but layout updates // should be deferred until the end of the batch. - var callback = renderRoot(root, Sync, true); - while (callback !== null) { - callback = callback(true); - } + + performSyncWorkOnRoot(root); } else { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); + if (executionContext === NoContext) { - // Flush the synchronous work now, wnless we're already working or inside + // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated @@ -18555,12 +19642,12 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { } } } else { - scheduleCallbackForRoot(root, priorityLevel, expirationTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); } if ( - (executionContext & DiscreteEventContext) !== NoContext && - // Only updates at user-blocking priority or greater are considered + (executionContext & DiscreteEventContext) !== NoContext && // Only updates at user-blocking priority or greater are considered // discrete, even inside a discrete event. (priorityLevel === UserBlockingPriority || priorityLevel === ImmediatePriority) @@ -18571,37 +19658,42 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); } else { var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) { rootsWithPendingDiscreteUpdates.set(root, expirationTime); } } } } -var scheduleWork = scheduleUpdateOnFiber; - -// This is split into a separate function so we can mark a fiber with pending +var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending // work without treating it as a typical update that originates from an event; // e.g. retrying a Suspense boundary isn't an update, but it does schedule work // on a fiber. + function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { // Update the source fiber's expiration time if (fiber.expirationTime < expirationTime) { fiber.expirationTime = expirationTime; } + var alternate = fiber.alternate; + if (alternate !== null && alternate.expirationTime < expirationTime) { alternate.expirationTime = expirationTime; - } - // Walk the parent path to the root and update the child expiration time. + } // Walk the parent path to the root and update the child expiration time. + var node = fiber.return; var root = null; + if (node === null && fiber.tag === HostRoot) { root = fiber.stateNode; } else { while (node !== null) { alternate = node.alternate; + if (node.childExpirationTime < expirationTime) { node.childExpirationTime = expirationTime; + if ( alternate !== null && alternate.childExpirationTime < expirationTime @@ -18614,580 +19706,430 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { ) { alternate.childExpirationTime = expirationTime; } + if (node.return === null && node.tag === HostRoot) { root = node.stateNode; break; } + node = node.return; } } if (root !== null) { - // Update the first and last pending expiration times in this root - var firstPendingTime = root.firstPendingTime; - if (expirationTime > firstPendingTime) { - root.firstPendingTime = expirationTime; - } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime === NoWork || expirationTime < lastPendingTime) { - root.lastPendingTime = expirationTime; - } + if (workInProgressRoot === root) { + // Received an update to a tree that's in the middle of rendering. Mark + // that's unprocessed work on this root. + markUnprocessedUpdateTime(expirationTime); + + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: This happens to work when receiving an update during the render + // phase, because of the trick inside computeExpirationForFiber to + // subtract 1 from `renderExpirationTime` to move it into a + // separate bucket. But we should probably model it with an exception, + // using the same mechanism we use to force hydration of a subtree. + // TODO: This does not account for low pri updates that were already + // scheduled before the root started rendering. Need to track the next + // pending expiration time (perhaps by backtracking the return path) and + // then trigger a restart in the `renderDidSuspendDelayIfPossible` path. + markRootSuspendedAtTime(root, renderExpirationTime); + } + } // Mark that the root has a pending update. + + markRootUpdatedAtTime(root, expirationTime); } return root; } -// Use this function, along with runRootCallback, to ensure that only a single -// callback per root is scheduled. It's still possible to call renderRoot -// directly, but scheduling via this function helps avoid excessive callbacks. -// It works by storing the callback node and expiration time on the root. When a -// new callback comes in, it compares the expiration time to determine if it -// should cancel the previous one. It also relies on commitRoot scheduling a -// callback to render the next level, because that means we don't need a -// separate callback per expiration time. -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - var existingCallbackExpirationTime = root.callbackExpirationTime; - if (existingCallbackExpirationTime < expirationTime) { - // New callback has higher priority than the existing one. - var existingCallbackNode = root.callbackNode; - if (existingCallbackNode !== null) { - cancelCallback(existingCallbackNode); - } - root.callbackExpirationTime = expirationTime; - - if (expirationTime === Sync) { - // Sync React callbacks are scheduled on a special internal queue - root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - ); - } else { - var options = null; - if ( - !disableSchedulerTimeoutBasedOnReactExpirationTime && - expirationTime !== Never - ) { - var timeout = expirationTimeToMs(expirationTime) - now(); - options = { timeout: timeout }; - } - - root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - options - ); - if ( - enableUserTimingAPI && - expirationTime !== Sync && - (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - // Scheduled an async callback, and we're not already working. Add an - // entry to the flamegraph that shows we're waiting for a callback - // to fire. - startRequestCallbackTimer(); - } - } +function getNextRootExpirationTimeToWorkOn(root) { + // Determines the next expiration time that the root should render, taking + // into account levels that may be suspended, or levels that may have + // received a ping. + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + return lastExpiredTime; + } // "Pending" refers to any update that hasn't committed yet, including if it + // suspended. The "suspended" range is therefore a subset. + + var firstPendingTime = root.firstPendingTime; + + if (!isRootSuspendedAtTime(root, firstPendingTime)) { + // The highest priority pending time is not suspended. Let's work on that. + return firstPendingTime; + } // If the first pending time is suspended, check if there's a lower priority + // pending level that we know about. Or check if we received a ping. Work + // on whichever is higher priority. + + var lastPingedTime = root.lastPingedTime; + var nextKnownPendingLevel = root.nextKnownPendingLevel; + return lastPingedTime > nextKnownPendingLevel + ? lastPingedTime + : nextKnownPendingLevel; +} // Use this function to schedule a task for a root. There's only one task per +// root; if a task was already scheduled, we'll check to make sure the +// expiration time of the existing task is the same as the expiration time of +// the next level that the root has work on. This function is called on every +// update, and right before exiting a task. + +function ensureRootIsScheduled(root) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + // Special case: Expired work should flush synchronously. + root.callbackExpirationTime = Sync; + root.callbackPriority = ImmediatePriority; + root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + ); + return; } - // Associate the current interactions with this new root+priority. - schedulePendingInteractions(root, expirationTime); -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + var existingCallbackNode = root.callbackNode; -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode; - var continuation = null; - try { - continuation = callback(isSync); - if (continuation !== null) { - return runRootCallback.bind(null, root, continuation); - } else { - return null; - } - } finally { - // If the callback exits without returning a continuation, remove the - // corresponding callback node from the root. Unless the callback node - // has changed, which implies that it was already cancelled by a high - // priority update. - if (continuation === null && prevCallbackNode === root.callbackNode) { + if (expirationTime === NoWork) { + // There's nothing to work on. + if (existingCallbackNode !== null) { root.callbackNode = null; root.callbackExpirationTime = NoWork; + root.callbackPriority = NoPriority; } - } -} -function flushDiscreteUpdates() { - // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. - // However, `act` uses `batchedUpdates`, so there's no way to distinguish - // those two cases. Need to fix this before exposing flushDiscreteUpdates - // as a public API. - if ( - (executionContext & (BatchedContext | RenderContext | CommitContext)) !== - NoContext - ) { - if (true && (executionContext & RenderContext) !== NoContext) { - warning$1( - false, - "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + - "already rendering." - ); - } - // We're already rendering, so we can't synchronously flush pending work. - // This is probably a nested event dispatch triggered by a lifecycle/effect, - // like `el.focus()`. Exit. return; - } - flushPendingDiscreteUpdates(); - if (!revertPassiveEffectsChange) { - // If the discrete updates scheduled passive effects, flush them now so that - // they fire before the next serial event. - flushPassiveEffects(); - } -} + } // TODO: If this is an update, we already read the current time. Pass the + // time as an argument. -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - if ( - firstBatch !== null && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ) { - scheduleCallback(NormalPriority, function() { - firstBatch._onComplete(); - return null; - }); - return true; - } else { - return false; - } -} + var currentTime = requestCurrentTime(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); // If there's an existing render task, confirm it has the correct priority and + // expiration time. Otherwise, we'll cancel it and schedule a new one. -function flushPendingDiscreteUpdates() { - if (rootsWithPendingDiscreteUpdates !== null) { - // For each root with pending discrete updates, schedule a callback to - // immediately flush them. - var roots = rootsWithPendingDiscreteUpdates; - rootsWithPendingDiscreteUpdates = null; - roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - }); - // Now flush the immediate queue. - flushSyncCallbackQueue(); - } -} + if (existingCallbackNode !== null) { + var existingCallbackPriority = root.callbackPriority; + var existingCallbackExpirationTime = root.callbackExpirationTime; -function batchedUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + if ( + // Callback must have the exact same expiration time. + existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority. + existingCallbackPriority >= priorityLevel + ) { + // Existing callback is sufficient. + return; + } // Need to schedule a new task. + // TODO: Instead of scheduling a new task, we should be able to change the + // priority of the existing one. -function batchedEventUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= EventContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } + cancelCallback(existingCallbackNode); } -} -function discreteUpdates$1(fn, a, b, c) { - var prevExecutionContext = executionContext; - executionContext |= DiscreteEventContext; - try { - // Should this - return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + var callbackNode; -function flushSync(fn, a) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - (function() { + if (expirationTime === Sync) { + // Sync React callbacks are scheduled on a special internal queue + callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root) + ); + } else { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects + // ordering because tasks are processed in timeout order. { - throw ReactError( - Error( - "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." - ) - ); + timeout: expirationTimeToMs(expirationTime) - now() } - })(); - } - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return runWithPriority(ImmediatePriority, fn.bind(null, a)); - } finally { - executionContext = prevExecutionContext; - // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - flushSyncCallbackQueue(); + ); } -} -function prepareFreshStack(root, expirationTime) { - root.finishedWork = null; - root.finishedExpirationTime = NoWork; + root.callbackNode = callbackNode; +} // This is the entry point for every concurrent task, i.e. anything that +// goes through Scheduler. - var timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; - // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - cancelTimeout(timeoutHandle); - } +function performConcurrentWorkOnRoot(root, didTimeout) { + // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. + currentEventTime = NoWork; - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - while (interruptedWork !== null) { - unwindInterruptedWork(interruptedWork); - interruptedWork = interruptedWork.return; + if (didTimeout) { + // The render task took too long to complete. Mark the current time as + // expired to synchronously render all expired work in a single batch. + var currentTime = requestCurrentTime(); + markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback. + + ensureRootIsScheduled(root); + return null; + } // Determine the next expiration time to work on, using the fields stored + // on the root. + + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + + if (expirationTime !== NoWork) { + var originalCallbackNode = root.callbackNode; + + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); } - } - workInProgressRoot = root; - workInProgress = createWorkInProgress(root.current, null, expirationTime); - renderExpirationTime = expirationTime; - workInProgressRootExitStatus = RootIncomplete; - workInProgressRootLatestProcessedExpirationTime = Sync; - workInProgressRootLatestSuspenseTimeout = Sync; - workInProgressRootCanSuspendUsingConfig = null; - workInProgressRootHasPendingPing = false; - - if (enableSchedulerTracing) { - spawnedWorkDuringRender = null; - } - - { - ReactStrictModeWarnings.discardPendingWarnings(); - componentsThatTriggeredHighPriSuspend = null; - } -} -function renderRoot(root, expirationTime, isSync) { - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (enableUserTimingAPI && expirationTime !== Sync) { - var didExpire = isSync; - stopRequestCallbackTimer(didExpire); - } + if ( + root !== workInProgressRoot || + expirationTime !== renderExpirationTime + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. - if (root.firstPendingTime < expirationTime) { - // If there's no work left at this expiration time, exit immediately. This - // happens when multiple callbacks are scheduled for a single root, but an - // earlier callback flushes the work of a later one. - return null; - } + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); - if (isSync && root.finishedExpirationTime === expirationTime) { - // There's already a pending commit at this expiration time. - // TODO: This is poorly factored. This case only exists for the - // batch.commit() API. - return commitRoot.bind(null, root); - } + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - flushPassiveEffects(); + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); - // If the root or expiration time have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) { - prepareFreshStack(root, expirationTime); - startWorkOnPendingInteractions(root, expirationTime); - } else if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // We could've received an update at a lower priority while we yielded. - // We're suspended in a delayed state. Once we complete this render we're - // just going to try to recover at the last pending time anyway so we might - // as well start doing that eagerly. - // Ideally we should be able to do this even for retries but we don't yet - // know if we're going to process an update which wants to commit earlier, - // and this path happens very early so it would happen too often. Instead, - // for that case, we'll wait until we complete. - if (workInProgressRootHasPendingPing) { - // We have a ping at this expiration. Let's restart to see if we get unblocked. - prepareFreshStack(root, expirationTime); - } else { - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately, while preserving the position in the queue. - return renderRoot.bind(null, root, lastPendingTime); + if (enableSchedulerTracing) { + popInteractions(prevInteractions); } - } - } - // If we have a work-in-progress fiber, it means there's still work to do - // in this root. - if (workInProgress !== null) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - prevDispatcher = ContextOnlyDispatcher; - } - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - startWorkLoopTimer(workInProgress); - - // TODO: Fork renderRoot into renderRootSync and renderRootAsync - if (isSync) { - if (expirationTime !== Sync) { - // An async update expired. There may be other expired updates on - // this root. We should render all the expired work in a - // single batch. - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) { - // Restart at the current time. - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } - return renderRoot.bind(null, root, currentTime); - } + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; } - } else { - // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - currentEventTime = NoWork; - } - - do { - try { - if (isSync) { - workLoopSync(); - } else { - workLoop(); - } - break; - } catch (thrownValue) { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooks(); - - var sourceFiber = workInProgress; - if (sourceFiber === null || sourceFiber.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - prepareFreshStack(root, expirationTime); - executionContext = prevExecutionContext; - throw thrownValue; - } - - if (enableProfilerTimer && sourceFiber.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true); - } - var returnFiber = sourceFiber.return; - throwException( + if (workInProgress !== null) { + // There's still work left over. Exit without committing. + stopInterruptedWorkLoopTimer(); + } else { + // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. + stopFinishedWorkLoopTimer(); + var finishedWork = (root.finishedWork = root.current.alternate); + root.finishedExpirationTime = expirationTime; + finishConcurrentRender( root, - returnFiber, - sourceFiber, - thrownValue, - renderExpirationTime + finishedWork, + workInProgressRootExitStatus, + expirationTime ); - workInProgress = completeUnitOfWork(sourceFiber); } - } while (true); - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } + ensureRootIsScheduled(root); - if (workInProgress !== null) { - // There's still work left over. Return a continuation. - stopInterruptedWorkLoopTimer(); - if (expirationTime !== Sync) { - startRequestCallbackTimer(); + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); } - return renderRoot.bind(null, root, expirationTime); } } - // We now have a consistent tree. The next step is either to commit it, or, if - // something suspended, wait to commit it after a timeout. - stopFinishedWorkLoopTimer(); - - root.finishedWork = root.current.alternate; - root.finishedExpirationTime = expirationTime; - - var isLocked = resolveLocksOnRoot(root, expirationTime); - if (isLocked) { - // This root has a lock that prevents it from committing. Exit. If we begin - // work on the root again, without any intervening updates, it will finish - // without doing additional work. - return null; - } + return null; +} +function finishConcurrentRender( + root, + finishedWork, + exitStatus, + expirationTime +) { // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: { - (function() { - { - throw ReactError(Error("Should have a work-in-progress.")); - } - })(); + switch (exitStatus) { + case RootIncomplete: + case RootFatalErrored: { + { + throw Error("Root did not complete. This is a bug in React."); + } } - // Flow knows about invariant, so it complains if I add a break statement, - // but eslint doesn't know about invariant, so it complains if I do. - // eslint-disable-next-line no-fallthrough + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + case RootErrored: { - // An error was thrown. First check if there is lower priority work - // scheduled on this root. - var _lastPendingTime = root.lastPendingTime; - if (_lastPendingTime < expirationTime) { - // There's lower priority work. Before raising the error, try rendering - // at the lower priority to see if it fixes it. Use a continuation to - // maintain the existing priority and position in the queue. - return renderRoot.bind(null, root, _lastPendingTime); - } - if (!isSync) { - // If we're rendering asynchronously, it's possible the error was - // caused by tearing due to a mutation during an event. Try rendering - // one more time without yiedling to events. - prepareFreshStack(root, expirationTime); - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - return null; - } - // If we're already rendering synchronously, commit the root in its - // errored state. - return commitRoot.bind(null, root); + // If this was an async render, the error may have happened due to + // a mutation in a concurrent event. Try rendering one more time, + // synchronously, to see if the error goes away. If there are + // lower priority updates, let's include those, too, in case they + // fix the inconsistency. Render at Idle to include all updates. + // If it was Idle or Never or some not-yet-invented time, render + // at that time. + markRootExpiredAtTime( + root, + expirationTime > Idle ? Idle : expirationTime + ); // We assume that this second render pass will be synchronous + // and therefore not hit this path again. + + break; } + case RootSuspended: { - flushSuspensePriorityWarningInDEV(); + markRootSuspendedAtTime(root, expirationTime); + var lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } - // We have an acceptable loading state. We need to figure out if we should - // immediately commit it or wait a bit. + flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. + // If we have processed new updates during this render, we may now + // have a new loading state ready. We want to ensure that we commit + // that as soon as possible. - // If we have processed new updates during this render, we may now have a - // new loading state ready. We want to ensure that we commit that as soon as - // possible. var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync; + if ( - hasNotProcessedNewUpdates && - !isSync && - // do not delay if we're inside an act() scope + hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // If we have not processed any new updates during this pass, then this is - // either a retry of an existing fallback state or a hidden tree. - // Hidden trees shouldn't be batched with other work and after that's - // fixed it can only be a retry. - // We're going to throttle committing retries so that we don't show too - // many loading states too quickly. + // If we have not processed any new updates during this pass, then + // this is either a retry of an existing fallback state or a + // hidden tree. Hidden trees shouldn't be batched with other work + // and after that's fixed it can only be a retry. We're going to + // throttle committing retries so that we don't show too many + // loading states too quickly. var msUntilTimeout = - globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - // Don't bother with a very short suspense time. + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. + if (msUntilTimeout > 10) { if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart + // earlier so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } } - var _lastPendingTime2 = root.lastPendingTime; - if (_lastPendingTime2 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level. - return renderRoot.bind(null, root, _lastPendingTime2); + + var nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (nextTime !== NoWork && nextTime !== expirationTime) { + // There's additional work on this root. + break; } - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + + if ( + lastSuspendedTime !== NoWork && + lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = lastSuspendedTime; + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. + root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootSuspendedWithDelay: { + markRootSuspendedAtTime(root, expirationTime); + var _lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === _lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } + flushSuspensePriorityWarningInDEV(); if ( - !isSync && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // We're suspended in a state that should be avoided. We'll try to avoid committing - // it for as long as the timeouts let us. + // We're suspended in a state that should be avoided. We'll try to + // avoid committing it for as long as the timeouts let us. if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var _lastPingedTime = root.lastPingedTime; + + if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart earlier + // so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } } - var _lastPendingTime3 = root.lastPendingTime; - if (_lastPendingTime3 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately. - return renderRoot.bind(null, root, _lastPendingTime3); + + var _nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (_nextTime !== NoWork && _nextTime !== expirationTime) { + // There's additional work on this root. + break; + } + + if ( + _lastSuspendedTime !== NoWork && + _lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = _lastSuspendedTime; + break; } - var _msUntilTimeout = void 0; + var _msUntilTimeout; + if (workInProgressRootLatestSuspenseTimeout !== Sync) { - // We have processed a suspense config whose expiration time we can use as - // the timeout. + // We have processed a suspense config whose expiration time we + // can use as the timeout. _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now(); } else if (workInProgressRootLatestProcessedExpirationTime === Sync) { - // This should never normally happen because only new updates cause - // delayed states, so we should have processed something. However, - // this could also happen in an offscreen tree. + // This should never normally happen because only new updates + // cause delayed states, so we should have processed something. + // However, this could also happen in an offscreen tree. _msUntilTimeout = 0; } else { - // If we don't have a suspense config, we're going to use a heuristic to + // If we don't have a suspense config, we're going to use a + // heuristic to determine how long we can suspend. var eventTimeMs = inferTimeFromExpirationTime( workInProgressRootLatestProcessedExpirationTime ); @@ -19195,40 +20137,40 @@ function renderRoot(root, expirationTime, isSync) { var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs; var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed < 0) { // We get this wrong some time since we estimate the time. timeElapsed = 0; } - _msUntilTimeout = jnd(timeElapsed) - timeElapsed; - - // Clamp the timeout to the expiration time. - // TODO: Once the event time is exact instead of inferred from expiration time + _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the + // event time is exact instead of inferred from expiration time // we don't need this. + if (timeUntilExpirationMs < _msUntilTimeout) { _msUntilTimeout = timeUntilExpirationMs; } - } + } // Don't bother with a very short suspense time. - // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootCompleted: { // The work completed. Ready to commit. if ( - !isSync && // do not delay if we're inside an act() scope !( true && @@ -19240,113 +20182,471 @@ function renderRoot(root, expirationTime, isSync) { ) { // If we have exceeded the minimum loading delay, which probably // means we have shown a spinner already, we might have to suspend - // a bit longer to ensure that the spinner is shown for enough time. + // a bit longer to ensure that the spinner is shown for + // enough time. var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay( workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig ); + if (_msUntilTimeout2 > 10) { + markRootSuspendedAtTime(root, expirationTime); root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout2 ); - return null; + break; } } - return commitRoot.bind(null, root); + + commitRoot(root); + break; } + default: { - (function() { - { - throw ReactError(Error("Unknown root exit status.")); - } - })(); + { + throw Error("Unknown root exit status."); + } } } -} +} // This is the entry point for synchronous tasks that don't go +// through Scheduler -function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); -} +function performSyncWorkOnRoot(root) { + // Check if there's expired work on this root. Otherwise, render at Sync. + var lastExpiredTime = root.lastExpiredTime; + var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync; + + if (root.finishedExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + // TODO: This is poorly factored. This case only exists for the + // batch.commit() API. + commitRoot(root); + } else { + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } + + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. -function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { - if ( - expirationTime < workInProgressRootLatestProcessedExpirationTime && - expirationTime > Never - ) { - workInProgressRootLatestProcessedExpirationTime = expirationTime; - } - if (suspenseConfig !== null) { if ( - expirationTime < workInProgressRootLatestSuspenseTimeout && - expirationTime > Never + root !== workInProgressRoot || + expirationTime !== renderExpirationTime ) { - workInProgressRootLatestSuspenseTimeout = expirationTime; - // Most of the time we only have one config and getting wrong is not bad. - workInProgressRootCanSuspendUsingConfig = suspenseConfig; + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. + + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); + + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (enableSchedulerTracing) { + popInteractions(prevInteractions); + } + + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; + } + + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + { + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + } else { + // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. + stopFinishedWorkLoopTimer(); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = expirationTime; + finishSyncRender(root, workInProgressRootExitStatus, expirationTime); + } // Before exiting, make sure there's a callback scheduled for the next + // pending level. + + ensureRootIsScheduled(root); } } + + return null; } -function renderDidSuspend() { - if (workInProgressRootExitStatus === RootIncomplete) { - workInProgressRootExitStatus = RootSuspended; +function finishSyncRender(root, exitStatus, expirationTime) { + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + { + if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) { + flushSuspensePriorityWarningInDEV(); + } } + + commitRoot(root); } -function renderDidSuspendDelayIfPossible() { +function flushDiscreteUpdates() { + // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. + // However, `act` uses `batchedUpdates`, so there's no way to distinguish + // those two cases. Need to fix this before exposing flushDiscreteUpdates + // as a public API. if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended + (executionContext & (BatchedContext | RenderContext | CommitContext)) !== + NoContext ) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } -} + if (true && (executionContext & RenderContext) !== NoContext) { + warning$1( + false, + "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + + "already rendering." + ); + } // We're already rendering, so we can't synchronously flush pending work. + // This is probably a nested event dispatch triggered by a lifecycle/effect, + // like `el.focus()`. Exit. -function renderDidError() { - if (workInProgressRootExitStatus !== RootCompleted) { - workInProgressRootExitStatus = RootErrored; + return; } -} -// Called during render to determine if anything has suspended. -// Returns false if we're not sure. -function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootIncomplete; -} + flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that + // they fire before the next serial event. -function inferTimeFromExpirationTime(expirationTime) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; + flushPassiveEffects(); } -function inferTimeFromExpirationTimeWithSuspenseConfig( - expirationTime, - suspenseConfig -) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time by subtracting the timeout - // that was added to the event time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return ( - earliestExpirationTimeMs - - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) - ); +function syncUpdates(fn, a, b, c) { + return runWithPriority(ImmediatePriority, fn.bind(null, a, b, c)); } -function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. - while (workInProgress !== null) { +function flushPendingDiscreteUpdates() { + if (rootsWithPendingDiscreteUpdates !== null) { + // For each root with pending discrete updates, schedule a callback to + // immediately flush them. + var roots = rootsWithPendingDiscreteUpdates; + rootsWithPendingDiscreteUpdates = null; + roots.forEach(function(expirationTime, root) { + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); + }); // Now flush the immediate queue. + + flushSyncCallbackQueue(); + } +} + +function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function batchedEventUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= EventContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function discreteUpdates$1(fn, a, b, c) { + var prevExecutionContext = executionContext; + executionContext |= DiscreteEventContext; + + try { + // Should this + return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} + +function flushSync(fn, a) { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + { + throw Error( + "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." + ); + } + } + + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return runWithPriority(ImmediatePriority, fn.bind(null, a)); + } finally { + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. + + flushSyncCallbackQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.finishedWork = null; + root.finishedExpirationTime = NoWork; + var timeoutHandle = root.timeoutHandle; + + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above + + cancelTimeout(timeoutHandle); + } + + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + + while (interruptedWork !== null) { + unwindInterruptedWork(interruptedWork); + interruptedWork = interruptedWork.return; + } + } + + workInProgressRoot = root; + workInProgress = createWorkInProgress(root.current, null, expirationTime); + renderExpirationTime = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; + workInProgressRootLatestProcessedExpirationTime = Sync; + workInProgressRootLatestSuspenseTimeout = Sync; + workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = NoWork; + workInProgressRootHasPendingPing = false; + + if (enableSchedulerTracing) { + spawnedWorkDuringRender = null; + } + + { + ReactStrictModeWarnings.discardPendingWarnings(); + componentsThatTriggeredHighPriSuspend = null; + } +} + +function handleError(root, thrownValue) { + do { + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooks(); + resetCurrentFiber(); + + if (workInProgress === null || workInProgress.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + return null; + } + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true); + } + + throwException( + root, + workInProgress.return, + workInProgress, + thrownValue, + renderExpirationTime + ); + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; + continue; + } // Return to the normal work loop. + + return; + } while (true); +} + +function pushDispatcher(root) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } +} + +function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher.current = prevDispatcher; +} + +function pushInteractions(root) { + if (enableSchedulerTracing) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; + } + + return null; +} + +function popInteractions(prevInteractions) { + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } +} + +function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); +} +function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { + if ( + expirationTime < workInProgressRootLatestProcessedExpirationTime && + expirationTime > Idle + ) { + workInProgressRootLatestProcessedExpirationTime = expirationTime; + } + + if (suspenseConfig !== null) { + if ( + expirationTime < workInProgressRootLatestSuspenseTimeout && + expirationTime > Idle + ) { + workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad. + + workInProgressRootCanSuspendUsingConfig = suspenseConfig; + } + } +} +function markUnprocessedUpdateTime(expirationTime) { + if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) { + workInProgressRootNextUnprocessedUpdateTime = expirationTime; + } +} +function renderDidSuspend() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} +function renderDidSuspendDelayIfPossible() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there's a lower priority update somewhere else in the tree. + + if ( + workInProgressRootNextUnprocessedUpdateTime !== NoWork && + workInProgressRoot !== null + ) { + // Mark the current render as suspended, and then mark that there's a + // pending update. + // TODO: This should immediately interrupt the current render, instead + // of waiting until the next time we yield. + markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime); + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + ); + } +} +function renderDidError() { + if (workInProgressRootExitStatus !== RootCompleted) { + workInProgressRootExitStatus = RootErrored; + } +} // Called during render to determine if anything has suspended. +// Returns false if we're not sure. + +function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootIncomplete; +} + +function inferTimeFromExpirationTime(expirationTime) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; +} + +function inferTimeFromExpirationTimeWithSuspenseConfig( + expirationTime, + suspenseConfig +) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time by subtracting the timeout + // that was added to the event time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return ( + earliestExpirationTimeMs - + (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) + ); +} // The work loop is an extremely hot path. Tell Closure not to inline it. + +/** @noinline */ + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { workInProgress = performUnitOfWork(workInProgress); } } +/** @noinline */ -function workLoop() { +function workLoopConcurrent() { // Perform work until Scheduler asks us to yield while (workInProgress !== null && !shouldYield()) { workInProgress = performUnitOfWork(workInProgress); @@ -19358,11 +20658,10 @@ function performUnitOfWork(unitOfWork) { // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = unitOfWork.alternate; - startWorkTimer(unitOfWork); setCurrentFiber(unitOfWork); + var next; - var next = void 0; if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { startProfilerTimer(unitOfWork); next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); @@ -19373,6 +20672,7 @@ function performUnitOfWork(unitOfWork) { resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { // If this doesn't spawn new work, complete the current work. next = completeUnitOfWork(unitOfWork); @@ -19386,17 +20686,18 @@ function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. workInProgress = unitOfWork; + do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = workInProgress.alternate; - var returnFiber = workInProgress.return; + var returnFiber = workInProgress.return; // Check if the work completed or if something threw. - // Check if the work completed or if something threw. if ((workInProgress.effectTag & Incomplete) === NoEffect) { setCurrentFiber(workInProgress); var next = void 0; + if ( !enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode @@ -19404,10 +20705,11 @@ function completeUnitOfWork(unitOfWork) { next = completeWork(current$$1, workInProgress, renderExpirationTime); } else { startProfilerTimer(workInProgress); - next = completeWork(current$$1, workInProgress, renderExpirationTime); - // Update render duration assuming we didn't error. + next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); } + stopWorkTimer(workInProgress); resetCurrentFiber(); resetChildExpirationTime(workInProgress); @@ -19418,8 +20720,7 @@ function completeUnitOfWork(unitOfWork) { } if ( - returnFiber !== null && - // Do not append effects to parents if a sibling failed to complete + returnFiber !== null && // Do not append effects to parents if a sibling failed to complete (returnFiber.effectTag & Incomplete) === NoEffect ) { // Append all the effects of the subtree and this fiber onto the effect @@ -19428,30 +20729,31 @@ function completeUnitOfWork(unitOfWork) { if (returnFiber.firstEffect === null) { returnFiber.firstEffect = workInProgress.firstEffect; } + if (workInProgress.lastEffect !== null) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; } - returnFiber.lastEffect = workInProgress.lastEffect; - } - // If this fiber had side-effects, we append it AFTER the children's + returnFiber.lastEffect = workInProgress.lastEffect; + } // If this fiber had side-effects, we append it AFTER the children's // side-effects. We can perform certain side-effects earlier if needed, // by doing multiple passes over the effect list. We don't want to // schedule our own side-effect on our own list because if end up // reusing children we'll schedule this effect onto itself since we're // at the end. - var effectTag = workInProgress.effectTag; - // Skip both NoWork and PerformedWork tags when creating the effect + var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect // list. PerformedWork effect is read by React DevTools but shouldn't be // committed. + if (effectTag > PerformedWork) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress; } else { returnFiber.firstEffect = workInProgress; } + returnFiber.lastEffect = workInProgress; } } @@ -19459,24 +20761,23 @@ function completeUnitOfWork(unitOfWork) { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. - var _next = unwindWork(workInProgress, renderExpirationTime); - - // Because this fiber did not complete, don't reset its expiration time. + var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time. if ( enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode ) { // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing. - // Include the time spent working on failed children before continuing. var actualDuration = workInProgress.actualDuration; var child = workInProgress.child; + while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } + workInProgress.actualDuration = actualDuration; } @@ -19491,6 +20792,7 @@ function completeUnitOfWork(unitOfWork) { _next.effectTag &= HostEffectMask; return _next; } + stopWorkTimer(workInProgress); if (returnFiber !== null) { @@ -19501,21 +20803,30 @@ function completeUnitOfWork(unitOfWork) { } var siblingFiber = workInProgress.sibling; + if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; - } - // Otherwise, return to the parent + } // Otherwise, return to the parent + workInProgress = returnFiber; - } while (workInProgress !== null); + } while (workInProgress !== null); // We've reached the root. - // We've reached the root. if (workInProgressRootExitStatus === RootIncomplete) { workInProgressRootExitStatus = RootCompleted; } + return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + var childExpirationTime = fiber.childExpirationTime; + return updateExpirationTime > childExpirationTime + ? updateExpirationTime + : childExpirationTime; +} + function resetChildExpirationTime(completedWork) { if ( renderExpirationTime !== Never && @@ -19526,55 +20837,62 @@ function resetChildExpirationTime(completedWork) { return; } - var newChildExpirationTime = NoWork; + var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time. - // Bubble up the earliest expiration time. if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - - // When a fiber is cloned, its actualDuration is reset to 0. This value will + var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. + var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child; - var child = completedWork.child; + while (child !== null) { var childUpdateExpirationTime = child.expirationTime; var childChildExpirationTime = child.childExpirationTime; + if (childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = childUpdateExpirationTime; } + if (childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = childChildExpirationTime; } + if (shouldBubbleActualDurations) { actualDuration += child.actualDuration; } + treeBaseDuration += child.treeBaseDuration; child = child.sibling; } + completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; + while (_child !== null) { var _childUpdateExpirationTime = _child.expirationTime; var _childChildExpirationTime = _child.childExpirationTime; + if (_childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childUpdateExpirationTime; } + if (_childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childChildExpirationTime; } + _child = _child.sibling; } } @@ -19588,14 +20906,6 @@ function commitRoot(root) { ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel) ); - // If there are passive effects, schedule a callback to flush them. This goes - // outside commitRootImpl so that it inherits the priority of the render. - if (rootWithPendingPassiveEffects !== null) { - scheduleCallback(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } return null; } @@ -19603,51 +20913,42 @@ function commitRootImpl(root, renderPriorityLevel) { flushPassiveEffects(); flushRenderPhaseStrictModeWarningsInDEV(); - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } var finishedWork = root.finishedWork; var expirationTime = root.finishedExpirationTime; + if (finishedWork === null) { return null; } + root.finishedWork = null; root.finishedExpirationTime = NoWork; - (function() { - if (!(finishedWork !== root.current)) { - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - - // commitRoot never returns a continuation; it always finishes synchronously. + if (!(finishedWork !== root.current)) { + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. + root.callbackNode = null; root.callbackExpirationTime = NoWork; - - startCommitTimer(); - - // Update the first and last pending times on this root. The new first + root.callbackPriority = NoPriority; + root.nextKnownPendingLevel = NoWork; + startCommitTimer(); // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime; - var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - var firstPendingTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = firstPendingTimeBeforeCommit; - if (firstPendingTimeBeforeCommit < root.lastPendingTime) { - // This usually means we've finished all the work, but it can also happen - // when something gets downprioritized during render, like a hidden tree. - root.lastPendingTime = firstPendingTimeBeforeCommit; - } + + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + markRootFinishedAtTime( + root, + expirationTime, + remainingExpirationTimeBeforeCommit + ); if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -19655,13 +20956,13 @@ function commitRootImpl(root, renderPriorityLevel) { workInProgress = null; renderExpirationTime = NoWork; } else { - } - // This indicates that the last root we worked on is not the same one that + } // This indicates that the last root we worked on is not the same one that // we're committing now. This most commonly happens when a suspended root // times out. - // Get the list of effects. - var firstEffect = void 0; + + var firstEffect; + if (finishedWork.effectTag > PerformedWork) { // A fiber's effect list consists only of its children, not itself. So if // the root has an effect, we need to add it to the end of the list. The @@ -19681,85 +20982,82 @@ function commitRootImpl(root, renderPriorityLevel) { if (firstEffect !== null) { var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } + var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles - // Reset this to null before calling lifecycles - ReactCurrentOwner$2.current = null; - - // The commit phase is broken into several sub-phases. We do a separate pass + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. + startCommitSnapshotEffectsTimer(); prepareForCommit(root.containerInfo); nextEffect = firstEffect; + do { { invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); + stopCommitSnapshotEffectsTimer(); if (enableProfilerTimer) { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. - // The next phase is the mutation phase, where we mutate the host tree. startCommitHostEffectsTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( null, commitMutationEffects, null, + root, renderPriorityLevel ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitHostEffectsTimer(); - resetAfterCommit(root.containerInfo); - // The work-in-progress tree is now the current tree. This must come after + stopCommitHostEffectsTimer(); + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. - root.current = finishedWork; - // The next phase is the layout phase, where we call effects that read + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read // the host tree after it's been mutated. The idiomatic use case for this is // layout, but class component lifecycles also fire here for legacy reasons. + startCommitLifeCyclesTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( @@ -19769,41 +21067,44 @@ function commitRootImpl(root, renderPriorityLevel) { root, expirationTime ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error2 = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error2); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitLifeCyclesTimer(); - - nextEffect = null; - // Tell Scheduler to yield at the end of the frame, so the browser has an + stopCommitLifeCyclesTimer(); + nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an // opportunity to paint. + requestPaint(); if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); } + executionContext = prevExecutionContext; } else { // No effects. - root.current = finishedWork; - // Measure these anyway so the flamegraph explicitly shows that there were + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. + startCommitSnapshotEffectsTimer(); stopCommitSnapshotEffectsTimer(); + if (enableProfilerTimer) { recordCommitTime(); } + startCommitHostEffectsTimer(); stopCommitHostEffectsTimer(); startCommitLifeCyclesTimer(); @@ -19811,7 +21112,6 @@ function commitRootImpl(root, renderPriorityLevel) { } stopCommitTimer(); - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { @@ -19826,26 +21126,22 @@ function commitRootImpl(root, renderPriorityLevel) { // nextEffect pointers to assist with GC. If we have passive effects, we'll // clear this in flushPassiveEffects. nextEffect = firstEffect; + while (nextEffect !== null) { var nextNextEffect = nextEffect.nextEffect; nextEffect.nextEffect = null; nextEffect = nextNextEffect; } - } + } // Check if there's remaining work on this root - // Check if there's remaining work on this root var remainingExpirationTime = root.firstPendingTime; - if (remainingExpirationTime !== NoWork) { - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - remainingExpirationTime - ); + if (remainingExpirationTime !== NoWork) { if (enableSchedulerTracing) { if (spawnedWorkDuringRender !== null) { var expirationTimes = spawnedWorkDuringRender; spawnedWorkDuringRender = null; + for (var i = 0; i < expirationTimes.length; i++) { scheduleInteractions( root, @@ -19854,9 +21150,9 @@ function commitRootImpl(root, renderPriorityLevel) { ); } } - } - scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + schedulePendingInteractions(root, remainingExpirationTime); + } } else { // If there's no remaining work, we can clear the set of already failed // error boundaries. @@ -19873,8 +21169,6 @@ function commitRootImpl(root, renderPriorityLevel) { } } - onCommitRoot(finishedWork.stateNode, expirationTime); - if (remainingExpirationTime === Sync) { // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. @@ -19888,6 +21182,11 @@ function commitRootImpl(root, renderPriorityLevel) { nestedUpdateCount = 0; } + onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. + + ensureRootIsScheduled(root); + if (hasUncaughtError) { hasUncaughtError = false; var _error3 = firstUncaughtError; @@ -19901,33 +21200,44 @@ function commitRootImpl(root, renderPriorityLevel) { // synchronously, but layout updates should be deferred until the end // of the batch. return null; - } + } // If layout work was scheduled, flush it now. - // If layout work was scheduled, flush it now. flushSyncCallbackQueue(); return null; } function commitBeforeMutationEffects() { while (nextEffect !== null) { - if ((nextEffect.effectTag & Snapshot) !== NoEffect) { + var effectTag = nextEffect.effectTag; + + if ((effectTag & Snapshot) !== NoEffect) { setCurrentFiber(nextEffect); recordEffect(); - var current$$1 = nextEffect.alternate; commitBeforeMutationLifeCycles(current$$1, nextEffect); - resetCurrentFiber(); } + + if ((effectTag & Passive) !== NoEffect) { + // If there are passive effects, schedule a callback to flush at + // the earliest opportunity. + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + nextEffect = nextEffect.nextEffect; } } -function commitMutationEffects(renderPriorityLevel) { +function commitMutationEffects(root, renderPriorityLevel) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & ContentReset) { @@ -19936,52 +21246,67 @@ function commitMutationEffects(renderPriorityLevel) { if (effectTag & Ref) { var current$$1 = nextEffect.alternate; + if (current$$1 !== null) { commitDetachRef(current$$1); } - } - - // The following switch statement is only concerned about placement, + } // The following switch statement is only concerned about placement, // updates, and deletions. To avoid needing to add a case for every possible // bitmap value, we remove the secondary effects from the effect tag and // switch on that value. - var primaryEffectTag = effectTag & (Placement | Update | Deletion); + + var primaryEffectTag = + effectTag & (Placement | Update | Deletion | Hydrating); + switch (primaryEffectTag) { case Placement: { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. + nextEffect.effectTag &= ~Placement; break; } + case PlacementAndUpdate: { // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - // Update + nextEffect.effectTag &= ~Placement; // Update + var _current = nextEffect.alternate; commitWork(_current, nextEffect); break; } - case Update: { + + case Hydrating: { + nextEffect.effectTag &= ~Hydrating; + break; + } + + case HydratingAndUpdate: { + nextEffect.effectTag &= ~Hydrating; // Update + var _current2 = nextEffect.alternate; commitWork(_current2, nextEffect); break; } + + case Update: { + var _current3 = nextEffect.alternate; + commitWork(_current3, nextEffect); + break; + } + case Deletion: { - commitDeletion(nextEffect, renderPriorityLevel); + commitDeletion(root, nextEffect, renderPriorityLevel); break; } - } + } // TODO: Only record a mutation effect if primaryEffectTag is non-zero. - // TODO: Only record a mutation effect if primaryEffectTag is non-zero. recordEffect(); - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } @@ -19991,7 +21316,6 @@ function commitLayoutEffects(root, committedExpirationTime) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) { @@ -20005,88 +21329,78 @@ function commitLayoutEffects(root, committedExpirationTime) { commitAttachRef(nextEffect); } - if (effectTag & Passive) { - rootDoesHavePassiveEffects = true; - } - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } } function flushPassiveEffects() { + if (pendingPassiveEffectsRenderPriority !== NoPriority) { + var priorityLevel = + pendingPassiveEffectsRenderPriority > NormalPriority + ? NormalPriority + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = NoPriority; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} + +function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } + var root = rootWithPendingPassiveEffects; var expirationTime = pendingPassiveEffectsExpirationTime; - var renderPriorityLevel = pendingPassiveEffectsRenderPriority; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = NoWork; - pendingPassiveEffectsRenderPriority = NoPriority; - var priorityLevel = - renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; - return runWithPriority( - priorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Cannot flush passive effects while already rendering."); } - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); - } - })(); var prevExecutionContext = executionContext; executionContext |= CommitContext; - - // Note: This currently assumes there are no passive effects on the root + var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root // fiber, because the root is not part of its own effect list. This could // change in the future. + var effect = root.current.firstEffect; + while (effect !== null) { { setCurrentFiber(effect); invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + if (hasCaughtError()) { - (function() { - if (!(effect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(effect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(effect, error); } + resetCurrentFiber(); } - var nextNextEffect = effect.nextEffect; - // Remove nextEffect pointer to assist GC + + var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC + effect.nextEffect = null; effect = nextNextEffect; } if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); finishPendingInteractions(root, expirationTime); } executionContext = prevExecutionContext; - flushSyncCallbackQueue(); - - // If additional passive effects were scheduled, increment a counter. If this + flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; - return true; } @@ -20096,7 +21410,6 @@ function isAlreadyFailedLegacyErrorBoundary(instance) { legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } - function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); @@ -20111,6 +21424,7 @@ function prepareToThrowUncaughtError(error) { firstUncaughtError = error; } } + var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { @@ -20118,8 +21432,10 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); enqueueUpdate(rootFiber, update); var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } } @@ -20132,6 +21448,7 @@ function captureCommitPhaseError(sourceFiber, error) { } var fiber = sourceFiber.return; + while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); @@ -20139,6 +21456,7 @@ function captureCommitPhaseError(sourceFiber, error) { } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; + if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && @@ -20147,24 +21465,27 @@ function captureCommitPhaseError(sourceFiber, error) { var errorInfo = createCapturedValue(error, sourceFiber); var update = createClassErrorUpdate( fiber, - errorInfo, - // TODO: This is always sync + errorInfo, // TODO: This is always sync Sync ); enqueueUpdate(fiber, update); var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } + return; } } + fiber = fiber.return; } } - function pingSuspendedRoot(root, thenable, suspendedTime) { var pingCache = root.pingCache; + if (pingCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. @@ -20175,10 +21496,8 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. - // If we're suspended with delay, we'll always suspend so we can always // restart. If we're suspended without any updates, it might be a retry. // If it's early in the retry we can restart. We can't know for sure @@ -20199,23 +21518,23 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // opportunity later. So we mark this render as having a ping. workInProgressRootHasPendingPing = true; } + return; } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < suspendedTime) { + if (!isRootSuspendedAtTime(root, suspendedTime)) { // The root is no longer suspended at this time. return; } - var pingTime = root.pingTime; - if (pingTime !== NoWork && pingTime < suspendedTime) { + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) { // There's already a lower priority ping scheduled. return; - } + } // Mark the time at which this ping was scheduled. - // Mark the time at which this ping was scheduled. - root.pingTime = suspendedTime; + root.lastPingedTime = suspendedTime; if (root.finishedExpirationTime === suspendedTime) { // If there's a pending fallback waiting to commit, throw it away. @@ -20223,54 +21542,70 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { root.finishedWork = null; } - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - suspendedTime - ); - scheduleCallbackForRoot(root, priorityLevel, suspendedTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, suspendedTime); } -function retryTimedOutBoundary(boundaryFiber) { +function retryTimedOutBoundary(boundaryFiber, retryTime) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new expiration time. - var currentTime = requestCurrentTime(); - var suspenseConfig = null; // Retries don't carry over the already committed update. - var retryTime = computeExpirationForFiber( - currentTime, - boundaryFiber, - suspenseConfig - ); - // TODO: Special case idle priority? - var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + if (retryTime === NoWork) { + var suspenseConfig = null; // Retries don't carry over the already committed update. + + var currentTime = requestCurrentTime(); + retryTime = computeExpirationForFiber( + currentTime, + boundaryFiber, + suspenseConfig + ); + } // TODO: Special case idle priority? + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { - scheduleCallbackForRoot(root, priorityLevel, retryTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, retryTime); } } +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryTime = NoWork; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + + retryTimedOutBoundary(boundaryFiber, retryTime); +} function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = void 0; + var retryTime = NoWork; // Default + + var retryCache; + if (enableSuspenseServerRenderer) { switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + break; - case DehydratedSuspenseComponent: - retryCache = boundaryFiber.memoizedState; + + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; break; - default: - (function() { - { - throw ReactError( - Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ) - ); - } - })(); + + default: { + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } } } else { retryCache = boundaryFiber.stateNode; @@ -20282,10 +21617,8 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); -} - -// Computes the next Just Noticeable Difference (JND) boundary. + retryTimedOutBoundary(boundaryFiber, retryTime); +} // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid @@ -20294,6 +21627,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. + function jnd(timeElapsed) { return timeElapsed < 120 ? 120 @@ -20316,25 +21650,28 @@ function computeMsUntilSuspenseLoadingDelay( suspenseConfig ) { var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0; + if (busyMinDurationMs <= 0) { return 0; } - var busyDelayMs = suspenseConfig.busyDelayMs | 0; - // Compute the time until this render pass would expire. + var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire. + var currentTimeMs = now(); var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig( mostRecentEventTime, suspenseConfig ); var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed <= busyDelayMs) { // If we haven't yet waited longer than the initial delay, we don't // have to wait any additional time. return 0; } - var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; - // This is the value that is passed to `setTimeout`. + + var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`. + return msUntilTimeout; } @@ -20342,15 +21679,12 @@ function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; - (function() { - { - throw ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) - ); - } - })(); + + { + 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." + ); + } } { @@ -20401,9 +21735,11 @@ function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { } var didWarnStateUpdateForUnmountedComponent = null; + function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { { var tag = fiber.tag; + if ( tag !== HostRoot && tag !== ClassComponent && @@ -20414,18 +21750,21 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { ) { // Only warn for user-defined components, not internal ones like Suspense. return; - } - // We show the whole stack but dedupe on the top component's name because + } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent !== null) { if (didWarnStateUpdateForUnmountedComponent.has(componentName)) { return; } + didWarnStateUpdateForUnmountedComponent.add(componentName); } else { didWarnStateUpdateForUnmountedComponent = new Set([componentName]); } + warningWithoutStack$1( false, "Can't perform a React state update on an unmounted component. This " + @@ -20439,20 +21778,22 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { } } -var beginWork$$1 = void 0; +var beginWork$$1; + if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var dummyFiber = null; + beginWork$$1 = function(current$$1, unitOfWork, expirationTime) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV( dummyFiber, unitOfWork ); + try { return beginWork$1(current$$1, unitOfWork, expirationTime); } catch (originalError) { @@ -20463,25 +21804,23 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ) { // Don't replay promises. Treat everything else like an error. throw originalError; - } - - // Keep this code in sync with renderRoot; any changes here must have + } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. - resetContextDependencies(); - resetHooks(); + resetContextDependencies(); + resetHooks(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. // Unwind the failed stack frame - unwindInterruptedWork(unitOfWork); - // Restore the original properties of the fiber. + unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber. + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if (enableProfilerTimer && unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); - } + } // Run beginWork again. - // Run beginWork again. invokeGuardedCallback( null, beginWork$1, @@ -20492,9 +21831,9 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ); if (hasCaughtError()) { - var replayError = clearCaughtError(); - // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. + var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. // Rethrow this error instead of the original one. + throw replayError; } else { // This branch is reachable if the render phase is impure. @@ -20508,6 +21847,7 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInGetChildContext = false; + function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { { if (fiber.tag === ClassComponent) { @@ -20516,16 +21856,19 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { if (didWarnAboutUpdateInGetChildContext) { return; } + warningWithoutStack$1( false, "setState(...): Cannot call setState() inside getChildContext()" ); didWarnAboutUpdateInGetChildContext = true; break; + case "render": if (didWarnAboutUpdateInRender) { return; } + warningWithoutStack$1( false, "Cannot update during an existing state transition (such as " + @@ -20537,11 +21880,11 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { } } } -} - -// a 'shared' variable that changes when act() opens/closes in tests. -var IsThisRendererActing = { current: false }; +} // a 'shared' variable that changes when act() opens/closes in tests. +var IsThisRendererActing = { + current: false +}; function warnIfNotScopedWithMatchingAct(fiber) { { if ( @@ -20568,7 +21911,6 @@ function warnIfNotScopedWithMatchingAct(fiber) { } } } - function warnIfNotCurrentlyActingEffectsInDEV(fiber) { { if ( @@ -20625,11 +21967,9 @@ function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { } } -var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; +var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler. -// In tests, we want to enforce a mocked scheduler. -var didWarnAboutUnmockedScheduler = false; -// TODO Before we release concurrent mode, revisit this and decide whether a mocked +var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked // scheduler is the actual recommendation. The alternative could be a testing build, // a new lib, or whatever; we dunno just yet. This message is for early adopters // to get their tests right. @@ -20664,20 +22004,22 @@ function warnIfUnmockedScheduler(fiber) { } } } - var componentsThatTriggeredHighPriSuspend = null; function checkForWrongSuspensePriorityInDEV(sourceFiber) { { var currentPriorityLevel = getCurrentPriorityLevel(); + if ( (sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority || currentPriorityLevel === ImmediatePriority) ) { var workInProgressNode = sourceFiber; + while (workInProgressNode !== null) { // Add the component that triggered the suspense var current$$1 = workInProgressNode.alternate; + if (current$$1 !== null) { // TODO: warn component that triggers the high priority // suspend is the HostRoot @@ -20686,10 +22028,13 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { // Loop through the component's update queue and see whether the component // has triggered any high priority updates var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var update = updateQueue.firstUpdate; + while (update !== null) { var priorityLevel = update.priority; + if ( priorityLevel === UserBlockingPriority || priorityLevel === ImmediatePriority @@ -20703,12 +22048,16 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + update = update.next; } } + break; + case FunctionComponent: case ForwardRef: case SimpleMemoComponent: @@ -20716,11 +22065,12 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null ) { - var _update = workInProgressNode.memoizedState.baseUpdate; - // Loop through the functional component's memoized state to see whether + var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether // the component has triggered any high pri updates + while (_update !== null) { var priority = _update.priority; + if ( priority === UserBlockingPriority || priority === ImmediatePriority @@ -20734,21 +22084,27 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + if ( _update.next === workInProgressNode.memoizedState.baseUpdate ) { break; } + _update = _update.next; } } + break; + default: break; } } + workInProgressNode = workInProgressNode.return; } } @@ -20774,8 +22130,7 @@ function flushSuspensePriorityWarningInDEV() { "triggers the bulk of the changes." + "\n\n" + "Refer to the documentation for useSuspenseTransition to learn how " + - "to implement this pattern.", - // TODO: Add link to React docs with more information, once it exists + "to implement this pattern.", // TODO: Add link to React docs with more information, once it exists componentNames.sort().join(", ") ); } @@ -20792,6 +22147,7 @@ function markSpawnedWork(expirationTime) { if (!enableSchedulerTracing) { return; } + if (spawnedWorkDuringRender === null) { spawnedWorkDuringRender = [expirationTime]; } else { @@ -20807,6 +22163,7 @@ function scheduleInteractions(root, expirationTime, interactions) { if (interactions.size > 0) { var pendingInteractionMap = root.pendingInteractionMap; var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { interactions.forEach(function(interaction) { if (!pendingInteractions.has(interaction)) { @@ -20817,15 +22174,15 @@ function scheduleInteractions(root, expirationTime, interactions) { pendingInteractions.add(interaction); }); } else { - pendingInteractionMap.set(expirationTime, new Set(interactions)); + pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions. - // Update the pending async work count for the current interactions. interactions.forEach(function(interaction) { interaction.__count++; }); } var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); subscriber.onWorkScheduled(interactions, threadID); @@ -20848,11 +22205,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { // This is called when new work is started on a root. if (!enableSchedulerTracing) { return; - } - - // Determine which interactions this batch of work currently includes, So that + } // Determine which interactions this batch of work currently includes, So that // we can accurately attribute time spent working on it, And so that cascading // work triggered during the render phase will be associated with it. + var interactions = new Set(); root.pendingInteractionMap.forEach(function( scheduledInteractions, @@ -20863,19 +22219,20 @@ function startWorkOnPendingInteractions(root, expirationTime) { return interactions.add(interaction); }); } - }); + }); // Store the current set of interactions on the FiberRoot for a few reasons: + // We can re-use it in hot functions like performConcurrentWorkOnRoot() + // without having to recalculate it. We will also use it in commitWork() to + // pass to any Profiler onRender() hooks. This also provides DevTools with a + // way to access it when the onCommitRoot() hook is called. - // Store the current set of interactions on the FiberRoot for a few reasons: - // We can re-use it in hot functions like renderRoot() without having to - // recalculate it. We will also use it in commitWork() to pass to any Profiler - // onRender() hooks. This also provides DevTools with a way to access it when - // the onCommitRoot() hook is called. root.memoizedInteractions = interactions; if (interactions.size > 0) { var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); + try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { @@ -20894,11 +22251,11 @@ function finishPendingInteractions(root, committedExpirationTime) { } var earliestRemainingTimeAfterCommit = root.firstPendingTime; - - var subscriber = void 0; + var subscriber; try { subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { var threadID = computeThreadID(root, committedExpirationTime); subscriber.onWorkStopped(root.memoizedInteractions, threadID); @@ -20922,7 +22279,6 @@ function finishPendingInteractions(root, committedExpirationTime) { // That indicates that we are waiting for suspense data. if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { pendingInteractionMap.delete(scheduledExpirationTime); - scheduledInteractions.forEach(function(interaction) { interaction.__count--; @@ -20945,21 +22301,22 @@ function finishPendingInteractions(root, committedExpirationTime) { var onCommitFiberRoot = null; var onCommitFiberUnmount = null; var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; - function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { // No DevTools return false; } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } + if (!hook.supportsFiber) { { warningWithoutStack$1( @@ -20968,16 +22325,18 @@ function injectInternals(internals) { "with the current version of React. Please update React DevTools. " + "https://fb.me/react-devtools" ); - } - // DevTools exists, even though it doesn't support Fiber. + } // DevTools exists, even though it doesn't support Fiber. + return true; } + try { - var rendererID = hook.inject(internals); - // We have successfully injected, so now it is safe to set up hooks. + var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. + onCommitFiberRoot = function(root, expirationTime) { try { var didError = (root.current.effectTag & DidCapture) === DidCapture; + if (enableProfilerTimer) { var currentTime = requestCurrentTime(); var priorityLevel = inferPriorityFromExpirationTime( @@ -20999,6 +22358,7 @@ function injectInternals(internals) { } } }; + onCommitFiberUnmount = function(fiber) { try { hook.onCommitFiberUnmount(rendererID, fiber); @@ -21022,34 +22382,33 @@ function injectInternals(internals) { err ); } - } - // DevTools exists + } // DevTools exists + return true; } - function onCommitRoot(root, expirationTime) { if (typeof onCommitFiberRoot === "function") { onCommitFiberRoot(root, expirationTime); } } - function onCommitUnmount(fiber) { if (typeof onCommitFiberUnmount === "function") { onCommitFiberUnmount(fiber); } } -var hasBadMapPolyfill = void 0; +var hasBadMapPolyfill; { hasBadMapPolyfill = false; + try { var nonExtensibleObject = Object.preventExtensions({}); var testMap = new Map([[nonExtensibleObject, null]]); - var testSet = new Set([nonExtensibleObject]); - // This is necessary for Rollup to not consider these unused. + var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. + testMap.set(0, 0); testSet.add(0); } catch (e) { @@ -21058,14 +22417,7 @@ var hasBadMapPolyfill = void 0; } } -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. - -var debugCounter = void 0; - -{ - debugCounter = 1; -} +var debugCounter = 1; function FiberNode(tag, pendingProps, key, mode) { // Instance @@ -21073,34 +22425,26 @@ function FiberNode(tag, pendingProps, key, mode) { this.key = key; this.elementType = null; this.type = null; - this.stateNode = null; + this.stateNode = null; // Fiber - // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; + this.mode = mode; // Effects - this.mode = mode; - - // Effects this.effectTag = NoEffect; this.nextEffect = null; - this.firstEffect = null; this.lastEffect = null; - this.expirationTime = NoWork; this.childExpirationTime = NoWork; - this.alternate = null; if (enableProfilerTimer) { @@ -21119,31 +22463,33 @@ function FiberNode(tag, pendingProps, key, mode) { this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - - // It's okay to replace the initial doubles with smis after initialization. + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). + this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; + } // This is normally DEV-only except www when it adds listeners. + // TODO: remove the User Timing integration in favor of Root Events. + + if (enableUserTimingAPI) { + this._debugID = debugCounter++; + this._debugIsCurrentlyTiming = false; } { - this._debugID = debugCounter++; this._debugSource = null; this._debugOwner = null; - this._debugIsCurrentlyTiming = false; this._debugNeedsRemount = false; this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } } -} - -// This is a constructor function, rather than a POJO constructor, still +} // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost @@ -21156,6 +22502,7 @@ function FiberNode(tag, pendingProps, key, mode) { // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. + var createFiber = function(tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); @@ -21173,25 +22520,27 @@ function isSimpleFunctionComponent(type) { type.defaultProps === undefined ); } - function resolveLazyComponentTag(Component) { if (typeof Component === "function") { return shouldConstruct(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; + if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } + if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } + return IndeterminateComponent; -} +} // This is used to create an alternate fiber to do work on. -// This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps, expirationTime) { var workInProgress = current.alternate; + if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused @@ -21219,13 +22568,11 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.alternate = current; current.alternate = workInProgress; } else { - workInProgress.pendingProps = pendingProps; - - // We already have an alternate. + workInProgress.pendingProps = pendingProps; // We already have an alternate. // Reset the effect tag. - workInProgress.effectTag = NoEffect; - // The effect list is no longer valid. + workInProgress.effectTag = NoEffect; // The effect list is no longer valid. + workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; @@ -21242,14 +22589,12 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21258,9 +22603,8 @@ function createWorkInProgress(current, pendingProps, expirationTime) { expirationTime: currentDependencies.expirationTime, firstContext: currentDependencies.firstContext, responders: currentDependencies.responders - }; + }; // These will be overridden during the parent's reconciliation - // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; @@ -21272,56 +22616,54 @@ function createWorkInProgress(current, pendingProps, expirationTime) { { workInProgress._debugNeedsRemount = current._debugNeedsRemount; + switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; + case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; + case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; + default: break; } } return workInProgress; -} +} // Used to reuse a Fiber for a second pass. -// Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderExpirationTime) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. - // Reset the effect tag but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. - workInProgress.effectTag &= Placement; + workInProgress.effectTag &= Placement; // The effect list is no longer valid. - // The effect list is no longer valid. workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; - var current = workInProgress.alternate; + if (current === null) { // Reset to createFiber's initial values. workInProgress.childExpirationTime = NoWork; workInProgress.expirationTime = renderExpirationTime; - workInProgress.child = null; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; - workInProgress.dependencies = null; if (enableProfilerTimer) { @@ -21334,14 +22676,12 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21362,9 +22702,9 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { return workInProgress; } - function createHostRootFiber(tag) { - var mode = void 0; + var mode; + if (tag === ConcurrentRoot) { mode = ConcurrentMode | BatchedMode | StrictMode; } else if (tag === BatchedRoot) { @@ -21382,7 +22722,6 @@ function createHostRootFiber(tag) { return createFiber(HostRoot, null, null, mode); } - function createFiberFromTypeAndProps( type, // React$ElementType key, @@ -21391,14 +22730,15 @@ function createFiberFromTypeAndProps( mode, expirationTime ) { - var fiber = void 0; + var fiber; + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - var fiberTag = IndeterminateComponent; - // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; + if (typeof type === "function") { if (shouldConstruct(type)) { fiberTag = ClassComponent; + { resolvedType = resolveClassForHotReloading(resolvedType); } @@ -21418,18 +22758,23 @@ function createFiberFromTypeAndProps( expirationTime, key ); + case REACT_CONCURRENT_MODE_TYPE: fiberTag = Mode; mode |= ConcurrentMode | BatchedMode | StrictMode; break; + case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictMode; break; + case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList( pendingProps, @@ -21437,29 +22782,37 @@ function createFiberFromTypeAndProps( expirationTime, key ); + default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; + case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; + case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; + { resolvedType = resolveForwardRefForHotReloading(resolvedType); } + break getTag; + case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; + case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_FUNDAMENTAL_TYPE: if (enableFundamentalAPI) { return createFiberFromFundamental( @@ -21470,10 +22823,24 @@ function createFiberFromTypeAndProps( key ); } + break; + + case REACT_SCOPE_TYPE: + if (enableScopeAPI) { + return createFiberFromScope( + type, + pendingProps, + mode, + expirationTime, + key + ); + } } } + var info = ""; + { if ( type === undefined || @@ -21486,23 +22853,22 @@ function createFiberFromTypeAndProps( "it's defined in, or you might have mixed up default and " + "named imports."; } + var ownerName = owner ? getComponentName(owner.type) : null; + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } } - (function() { - { - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (type == null ? type : typeof type) + - "." + - info - ) - ); - } - })(); + + { + 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 + ); + } } } } @@ -21511,15 +22877,15 @@ function createFiberFromTypeAndProps( fiber.elementType = type; fiber.type = resolvedType; fiber.expirationTime = expirationTime; - return fiber; } - function createFiberFromElement(element, mode, expirationTime) { var owner = null; + { owner = element._owner; } + var type = element.type; var key = element.key; var pendingProps = element.props; @@ -21531,19 +22897,19 @@ function createFiberFromElement(element, mode, expirationTime) { mode, expirationTime ); + { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } + return fiber; } - function createFiberFromFragment(elements, mode, expirationTime, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromFundamental( fundamentalComponent, pendingProps, @@ -21558,6 +22924,14 @@ function createFiberFromFundamental( return fiber; } +function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) { + var fiber = createFiber(ScopeComponent, pendingProps, key, mode); + fiber.type = scope; + fiber.elementType = scope; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -21571,76 +22945,74 @@ function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { } } - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - // TODO: The Profiler fiber shouldn't have a type. It has a tag. + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag. + fiber.elementType = REACT_PROFILER_TYPE; fiber.type = REACT_PROFILER_TYPE; fiber.expirationTime = expirationTime; - return fiber; } function createFiberFromSuspense(pendingProps, mode, expirationTime, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - - // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. + fiber.type = REACT_SUSPENSE_TYPE; fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + { // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. fiber.type = REACT_SUSPENSE_LIST_TYPE; } + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromText(content, mode, expirationTime) { var fiber = createFiber(HostText, content, null, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - // TODO: These should not need a type. + var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type. + fiber.elementType = "DELETED"; fiber.type = "DELETED"; return fiber; } - +function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; +} function createFiberFromPortal(portal, mode, expirationTime) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.expirationTime = expirationTime; fiber.stateNode = { containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates + pendingChildren: null, + // Used by persistent updates implementation: portal.implementation }; return fiber; -} +} // Used for stashing WIP properties to replay failed work in DEV. -// Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); - } - - // This is intentionally written as a list of all properties. + } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 @@ -21669,12 +23041,14 @@ function assignFiberPropertiesInDEV(target, source) { target.expirationTime = source.expirationTime; target.childExpirationTime = source.childExpirationTime; target.alternate = source.alternate; + if (enableProfilerTimer) { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } + target._debugID = source._debugID; target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; @@ -21684,19 +23058,6 @@ function assignFiberPropertiesInDEV(target, source) { return target; } -// TODO: This should be lifted into the renderer. - -// The following attributes are only used by interaction tracing builds. -// They enable interactions to be associated with their async work, -// And expose interaction metadata to the React DevTools Profiler plugin. -// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. - -// Exported FiberRoot type includes all properties, -// To avoid requiring potentially error-prone :any casts throughout the project. -// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true). -// The types are defined separately within this file to ensure they stay in sync. -// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.) - function FiberRootNode(containerInfo, tag, hydrate) { this.tag = tag; this.current = null; @@ -21709,31 +23070,129 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.context = null; this.pendingContext = null; this.hydrate = hydrate; - this.firstBatch = null; this.callbackNode = null; - this.callbackExpirationTime = NoWork; + this.callbackPriority = NoPriority; this.firstPendingTime = NoWork; - this.lastPendingTime = NoWork; - this.pingTime = NoWork; + this.firstSuspendedTime = NoWork; + this.lastSuspendedTime = NoWork; + this.nextKnownPendingLevel = NoWork; + this.lastPingedTime = NoWork; + this.lastExpiredTime = NoWork; if (enableSchedulerTracing) { this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } + + if (enableSuspenseCallback) { + this.hydrationCallbacks = null; + } } -function createFiberRoot(containerInfo, tag, hydrate) { +function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate); - // Cyclic construction. This cheats the type system right now because + if (enableSuspenseCallback) { + root.hydrationCallbacks = hydrationCallbacks; + } // Cyclic construction. This cheats the type system right now because // stateNode is any. + var uninitializedFiber = createHostRootFiber(tag); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - return root; } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + return ( + firstSuspendedTime !== NoWork && + firstSuspendedTime >= expirationTime && + lastSuspendedTime <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + + if (firstSuspendedTime < expirationTime) { + root.firstSuspendedTime = expirationTime; + } + + if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) { + root.lastSuspendedTime = expirationTime; + } + + if (expirationTime <= root.lastPingedTime) { + root.lastPingedTime = NoWork; + } + + if (expirationTime <= root.lastExpiredTime) { + root.lastExpiredTime = NoWork; + } +} +function markRootUpdatedAtTime(root, expirationTime) { + // Update the range of pending times + var firstPendingTime = root.firstPendingTime; + + if (expirationTime > firstPendingTime) { + root.firstPendingTime = expirationTime; + } // Update the range of suspended times. Treat everything lower priority or + // equal to this update as unsuspended. + + var firstSuspendedTime = root.firstSuspendedTime; + + if (firstSuspendedTime !== NoWork) { + if (expirationTime >= firstSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (expirationTime >= root.lastSuspendedTime) { + root.lastSuspendedTime = expirationTime + 1; + } // This is a pending level. Check if it's higher priority than the next + // known pending level. + + if (expirationTime > root.nextKnownPendingLevel) { + root.nextKnownPendingLevel = expirationTime; + } + } +} +function markRootFinishedAtTime( + root, + finishedExpirationTime, + remainingExpirationTime +) { + // Update the range of pending times + root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or + // equal to this update as unsuspended. + + if (finishedExpirationTime <= root.lastSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (finishedExpirationTime <= root.firstSuspendedTime) { + // Part of the suspended range is now unsuspended. Narrow the range to + // include everything between the unsuspended time (non-inclusive) and the + // last suspended time. + root.firstSuspendedTime = finishedExpirationTime - 1; + } + + if (finishedExpirationTime <= root.lastPingedTime) { + // Clear the pinged time + root.lastPingedTime = NoWork; + } + + if (finishedExpirationTime <= root.lastExpiredTime) { + // Clear the expired time + root.lastExpiredTime = NoWork; + } +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) { + root.lastExpiredTime = expirationTime; + } +} // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. @@ -21742,14 +23201,10 @@ function createFiberRoot(containerInfo, tag, hydrate) { var ReactFiberInstrumentation = { debugTool: null }; - var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. - -var didWarnAboutNestedUpdates = void 0; -var didWarnAboutFindNodeInStrictMode = void 0; +var didWarnAboutNestedUpdates; +var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; @@ -21766,6 +23221,7 @@ function getContextForSubtree(parentComponent) { if (fiber.tag === ClassComponent) { var Component = fiber.type; + if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } @@ -21774,166 +23230,72 @@ function getContextForSubtree(parentComponent) { return parentContext; } -function scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback -) { - { - if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - 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" - ); +function findHostInstance(component) { + var fiber = get(component); + + if (fiber === undefined) { + if (typeof component.render === "function") { + { + throw Error("Unable to find node on an unmounted component."); + } + } else { + { + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } } } - var update = createUpdate(expirationTime, suspenseConfig); - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = { element: element }; - - callback = callback === undefined ? null : callback; - if (callback !== null) { - !(typeof callback === "function") - ? warningWithoutStack$1( - false, - "render(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callback - ) - : void 0; - update.callback = callback; - } + var hostFiber = findCurrentHostFiber(fiber); - if (revertPassiveEffectsChange) { - flushPassiveEffects(); + if (hostFiber === null) { + return null; } - enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); - return expirationTime; + return hostFiber.stateNode; } -function updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback -) { - // TODO: If this is a nested container, this won't be the root. - var current$$1 = container.current; - +function findHostInstanceWithWarning(component, methodName) { { - if (ReactFiberInstrumentation_1.debugTool) { - if (current$$1.alternate === null) { - ReactFiberInstrumentation_1.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); - } - } - } - - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - return scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback - ); -} + var fiber = get(component); -function findHostInstance(component) { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { + if (fiber === undefined) { + if (typeof component.render === "function") { { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); + throw Error("Unable to find node on an unmounted component."); } - })(); - } else { - (function() { + } else { { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } - })(); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - } else { - (function() { - { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) - ); - } - })(); } } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + if (hostFiber.mode & StrictMode) { var componentName = getComponentName(fiber.type) || "Component"; + if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; + if (fiber.mode & StrictMode) { warningWithoutStack$1( false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which is inside StrictMode. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -21944,10 +23306,9 @@ function findHostInstanceWithWarning(component, methodName) { false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which renders StrictMode children. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -21956,18 +23317,20 @@ function findHostInstanceWithWarning(component, methodName) { } } } + return hostFiber.stateNode; } + return findHostInstance(component); } -function createContainer(containerInfo, tag, hydrate) { - return createFiberRoot(containerInfo, tag, hydrate); +function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) { + return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks); } - function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; var currentTime = requestCurrentTime(); + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -21975,30 +23338,83 @@ function updateContainer(element, container, parentComponent, callback) { warnIfNotScopedWithMatchingAct(current$$1); } } + var suspenseConfig = requestCurrentSuspenseConfig(); var expirationTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - return updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback - ); -} + { + if (ReactFiberInstrumentation_1.debugTool) { + if (current$$1.alternate === null) { + ReactFiberInstrumentation_1.debugTool.onMountContainer(container); + } else if (element === null) { + ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); + } else { + ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); + } + } + } + + var context = getContextForSubtree(parentComponent); + + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + + { + if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + 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" + ); + } + } + + var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property + // being called "element". + + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; + + if (callback !== null) { + !(typeof callback === "function") + ? warningWithoutStack$1( + false, + "render(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callback + ) + : void 0; + update.callback = callback; + } + + enqueueUpdate(current$$1, update); + scheduleWork(current$$1, expirationTime); + return expirationTime; +} function getPublicRootInstance(container) { var containerFiber = container.current; + if (!containerFiber.child) { return null; } + switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); + default: return containerFiber.child.stateNode; } @@ -22011,7 +23427,6 @@ var shouldSuspendImpl = function(fiber) { function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } - var overrideHookState = null; var overrideProps = null; var scheduleUpdate = null; @@ -22022,62 +23437,53 @@ var setSuspenseHandler = null; if (idx >= path.length) { return value; } + var key = path[idx]; - var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); - // $FlowFixMe number or string is fine here + var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); // $FlowFixMe number or string is fine here + updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); return updated; }; var copyWithSet = function(obj, path, value) { return copyWithSetImpl(obj, path, 0, value); - }; + }; // Support DevTools editable values for useState and useReducer. - // Support DevTools editable values for useState and useReducer. overrideHookState = function(fiber, id, path, value) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; + while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } - if (currentHook !== null) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } + if (currentHook !== null) { var newState = copyWithSet(currentHook.memoizedState, path, value); currentHook.memoizedState = newState; - currentHook.baseState = newState; - - // We aren't actually adding an update to the queue, + currentHook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); + fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); scheduleWork(fiber, Sync); } - }; + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } + scheduleWork(fiber, Sync); }; scheduleUpdate = function(fiber) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } scheduleWork(fiber, Sync); }; @@ -22089,7 +23495,6 @@ var setSuspenseHandler = null; function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals( Object.assign({}, devToolsConfig, { overrideHookState: overrideHookState, @@ -22099,9 +23504,11 @@ function injectIntoDevTools(devToolsConfig) { currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + return hostFiber.stateNode; }, findFiberByHostInstance: function(instance) { @@ -22109,9 +23516,9 @@ function injectIntoDevTools(devToolsConfig) { // Might not be implemented by the renderer. return null; } + return findFiberByHostInstance(instance); }, - // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh, scheduleRefresh: scheduleRefresh, @@ -22130,13 +23537,11 @@ function injectIntoDevTools(devToolsConfig) { function createPortal( children, - containerInfo, - // TODO: figure out the API for cross-renderer implementation. + containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation ) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, @@ -22147,404 +23552,31 @@ function createPortal( }; } -// TODO: this is special because it gets imported during build. - -var ReactVersion = "16.8.6"; - -// Modules provided by RN: -var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { - /** - * `NativeMethodsMixin` provides methods to access the underlying native - * component directly. This can be useful in cases when you want to focus - * a view or measure its on-screen dimensions, for example. - * - * The methods described here are available on most of the default components - * provided by React Native. Note, however, that they are *not* available on - * composite components that aren't directly backed by a native view. This will - * generally include most components that you define in your own app. For more - * information, see [Direct - * Manipulation](docs/direct-manipulation.html). - * - * Note the Flow $Exact<> syntax is required to support mixins. - * React createClass mixins can only be used with exact types. - */ - var NativeMethodsMixin = { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measure( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measureInWindow( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeNode`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * - * As always, to obtain a native node handle for a component, you can use - * `findNodeHandle(component)`. - */ - measureLayout: function( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: measureLayout on components using NativeMethodsMixin " + - "or ReactNative.NativeComponent is not currently supported in Fabric. " + - "measureLayout must be called on a native ref. Consider using forwardRef." - ); - return; - } else { - var relativeNode = void 0; - - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } - - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." - ); - - return; - } - - ReactNativePrivateInterface.UIManager.measureLayout( - findNodeHandle(this), - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - } - }, - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](docs/direct-manipulation.html)). - */ - setNativeProps: function(nativeProps) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than findNodeHandle() because - // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - return; - } - - var nativeTag = - maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; - var viewConfig = - maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - - { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = create(nativeProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( - nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } - }, - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus: function() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }, - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur: function() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - } - }; - - { - // hide this from Flow since we can't define these properties outside of - // true without actually implementing them (setting them to undefined - // isn't allowed by ReactClass) - var NativeMethodsMixin_DEV = NativeMethodsMixin; - (function() { - if ( - !( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps - ) - ) { - throw ReactError(Error("Do not override existing functions.")); - } - })(); - // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, - // Once these lifecycles have been remove from the reconciler. - NativeMethodsMixin_DEV.componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { - throwOnStylesProp(this, newProps); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( - newProps - ) { - throwOnStylesProp(this, newProps); - }; - - // React may warn about cWM/cWRP/cWU methods being deprecated. - // Add a flag to suppress these warnings for this special case. - // TODO (bvaughn) Remove this flag once the above methods have been removed. - NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; - NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; - } - - return NativeMethodsMixin; -}; - -function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); -} - -// Modules provided by RN: -var ReactNativeComponent = function(findNodeHandle, findHostInstance) { - /** - * Superclass that provides methods to access the underlying native component. - * This can be useful when you want to focus a view or measure its dimensions. - * - * Methods implemented by this class are available on most default components - * provided by React Native. However, they are *not* available on composite - * components that are not directly backed by a native view. For more - * information, see [Direct Manipulation](docs/direct-manipulation.html). - * - * @abstract - */ - var ReactNativeComponent = (function(_React$Component) { - _inherits(ReactNativeComponent, _React$Component); - - function ReactNativeComponent() { - _classCallCheck$1(this, ReactNativeComponent); - - return _possibleConstructorReturn( - this, - _React$Component.apply(this, arguments) - ); - } - - /** - * Removes focus. This is the opposite of `focus()`. - */ - - /** - * Due to bugs in Flow's handling of React.createClass, some fields already - * declared in the base class need to be redeclared below. - */ - ReactNativeComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - }; - - /** - * Requests focus. The exact behavior depends on the platform and view. - */ - - ReactNativeComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }; - +// TODO: this is special because it gets imported during build. + +var ReactVersion = "16.10.2"; + +var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { + /** + * `NativeMethodsMixin` provides methods to access the underlying native + * component directly. This can be useful in cases when you want to focus + * a view or measure its on-screen dimensions, for example. + * + * The methods described here are available on most of the default components + * provided by React Native. Note, however, that they are *not* available on + * composite components that aren't directly backed by a native view. This will + * generally include most components that you define in your own app. For more + * information, see [Direct + * Manipulation](docs/direct-manipulation.html). + * + * Note the Flow $Exact<> syntax is required to support mixins. + * React createClass mixins can only be used with exact types. + */ + var NativeMethodsMixin = { /** - * Measures the on-screen location and dimensions. If successful, the callback - * will be called asynchronously with the following arguments: + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: * * - x * - y @@ -22553,24 +23585,22 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * - pageX * - pageY * - * These values are not available until after natives rendering completes. If - * you need the measurements as soon as possible, consider using the - * [`onLayout` prop](docs/view.html#onlayout) instead. + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. */ - - ReactNativeComponent.prototype.measure = function measure(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measure: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22589,37 +23619,34 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Measures the on-screen location and dimensions. Even if the React Native - * root view is embedded within another native view, this method will give you - * the absolute coordinates measured from the window. If successful, the - * callback will be called asynchronously with the following arguments: + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: * * - x * - y * - width * - height * - * These values are not available until after natives rendering completes. + * Note that these measurements are not available until after the rendering + * has been completed in native. */ - - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measureInWindow: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22638,32 +23665,32 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Similar to [`measure()`](#measure), but the resulting location will be - * relative to the supplied ancestor's location. + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeNode`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. * - * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + * As always, to obtain a native node handle for a component, you can use + * `findNodeHandle(component)`. */ - - ReactNativeComponent.prototype.measureLayout = function measureLayout( + measureLayout: function( relativeToNativeNode, onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + onFail + ) /* currently unused */ + { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22677,7 +23704,7 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { ); return; } else { - var relativeNode = void 0; + var relativeNode; if (typeof relativeToNativeNode === "number") { // Already a node handle @@ -22691,7 +23718,6 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { false, "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." ); - return; } @@ -22702,7 +23728,7 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); } - }; + }, /** * This function sends props straight to native. They will not participate in @@ -22710,27 +23736,22 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ - - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + setNativeProps: function(nativeProps) { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // Use findNodeHandle() rather than findNodeHandle() because // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22748,11 +23769,14 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { var viewConfig = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - var updatePayload = create(nativeProps, viewConfig.validAttributes); + { + warnForStyleProps(nativeProps, viewConfig.validAttributes); + } - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( nativeTag, @@ -22760,23 +23784,339 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { updatePayload ); } + }, + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus: function() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }, + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur: function() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + } + }; + + { + // hide this from Flow since we can't define these properties outside of + // true without actually implementing them (setting them to undefined + // isn't allowed by ReactClass) + var NativeMethodsMixin_DEV = NativeMethodsMixin; + + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw Error("Do not override existing functions."); + } // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, + // Once these lifecycles have been remove from the reconciler. + + NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp(this, this.props); + }; + + NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp(this, newProps); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { + throwOnStylesProp(this, this.props); }; - return ReactNativeComponent; - })(React.Component); + NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( + newProps + ) { + throwOnStylesProp(this, newProps); + }; // React may warn about cWM/cWRP/cWU methods being deprecated. + // Add a flag to suppress these warnings for this special case. + // TODO (bvaughn) Remove this flag once the above methods have been removed. + + NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; + NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; + } + + return NativeMethodsMixin; +}; + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} + +var ReactNativeComponent = function(findNodeHandle, findHostInstance) { + /** + * Superclass that provides methods to access the underlying native component. + * This can be useful when you want to focus a view or measure its dimensions. + * + * Methods implemented by this class are available on most default components + * provided by React Native. However, they are *not* available on composite + * components that are not directly backed by a native view. For more + * information, see [Direct Manipulation](docs/direct-manipulation.html). + * + * @abstract + */ + var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); + + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } + + var _proto = ReactNativeComponent.prototype; + + /** + * Due to bugs in Flow's handling of React.createClass, some fields already + * declared in the base class need to be redeclared below. + */ + + /** + * Removes focus. This is the opposite of `focus()`. + */ + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + }; + /** + * Requests focus. The exact behavior depends on the platform and view. + */ + + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }; + /** + * Measures the on-screen location and dimensions. If successful, the callback + * will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * These values are not available until after natives rendering completes. If + * you need the measurements as soon as possible, consider using the + * [`onLayout` prop](docs/view.html#onlayout) instead. + */ + + _proto.measure = function measure(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Measures the on-screen location and dimensions. Even if the React Native + * root view is embedded within another native view, this method will give you + * the absolute coordinates measured from the window. If successful, the + * callback will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * + * These values are not available until after natives rendering completes. + */ + + _proto.measureInWindow = function measureInWindow(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Similar to [`measure()`](#measure), but the resulting location will be + * relative to the supplied ancestor's location. + * + * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + */ + + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: measureLayout on components using NativeMethodsMixin " + + "or ReactNative.NativeComponent is not currently supported in Fabric. " + + "measureLayout must be called on a native ref. Consider using forwardRef." + ); + return; + } else { + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } + + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } + + ReactNativePrivateInterface.UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } + }; + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](docs/direct-manipulation.html)). + */ + + _proto.setNativeProps = function setNativeProps(nativeProps) { + // Class components don't have viewConfig -> validateAttributes. + // Nor does it make sense to set native props on a non-native component. + // Instead, find the nearest host component and set props on it. + // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // We want the instance/wrapper (not the native tag). + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + var nativeTag = + maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; + var viewConfig = + maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } + }; - // eslint-disable-next-line no-unused-expressions + return ReactNativeComponent; + })(React.Component); // eslint-disable-next-line no-unused-expressions return ReactNativeComponent; }; -// Module provided by RN: var emptyObject$2 = {}; + { Object.freeze(emptyObject$2); } -var getInspectorDataForViewTag = void 0; +var getInspectorDataForViewTag; { var traverseOwnerTreeUp = function(hierarchy, instance) { @@ -22800,30 +24140,36 @@ var getInspectorDataForViewTag = void 0; return instance; } } + return hierarchy[0]; }; var getHostProps = function(fiber) { var host = findCurrentHostFiber(fiber); + if (host) { return host.memoizedProps || emptyObject$2; } + return emptyObject$2; }; var getHostNode = function(fiber, findNodeHandle) { - var hostNode = void 0; - // look for children first for the hostNode + var hostNode; // look for children first for the hostNode // as composite fibers do not have a hostNode + while (fiber) { if (fiber.stateNode !== null && fiber.tag === HostComponent) { hostNode = findNodeHandle(fiber.stateNode); } + if (hostNode) { return hostNode; } + fiber = fiber.child; } + return null; }; @@ -22848,9 +24194,8 @@ var getInspectorDataForViewTag = void 0; }; getInspectorDataForViewTag = function(viewTag) { - var closestInstance = getInstanceFromTag(viewTag); + var closestInstance = getInstanceFromTag(viewTag); // Handle case where user clicks outside of ReactNative - // Handle case where user clicks outside of ReactNative if (!closestInstance) { return { hierarchy: [], @@ -22867,7 +24212,6 @@ var getInspectorDataForViewTag = void 0; var props = getHostProps(instance); var source = instance._debugSource; var selection = fiberHierarchy.indexOf(instance); - return { hierarchy: hierarchy, props: props, @@ -22877,13 +24221,12 @@ var getInspectorDataForViewTag = void 0; }; } -// TODO: direct imports like some-package/src/* are bad. Fix me. -// Module provided by RN: var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function findNodeHandle(componentOrHandle) { { var owner = ReactCurrentOwner.current; + if (owner !== null && owner.stateNode !== null) { !owner.stateNode._warnedAboutRefsInRender ? warningWithoutStack$1( @@ -22896,24 +24239,29 @@ function findNodeHandle(componentOrHandle) { getComponentName(owner.type) || "A component" ) : void 0; - owner.stateNode._warnedAboutRefsInRender = true; } } + if (componentOrHandle == null) { return null; } + if (typeof componentOrHandle === "number") { // Already a node handle return componentOrHandle; } + if (componentOrHandle._nativeTag) { return componentOrHandle._nativeTag; } + if (componentOrHandle.canonical && componentOrHandle.canonical._nativeTag) { return componentOrHandle.canonical._nativeTag; } - var hostInstance = void 0; + + var hostInstance; + { hostInstance = findHostInstanceWithWarning( componentOrHandle, @@ -22924,10 +24272,12 @@ function findNodeHandle(componentOrHandle) { if (hostInstance == null) { return hostInstance; } + if (hostInstance.canonical) { // Fabric return hostInstance.canonical._nativeTag; } + return hostInstance._nativeTag; } @@ -22940,19 +24290,18 @@ setBatchingImplementation( function computeComponentStackForErrorReporting(reactTag) { var fiber = getInstanceFromTag(reactTag); + if (!fiber) { return ""; } + return getStackByFiberInDevAndProd(fiber); } var roots = new Map(); - var ReactNativeRenderer = { NativeComponent: ReactNativeComponent(findNodeHandle, findHostInstance), - findNodeHandle: findNodeHandle, - dispatchCommand: function(handle, command, args) { if (handle._nativeTag == null) { !(handle._nativeTag != null) @@ -22977,15 +24326,16 @@ var ReactNativeRenderer = { if (!root) { // TODO (bvaughn): If we decide to keep the wrapper component, // We could create a wrapper for containerTag as well to reduce special casing. - root = createContainer(containerTag, LegacyRoot, false); + root = createContainer(containerTag, LegacyRoot, false, null); roots.set(containerTag, root); } - updateContainer(element, root, null, callback); + updateContainer(element, root, null, callback); return getPublicRootInstance(root); }, unmountComponentAtNode: function(containerTag) { var root = roots.get(containerTag); + if (root) { // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? updateContainer(null, root, null, function() { @@ -22994,27 +24344,22 @@ var ReactNativeRenderer = { } }, unmountComponentAtNodeAndRemoveContainer: function(containerTag) { - ReactNativeRenderer.unmountComponentAtNode(containerTag); + ReactNativeRenderer.unmountComponentAtNode(containerTag); // Call back into native to remove all of the subviews from this container - // Call back into native to remove all of the subviews from this container ReactNativePrivateInterface.UIManager.removeRootView(containerTag); }, createPortal: function(children, containerTag) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - return createPortal(children, containerTag, null, key); }, - unstable_batchedUpdates: batchedUpdates, - __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // Used as a mixin in many createClass-based components NativeMethodsMixin: NativeMethodsMixin(findNodeHandle, findHostInstance), computeComponentStackForErrorReporting: computeComponentStackForErrorReporting } }; - injectIntoDevTools({ findFiberByHostInstance: getInstanceFromTag, getInspectorDataForViewTag: getInspectorDataForViewTag, @@ -23032,6 +24377,7 @@ var ReactNativeRenderer$3 = // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. + var reactNativeRenderer = ReactNativeRenderer$3.default || ReactNativeRenderer$3; diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js b/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js index aeba7c7dcdf8a8..ddde5cc617dad8 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js @@ -23,15 +23,6 @@ var checkPropTypes = require("prop-types/checkPropTypes"); var Scheduler = require("scheduler"); var tracing = require("scheduler/tracing"); -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. - -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} - /** * Use invariant() to assert state which your program assumes to be true. * @@ -47,76 +38,69 @@ function ReactError(error) { * Injectable ordering of event plugins. */ var eventPluginOrder = null; - /** * Injectable mapping from names to event plugin modules. */ -var namesToPlugins = {}; +var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ + function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } + for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); - (function() { - if (!(pluginIndex > -1)) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) - ); - } - })(); + + if (!(pluginIndex > -1)) { + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + if (plugins[pluginIndex]) { continue; } - (function() { - if (!pluginModule.extractEvents) { - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) - ); - } - })(); + + if (!pluginModule.extractEvents) { + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + } + plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { - (function() { - if ( - !publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ) - ) { - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) - ); - } - })(); + if ( + !publishEventForPlugin( + publishedEvents[eventName], + pluginModule, + eventName + ) + ) { + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } } } } - /** * Publishes an event so that it can be dispatched by the supplied plugin. * @@ -125,21 +109,19 @@ function recomputePluginOrdering() { * @return {boolean} True if the event was successfully published. * @private */ + function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - (function() { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName + - "`." - ) - ); - } - })(); - eventNameDispatchConfigs[eventName] = dispatchConfig; + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." + ); + } + eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { @@ -151,6 +133,7 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); } } + return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( @@ -160,9 +143,9 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { ); return true; } + return false; } - /** * Publishes a registration name that is used to identify dispatched events. * @@ -170,18 +153,16 @@ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { * @param {object} PluginModule Plugin publishing the event. * @private */ + function publishRegistrationName(registrationName, pluginModule, eventName) { - (function() { - if (!!registrationNameModules[registrationName]) { - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) - ); - } - })(); + if (!!registrationNameModules[registrationName]) { + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + registrationNameModules[registrationName] = pluginModule; registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; @@ -190,7 +171,6 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { var lowerCasedName = registrationName.toLowerCase(); } } - /** * Registers plugins so that they can extract and dispatch events. * @@ -200,23 +180,23 @@ function publishRegistrationName(registrationName, pluginModule, eventName) { /** * Ordered list of injected plugins. */ -var plugins = []; +var plugins = []; /** * Mapping from event name to dispatch config */ -var eventNameDispatchConfigs = {}; +var eventNameDispatchConfigs = {}; /** * Mapping from registration name to plugin module */ -var registrationNameModules = {}; +var registrationNameModules = {}; /** * Mapping from registration name to event name */ -var registrationNameDependencies = {}; +var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available @@ -235,21 +215,17 @@ var registrationNameDependencies = {}; * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ + function injectEventPluginOrder(injectedEventPluginOrder) { - (function() { - if (!!eventPluginOrder) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) - ); - } - })(); - // Clone the ordering so it cannot be dynamically mutated. + if (!!eventPluginOrder) { + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." + ); + } // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); } - /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. @@ -260,32 +236,34 @@ function injectEventPluginOrder(injectedEventPluginOrder) { * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ + function injectEventPluginsByName(injectedNamesToPlugins) { var isOrderingDirty = false; + for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } + var pluginModule = injectedNamesToPlugins[pluginName]; + if ( !namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule ) { - (function() { - if (!!namesToPlugins[pluginName]) { - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) - ); - } - })(); + if (!!namesToPlugins[pluginName]) { + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } + if (isOrderingDirty) { recomputePluginOrdering(); } @@ -303,6 +281,7 @@ var invokeGuardedCallbackImpl = function( f ) { var funcArgs = Array.prototype.slice.call(arguments, 3); + try { func.apply(context, funcArgs); } catch (error) { @@ -329,7 +308,6 @@ var invokeGuardedCallbackImpl = function( // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if ( @@ -355,52 +333,45 @@ var invokeGuardedCallbackImpl = function( // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebookincubator/create-react-app/issues/3482 // So we preemptively throw with a better message instead. - (function() { - if (!(typeof document !== "undefined")) { - throw ReactError( - Error( - "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." - ) - ); - } - })(); - var evt = document.createEvent("Event"); + if (!(typeof document !== "undefined")) { + 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." + ); + } - // Keeps track of whether the user-provided callback threw an error. We + var evt = document.createEvent("Event"); // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. - var didError = true; - // Keeps track of the value of window.event so that we can reset it + var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. - var windowEvent = window.event; - // Keeps track of the descriptor of window.event to restore it after event + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 + var windowEventDescriptor = Object.getOwnPropertyDescriptor( window, "event" - ); - - // Create an event handler for our fake event. We will synchronously + ); // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - - // We check for window.hasOwnProperty('event') to prevent the + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. + if ( typeof window.event !== "undefined" && window.hasOwnProperty("event") @@ -410,9 +381,7 @@ var invokeGuardedCallbackImpl = function( func.apply(context, funcArgs); didError = false; - } - - // Create a global error event handler. We use this to capture the value + } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of @@ -423,17 +392,20 @@ var invokeGuardedCallbackImpl = function( // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. + + var error; // Use this to track whether the error event is ever called. + var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } + if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. @@ -446,17 +418,14 @@ var invokeGuardedCallbackImpl = function( } } } - } + } // Create a fake event type. - // Create a fake event type. - var evtType = "react-" + (name ? name : "invokeguardedcallback"); + var evtType = "react-" + (name ? name : "invokeguardedcallback"); // Attach our event handlers - // Attach our event handlers window.addEventListener("error", handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); - - // Synchronously dispatch our fake event. If the user-provided function + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); @@ -484,10 +453,10 @@ var invokeGuardedCallbackImpl = function( "See https://fb.me/react-crossorigin-error for more information." ); } + this.onError(error); - } + } // Remove our event listeners - // Remove our event listeners window.removeEventListener("error", handleWindowError); }; @@ -497,21 +466,17 @@ var invokeGuardedCallbackImpl = function( var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// Used by Fiber to simulate a try-catch. var hasError = false; -var caughtError = null; +var caughtError = null; // Used by event system to capture/rethrow the first error. -// Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; - var reporter = { onError: function(error) { hasError = true; caughtError = error; } }; - /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. @@ -525,12 +490,12 @@ var reporter = { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } - /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. @@ -541,6 +506,7 @@ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallbackAndCatchFirstError( name, func, @@ -553,19 +519,21 @@ function invokeGuardedCallbackAndCatchFirstError( f ) { invokeGuardedCallback.apply(this, arguments); + if (hasError) { var error = clearCaughtError(); + if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } - /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ + function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; @@ -574,11 +542,9 @@ function rethrowCaughtError() { throw error; } } - function hasCaughtError() { return hasError; } - function clearCaughtError() { if (hasError) { var error = caughtError; @@ -586,15 +552,11 @@ function clearCaughtError() { caughtError = null; return error; } else { - (function() { - { - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -604,14 +566,13 @@ function clearCaughtError() { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - var warningWithoutStack = function() {}; { warningWithoutStack = function(condition, format) { for ( var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), + args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++ @@ -625,25 +586,28 @@ var warningWithoutStack = function() {}; "message argument" ); } + if (args.length > 8) { // Check before the condition to catch violations early. throw new Error( "warningWithoutStack() currently supports at most 8 arguments." ); } + if (condition) { return; } + if (typeof console !== "undefined") { var argsWithFormat = args.map(function(item) { return "" + item; }); - argsWithFormat.unshift("Warning: " + format); - - // We intentionally don't use spread (or .apply) directly because it + argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 + Function.prototype.apply.call(console.error, console, argsWithFormat); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -664,7 +628,6 @@ var warningWithoutStack$1 = warningWithoutStack; var getFiberCurrentPropsFromNode = null; var getInstanceFromNode = null; var getNodeFromInstance = null; - function setComponentTree( getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, @@ -673,6 +636,7 @@ function setComponentTree( getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode = getInstanceFromNodeImpl; getNodeFromInstance = getNodeFromInstanceImpl; + { !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1( @@ -683,70 +647,69 @@ function setComponentTree( : void 0; } } +var validateEventDispatches; -var validateEventDispatches = void 0; { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, "EventPluginUtils: Invalid `event`.") : void 0; }; } - /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ + function executeDispatch(event, listener, inst) { var type = event.type || "unknown-event"; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } - /** * Standard/simple iteration through an event's collected dispatches. */ + function executeDispatchesInOrder(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, dispatchListeners, dispatchInstances); } + event._dispatchListeners = null; event._dispatchInstances = null; } - /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. @@ -754,18 +717,21 @@ function executeDispatchesInOrder(event) { * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ + function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } @@ -775,19 +741,19 @@ function executeDispatchesInOrderStopAtTrueImpl(event) { return dispatchInstances; } } + return null; } - /** * @see executeDispatchesInOrderStopAtTrueImpl */ + function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } - /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make @@ -797,17 +763,19 @@ function executeDispatchesInOrderStopAtTrue(event) { * * @return {*} The return value of executing the single dispatch. */ + function executeDirectDispatch(event) { { validateEventDispatches(event); } + var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - (function() { - if (!!Array.isArray(dispatchListener)) { - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); - } - })(); + + if (!!Array.isArray(dispatchListener)) { + throw Error("executeDirectDispatch(...): Invalid `event`."); + } + event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -817,11 +785,11 @@ function executeDirectDispatch(event) { event._dispatchInstances = null; return res; } - /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ + function hasDispatches(event) { return !!event._dispatchListeners; } @@ -840,27 +808,23 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } + current.push(next); return current; } @@ -894,14 +858,15 @@ function forEachAccumulated(arr, cb, scope) { * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ -var eventQueue = null; +var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ + var executeDispatchesAndRelease = function(event) { if (event) { executeDispatchesInOrder(event); @@ -911,6 +876,7 @@ var executeDispatchesAndRelease = function(event) { } } }; + var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(e); }; @@ -918,10 +884,9 @@ var executeDispatchesAndReleaseTopLevel = function(e) { function runEventsInBatch(events) { if (events !== null) { eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more + } // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. + var processingEventQueue = eventQueue; eventQueue = null; @@ -930,16 +895,13 @@ function runEventsInBatch(events) { } forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - (function() { - if (!!eventQueue) { - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) - ); - } - })(); - // This would be a good time to rethrow if any of the event handlers threw. + + if (!!eventQueue) { + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + } // This would be a good time to rethrow if any of the event handlers threw. + rethrowCaughtError(); } @@ -965,11 +927,11 @@ function shouldPreventMouseEvent(name, type, props) { case "onMouseUp": case "onMouseUpCapture": return !!(props.disabled && isInteractive(type)); + default: return false; } } - /** * This is a unified interface for event plugins to be installed and configured. * @@ -996,6 +958,7 @@ function shouldPreventMouseEvent(name, type, props) { /** * Methods for injecting dependencies. */ + var injection = { /** * @param {array} InjectedEventPluginOrder @@ -1008,47 +971,48 @@ var injection = { */ injectEventPluginsByName: injectEventPluginsByName }; - /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ -function getListener(inst, registrationName) { - var listener = void 0; - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not +function getListener(inst, registrationName) { + var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon + var stateNode = inst.stateNode; + if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } + var props = getFiberCurrentPropsFromNode(stateNode); + if (!props) { // Work in progress. return null; } + listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - (function() { - if (!(!listener || typeof listener === "function")) { - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) - ); - } - })(); + + if (!(!listener || typeof listener === "function")) { + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + return listener; } - /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. @@ -1056,28 +1020,35 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ + function extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = null; + for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; + if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); + if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } + return events; } @@ -1085,13 +1056,15 @@ function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ); runEventsInBatch(events); } @@ -1099,8 +1072,11 @@ function runExtractedPluginEventsInBatch( var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + var HostComponent = 5; var HostText = 6; var Fragment = 7; @@ -1114,101 +1090,111 @@ var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; -var DehydratedSuspenseComponent = 18; +var DehydratedFragment = 18; var SuspenseListComponent = 19; var FundamentalComponent = 20; +var ScopeComponent = 21; function getParent(inst) { do { - inst = inst.return; - // TODO: If this is a HostRoot we might want to bail out. + inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); + if (inst) { return inst; } + return null; } - /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ + function getLowestCommonAncestor(instA, instB) { var depthA = 0; + for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } + var depthB = 0; + for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; - } + } // If A is deeper, crawl up. - // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; - } + } // If B is deeper, crawl up. - // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; - } + } // Walk in lockstep until we find a match. - // Walk in lockstep until we find a match. var depth = depthA; + while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } + instA = getParent(instA); instB = getParent(instB); } + return null; } - /** * Return if A is an ancestor of B. */ + function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } + instB = getParent(instB); } + return false; } - /** * Return the parent instance of the passed-in instance. */ + function getParentInstance(inst) { return getParent(inst); } - /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ + function traverseTwoPhase(inst, fn, arg) { var path = []; + while (inst) { path.push(inst); inst = getParent(inst); } - var i = void 0; + + var i; + for (i = path.length; i-- > 0; ) { fn(path[i], "captured", arg); } + for (i = 0; i < path.length; i++) { fn(path[i], "bubbled", arg); } } - /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. @@ -1226,7 +1212,6 @@ function listenerAtPhase(inst, event, propagationPhase) { event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } - /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which @@ -1243,13 +1228,16 @@ function listenerAtPhase(inst, event, propagationPhase) { * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ + function accumulateDirectionalDispatches(inst, phase, event) { { !inst ? warningWithoutStack$1(false, "Dispatching inst must not be null") : void 0; } + var listener = listenerAtPhase(inst, event, phase); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1258,7 +1246,6 @@ function accumulateDirectionalDispatches(inst, phase, event) { event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } - /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through @@ -1266,15 +1253,16 @@ function accumulateDirectionalDispatches(inst, phase, event) { * single traversal for the entire collection of events because each event may * have a different target. */ + function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } - /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ + function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; @@ -1282,16 +1270,17 @@ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } - /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ + function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); + if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, @@ -1301,12 +1290,12 @@ function accumulateDispatches(inst, ignoredDirection, event) { } } } - /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ + function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); @@ -1316,7 +1305,6 @@ function accumulateDirectDispatchesSingle(event) { function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } - function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } @@ -1326,13 +1314,12 @@ function accumulateDirectDispatches(events) { } /* eslint valid-typeof: 0 */ - var EVENT_POOL_SIZE = 10; - /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ + var EventInterface = { type: null, target: null, @@ -1357,7 +1344,6 @@ function functionThatReturnsTrue() { function functionThatReturnsFalse() { return false; } - /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. @@ -1376,6 +1362,7 @@ function functionThatReturnsFalse() { * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ + function SyntheticEvent( dispatchConfig, targetInst, @@ -1394,16 +1381,19 @@ function SyntheticEvent( this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; - var Interface = this.constructor.Interface; + for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } + { delete this[propName]; // this has a getter/setter for warnings } + var normalize = Interface[propName]; + if (normalize) { this[propName] = normalize(nativeEvent); } else { @@ -1419,11 +1409,13 @@ function SyntheticEvent( nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } + this.isPropagationStopped = functionThatReturnsFalse; return this; } @@ -1432,6 +1424,7 @@ Object.assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; + if (!event) { return; } @@ -1441,11 +1434,12 @@ Object.assign(SyntheticEvent.prototype, { } else if (typeof event.returnValue !== "unknown") { event.returnValue = false; } + this.isDefaultPrevented = functionThatReturnsTrue; }, - stopPropagation: function() { var event = this.nativeEvent; + if (!event) { return; } @@ -1485,6 +1479,7 @@ Object.assign(SyntheticEvent.prototype, { */ destructor: function() { var Interface = this.constructor.Interface; + for (var propName in Interface) { { Object.defineProperty( @@ -1494,6 +1489,7 @@ Object.assign(SyntheticEvent.prototype, { ); } } + this.dispatchConfig = null; this._targetInst = null; this.nativeEvent = null; @@ -1501,6 +1497,7 @@ Object.assign(SyntheticEvent.prototype, { this.isPropagationStopped = functionThatReturnsFalse; this._dispatchListeners = null; this._dispatchInstances = null; + { Object.defineProperty( this, @@ -1536,35 +1533,33 @@ Object.assign(SyntheticEvent.prototype, { } } }); - SyntheticEvent.Interface = EventInterface; - /** * Helper to reduce boilerplate when creating subclasses. */ + SyntheticEvent.extend = function(Interface) { var Super = this; var E = function() {}; + E.prototype = Super.prototype; var prototype = new E(); function Class() { return Super.apply(this, arguments); } + Object.assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; - Class.Interface = Object.assign({}, Super.Interface, Interface); Class.extend = Super.extend; addEventPoolingTo(Class); - return Class; }; addEventPoolingTo(SyntheticEvent); - /** * Helper to nullify syntheticEvent instance properties when destructing * @@ -1572,6 +1567,7 @@ addEventPoolingTo(SyntheticEvent); * @param {?object} getVal * @return {object} defineProperty object */ + function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === "function"; return { @@ -1614,6 +1610,7 @@ function getPooledWarningPropertyDefinition(propName, getVal) { function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; + if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call( @@ -1625,6 +1622,7 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { ); return instance; } + return new EventConstructor( dispatchConfig, targetInst, @@ -1635,16 +1633,15 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - (function() { - if (!(event instanceof EventConstructor)) { - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) - ); - } - })(); + + if (!(event instanceof EventConstructor)) { + throw Error( + "Trying to release an event instance into a pool of a different type." + ); + } + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } @@ -1661,6 +1658,7 @@ function addEventPoolingTo(EventConstructor) { * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ + var ResponderSyntheticEvent = SyntheticEvent.extend({ touchHistory: function(nativeEvent) { return null; // Actually doesn't even look at the native event. @@ -1673,19 +1671,15 @@ var TOP_TOUCH_END = "topTouchEnd"; var TOP_TOUCH_CANCEL = "topTouchCancel"; var TOP_SCROLL = "topScroll"; var TOP_SELECTION_CHANGE = "topSelectionChange"; - function isStartish(topLevelType) { return topLevelType === TOP_TOUCH_START; } - function isMoveish(topLevelType) { return topLevelType === TOP_TOUCH_MOVE; } - function isEndish(topLevelType) { return topLevelType === TOP_TOUCH_END || topLevelType === TOP_TOUCH_CANCEL; } - var startDependencies = [TOP_TOUCH_START]; var moveDependencies = [TOP_TOUCH_MOVE]; var endDependencies = [TOP_TOUCH_CANCEL, TOP_TOUCH_END]; @@ -1714,11 +1708,11 @@ function timestampForTouch(touch) { // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } - /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ + function createTouchRecord(touch) { return { touchActive: true, @@ -1750,11 +1744,10 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - (function() { - if (!(identifier != null)) { - throw ReactError(Error("Touch object is missing identifier.")); - } - })(); + if (!(identifier != null)) { + throw Error("Touch object is missing identifier."); + } + { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1766,22 +1759,26 @@ function getTouchIdentifier(_ref) { ) : void 0; } + return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; + if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } + touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1803,6 +1800,7 @@ function recordTouchMove(touch) { function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; + if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; @@ -1833,9 +1831,11 @@ function printTouch(touch) { function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); + if (touchBank.length > MAX_TOUCH_BANK) { printed += " (original size: " + touchBank.length + ")"; } + return printed; } @@ -1846,6 +1846,7 @@ var ResponderTouchHistoryStore = { } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; @@ -1853,14 +1854,17 @@ var ResponderTouchHistoryStore = { } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; + if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; + if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } + { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; !(activeRecord != null && activeRecord.touchActive) @@ -1870,7 +1874,6 @@ var ResponderTouchHistoryStore = { } } }, - touchHistory: touchHistory }; @@ -1881,23 +1884,19 @@ var ResponderTouchHistoryStore = { * * @return {*|array<*>} An accumulation of items. */ + function accumulate(current, next) { - (function() { - if (!(next != null)) { - throw ReactError( - Error( - "accumulate(...): Accumulated items must not be null or undefined." - ) - ); - } - })(); + if (!(next != null)) { + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." + ); + } if (current == null) { return next; - } - - // Both are not empty. Warning: Never call x.concat(y) when you are not + } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). + if (Array.isArray(current)) { return current.concat(next); } @@ -1913,17 +1912,19 @@ function accumulate(current, next) { * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ -var responderInst = null; +var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ + var trackedTouchCount = 0; var changeResponder = function(nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; + if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange( oldResponderInst, @@ -2026,7 +2027,6 @@ var eventTypes = { dependencies: [] } }; - /** * * Responder System: @@ -2229,17 +2229,15 @@ function setResponderAndExtractTransfer( ? eventTypes.moveShouldSetResponder : topLevelType === TOP_SELECTION_CHANGE ? eventTypes.selectionChangeShouldSetResponder - : eventTypes.scrollShouldSetResponder; + : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. - // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst - : getLowestCommonAncestor(responderInst, targetInst); - - // When capturing/bubbling the "shouldSet" event, we want to skip the target + : getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. + var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent.getPooled( shouldSetEventType, @@ -2248,12 +2246,15 @@ function setResponderAndExtractTransfer( nativeEventTarget ); shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; + if (skipOverBubbleShouldSetFrom) { accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { accumulateTwoPhaseDispatches(shouldSetEvent); } + var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent); + if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } @@ -2261,7 +2262,8 @@ function setResponderAndExtractTransfer( if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } - var extracted = void 0; + + var extracted; var grantEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, wantsResponderInst, @@ -2269,9 +2271,9 @@ function setResponderAndExtractTransfer( nativeEventTarget ); grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory; - accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch(grantEvent) === true; + if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent.getPooled( eventTypes.responderTerminationRequest, @@ -2285,6 +2287,7 @@ function setResponderAndExtractTransfer( var shouldSwitch = !hasDispatches(terminationRequestEvent) || executeDirectDispatch(terminationRequestEvent); + if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } @@ -2315,9 +2318,9 @@ function setResponderAndExtractTransfer( extracted = accumulate(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } + return extracted; } - /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer @@ -2326,10 +2329,10 @@ function setResponderAndExtractTransfer( * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ + function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return ( - topLevelInst && - // responderIgnoreScroll: We are trying to migrate away from specifically + topLevelInst && // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead ((topLevelType === TOP_SCROLL && !nativeEvent.responderIgnoreScroll) || @@ -2338,7 +2341,6 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { isMoveish(topLevelType)) ); } - /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. @@ -2346,22 +2348,28 @@ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ + function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; + if (!touches || touches.length === 0) { return true; } + for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; + if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = getInstanceFromNode(target); + if (isAncestor(responderInst, targetInst)) { return false; } } } + return true; } @@ -2370,7 +2378,6 @@ var ResponderEventPlugin = { _getResponder: function() { return responderInst; }, - eventTypes: eventTypes, /** @@ -2382,7 +2389,8 @@ var ResponderEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (isStartish(topLevelType)) { trackedTouchCount += 1; @@ -2390,7 +2398,7 @@ var ResponderEventPlugin = { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ); return null; @@ -2398,7 +2406,6 @@ var ResponderEventPlugin = { } ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); - var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer( topLevelType, @@ -2406,8 +2413,7 @@ var ResponderEventPlugin = { nativeEvent, nativeEventTarget ) - : null; - // Responder may or may not have transferred on a new touch start/move. + : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional @@ -2417,6 +2423,7 @@ var ResponderEventPlugin = { // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). + var isResponderTouchStart = responderInst && isStartish(topLevelType); var isResponderTouchMove = responderInst && isMoveish(topLevelType); var isResponderTouchEnd = responderInst && isEndish(topLevelType); @@ -2452,6 +2459,7 @@ var ResponderEventPlugin = { : isResponderRelease ? eventTypes.responderRelease : null; + if (finalTouch) { var finalEvent = ResponderSyntheticEvent.getPooled( finalTouch, @@ -2467,9 +2475,7 @@ var ResponderEventPlugin = { return extracted; }, - GlobalResponderHandler: null, - injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler @@ -2482,14 +2488,12 @@ var ResponderEventPlugin = { } }; -// Module provided by RN: var customBubblingEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customBubblingEventTypes; var customDirectEventTypes = ReactNativePrivateInterface.ReactNativeViewConfigRegistry .customDirectEventTypes; - var ReactNativeBridgeEventPlugin = { eventTypes: {}, @@ -2500,29 +2504,30 @@ var ReactNativeBridgeEventPlugin = { topLevelType, targetInst, nativeEvent, - nativeEventTarget + nativeEventTarget, + eventSystemFlags ) { if (targetInst == null) { // Probably a node belonging to another renderer's tree. return null; } + var bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; var directDispatchConfig = customDirectEventTypes[topLevelType]; - (function() { - if (!(bubbleDispatchConfig || directDispatchConfig)) { - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) - ); - } - })(); + + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget ); + if (bubbleDispatchConfig) { accumulateTwoPhaseDispatches(event); } else if (directDispatchConfig) { @@ -2530,6 +2535,7 @@ var ReactNativeBridgeEventPlugin = { } else { return null; } + return event; } }; @@ -2549,12 +2555,13 @@ var ReactNativeEventPluginOrder = [ /** * Inject module for resolving DOM hierarchy and plugin ordering. */ -injection.injectEventPluginOrder(ReactNativeEventPluginOrder); +injection.injectEventPluginOrder(ReactNativeEventPluginOrder); /** * Some important event plugins included by default (without having to require * them). */ + injection.injectEventPluginsByName({ ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin @@ -2562,11 +2569,9 @@ injection.injectEventPluginsByName({ var instanceCache = new Map(); var instanceProps = new Map(); - function precacheFiberNode(hostInst, tag) { instanceCache.set(tag, hostInst); } - function uncacheFiberNode(tag) { instanceCache.delete(tag); instanceProps.delete(tag); @@ -2578,26 +2583,26 @@ function getInstanceFromTag(tag) { function getTagFromInstance(inst) { var tag = inst.stateNode._nativeTag; + if (tag === undefined) { tag = inst.stateNode.canonical._nativeTag; } - (function() { - if (!tag) { - throw ReactError(Error("All native instances should have a tag.")); - } - })(); + + if (!tag) { + throw Error("All native instances should have a tag."); + } + return tag; } function getFiberCurrentPropsFromNode$1(stateNode) { return instanceProps.get(stateNode._nativeTag) || null; } - function updateFiberProps(tag, props) { instanceProps.set(tag, props); } -// Use to restore controlled state after a change event has fired. +var PLUGIN_EVENT_SYSTEM = 1; var restoreImpl = null; var restoreTarget = null; @@ -2607,19 +2612,18 @@ function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { // Unmounted return; } - (function() { - if (!(typeof restoreImpl === "function")) { - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof restoreImpl === "function")) { + 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." + ); + } + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, props); } @@ -2627,17 +2631,17 @@ function restoreStateOfTarget(target) { function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } - function restoreStateIfNeeded() { if (!restoreTarget) { return; } + var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; - restoreStateOfTarget(target); + if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); @@ -2656,38 +2660,39 @@ var enableSuspenseServerRenderer = false; var enableFlareAPI = false; var enableFundamentalAPI = false; +var enableScopeAPI = false; var warnAboutUnmockedScheduler = false; -var revertPassiveEffectsChange = false; var flushSuspenseFallbacksInTests = true; - var enableSuspenseCallback = false; var warnAboutDefaultPropsOnFunctionComponents = false; var warnAboutStringRefs = false; var disableLegacyContext = false; var disableSchedulerTimeoutBasedOnReactExpirationTime = false; - // Only used in www builds. -// Used as a way to call batchedUpdates when we don't have a reference to +// Flow magic to verify the exports of this file match the original version. + // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. - // Defaults + var batchedUpdatesImpl = function(fn, bookkeeping) { return fn(bookkeeping); }; + var flushDiscreteUpdatesImpl = function() {}; -var isInsideEventHandler = false; +var isInsideEventHandler = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React @@ -2703,7 +2708,9 @@ function batchedUpdates(fn, bookkeeping) { // fully completes before restoring state. return fn(bookkeeping); } + isInsideEventHandler = true; + try { return batchedUpdatesImpl(fn, bookkeeping); } finally { @@ -2711,6 +2718,7 @@ function batchedUpdates(fn, bookkeeping) { finishEventHandler(); } } +// This is for the React Flare event system function setBatchingImplementation( _batchedUpdatesImpl, @@ -2726,10 +2734,9 @@ function setBatchingImplementation( * Version of `ReactBrowserEventEmitter` that works on the receiving side of a * serialized worker boundary. */ - // Shared default empty native event - conserve memory. -var EMPTY_NATIVE_EVENT = {}; +var EMPTY_NATIVE_EVENT = {}; /** * Selects a subsequence of `Touch`es, without destroying `touches`. * @@ -2737,14 +2744,16 @@ var EMPTY_NATIVE_EVENT = {}; * @param {Array} indices Indices by which to pull subsequence. * @return {Array} Subsequence of touch objects. */ + var touchSubsequence = function(touches, indices) { var ret = []; + for (var i = 0; i < indices.length; i++) { ret.push(touches[indices[i]]); } + return ret; }; - /** * TODO: Pool all of this. * @@ -2756,27 +2765,32 @@ var touchSubsequence = function(touches, indices) { * @param {Array} indices Indices to remove from `touches`. * @return {Array} Subsequence of removed touch objects. */ + var removeTouchesAtIndices = function(touches, indices) { - var rippedOut = []; - // use an unsafe downcast to alias to nullable elements, + var rippedOut = []; // use an unsafe downcast to alias to nullable elements, // so we can delete and then compact. + var temp = touches; + for (var i = 0; i < indices.length; i++) { var index = indices[i]; rippedOut.push(touches[index]); temp[index] = null; } + var fillAt = 0; + for (var j = 0; j < temp.length; j++) { var cur = temp[j]; + if (cur !== null) { temp[fillAt++] = cur; } } + temp.length = fillAt; return rippedOut; }; - /** * Internal version of `receiveEvent` in terms of normalized (non-tag) * `rootNodeID`. @@ -2787,6 +2801,7 @@ var removeTouchesAtIndices = function(touches, indices) { * @param {TopLevelType} topLevelType Top level type of event. * @param {?object} nativeEventParam Object passed from native. */ + function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; var inst = getInstanceFromTag(rootNodeID); @@ -2795,13 +2810,12 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - nativeEvent.target + nativeEvent.target, + PLUGIN_EVENT_SYSTEM ); - }); - // React Native doesn't use ReactControlledComponent but if it did, here's + }); // React Native doesn't use ReactControlledComponent but if it did, here's // where it would do it. } - /** * Publicly exposed method on module for native objc to invoke when a top * level event is extracted. @@ -2809,10 +2823,10 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { * @param {TopLevelType} topLevelType Top level type of event. * @param {object} nativeEventParam Object passed from native. */ + function receiveEvent(rootNodeID, topLevelType, nativeEventParam) { _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam); } - /** * Simple multi-wrapper around `receiveEvent` that is intended to receive an * efficient representation of `Touch` objects, and other information that @@ -2837,6 +2851,7 @@ function receiveEvent(rootNodeID, topLevelType, nativeEventParam) { * Web desktop polyfills only need to construct a fake touch event with * identifier 0, also abandoning traditional click handlers. */ + function receiveTouches(eventTopLevelType, touches, changedIndices) { var changedTouches = eventTopLevelType === "topTouchEnd" || @@ -2845,14 +2860,15 @@ function receiveTouches(eventTopLevelType, touches, changedIndices) { : touchSubsequence(touches, changedIndices); for (var jj = 0; jj < changedTouches.length; jj++) { - var touch = changedTouches[jj]; - // Touch objects can fulfill the role of `DOM` `Event` objects if we set + var touch = changedTouches[jj]; // Touch objects can fulfill the role of `DOM` `Event` objects if we set // the `changedTouches`/`touches`. This saves allocations. + touch.changedTouches = changedTouches; touch.touches = touches; var nativeEvent = touch; var rootNodeID = null; var target = nativeEvent.target; + if (target !== null && target !== undefined) { if (target < 1) { { @@ -2864,8 +2880,8 @@ function receiveTouches(eventTopLevelType, touches, changedIndices) { } else { rootNodeID = target; } - } - // $FlowFixMe Shouldn't we *not* call it if rootNodeID is null? + } // $FlowFixMe Shouldn't we *not* call it if rootNodeID is null? + _receiveRootNodeIDEvent(rootNodeID, eventTopLevelType, nativeEvent); } } @@ -2885,21 +2901,19 @@ var ReactNativeGlobalResponderHandler = { } }; -// Module provided by RN: /** * Register the event emitter with the native bridge */ + ReactNativePrivateInterface.RCTEventEmitter.register({ receiveEvent: receiveEvent, receiveTouches: receiveTouches }); - setComponentTree( getFiberCurrentPropsFromNode$1, getInstanceFromTag, getTagFromInstance ); - ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactNativeGlobalResponderHandler ); @@ -2929,16 +2943,16 @@ function set(key, value) { } var ReactSharedInternals = - React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - -// Prevent newer renderers from RTE when used with older react package versions. + React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentDispatcher")) { ReactSharedInternals.ReactCurrentDispatcher = { current: null }; } + if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null @@ -2948,7 +2962,6 @@ if (!ReactSharedInternals.hasOwnProperty("ReactCurrentBatchConfig")) { // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === "function" && Symbol.for; - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 0xeacb; @@ -2957,8 +2970,7 @@ var REACT_STRICT_MODE_TYPE = hasSymbol : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; -// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary // (unstable) APIs that have been removed. Can we remove the symbols? var REACT_CONCURRENT_MODE_TYPE = hasSymbol @@ -2977,33 +2989,108 @@ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 0xead6; - +var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } + var maybeIterator = (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { return maybeIterator; } + return null; } +/** + * Similar to invariant but only logs a warning if the condition is not met. + * This can be used to log issues in development environments in critical + * paths. Removing the logging code for production environments will keep the + * same logic and follow the same code paths. + */ + +var warning = warningWithoutStack$1; + +{ + warning = function(condition, format) { + if (condition) { + return; + } + + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args + + for ( + var _len = arguments.length, + args = new Array(_len > 2 ? _len - 2 : 0), + _key = 2; + _key < _len; + _key++ + ) { + args[_key - 2] = arguments[_key]; + } + + warningWithoutStack$1.apply( + void 0, + [false, format + "%s"].concat(args, [stack]) + ); + }; +} + +var warning$1 = warning; + +var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; - function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then( + function(moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; -function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; + { + if (defaultExport === undefined) { + 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 + ); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, + function(error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + } + ); + } +} + +function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ""; return ( outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName) @@ -3015,6 +3102,7 @@ function getComponentName(type) { // Host root, text node or just invalid type. return null; } + { if (typeof type.tag === "number") { warningWithoutStack$1( @@ -3024,116 +3112,169 @@ function getComponentName(type) { ); } } + if (typeof type === "function") { return type.displayName || type.name || null; } + if (typeof type === "string") { return type; } + switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; + case REACT_PORTAL_TYPE: return "Portal"; + case REACT_PROFILER_TYPE: return "Profiler"; + case REACT_STRICT_MODE_TYPE: return "StrictMode"; + case REACT_SUSPENSE_TYPE: return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } + if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return "Context.Consumer"; + case REACT_PROVIDER_TYPE: return "Context.Provider"; + case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: return getComponentName(type.type); + case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); + if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; } } } + return null; } // Don't change these two values. They're used by React Dev Tools. -var NoEffect = /* */ 0; -var PerformedWork = /* */ 1; - -// You can change the rest (and add more). -var Placement = /* */ 2; -var Update = /* */ 4; -var PlacementAndUpdate = /* */ 6; -var Deletion = /* */ 8; -var ContentReset = /* */ 16; -var Callback = /* */ 32; -var DidCapture = /* */ 64; -var Ref = /* */ 128; -var Snapshot = /* */ 256; -var Passive = /* */ 512; - -// Passive & Update & Callback & Ref & Snapshot -var LifecycleEffectMask = /* */ 932; - -// Union of all host effects -var HostEffectMask = /* */ 1023; - -var Incomplete = /* */ 1024; -var ShouldCapture = /* */ 2048; +var NoEffect = + /* */ + 0; +var PerformedWork = + /* */ + 1; // You can change the rest (and add more). + +var Placement = + /* */ + 2; +var Update = + /* */ + 4; +var PlacementAndUpdate = + /* */ + 6; +var Deletion = + /* */ + 8; +var ContentReset = + /* */ + 16; +var Callback = + /* */ + 32; +var DidCapture = + /* */ + 64; +var Ref = + /* */ + 128; +var Snapshot = + /* */ + 256; +var Passive = + /* */ + 512; +var Hydrating = + /* */ + 1024; +var HydratingAndUpdate = + /* */ + 1028; // Passive & Update & Callback & Ref & Snapshot + +var LifecycleEffectMask = + /* */ + 932; // Union of all host effects + +var HostEffectMask = + /* */ + 2047; +var Incomplete = + /* */ + 2048; +var ShouldCapture = + /* */ + 4096; var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - -var MOUNTING = 1; -var MOUNTED = 2; -var UNMOUNTED = 3; - -function isFiberMountedImpl(fiber) { +function getNearestMountedFiber(fiber) { var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; - } - while (node.return) { - node = node.return; - if ((node.effectTag & Placement) !== NoEffect) { - return MOUNTING; + var nextNode = node; + + do { + node = nextNode; + + if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { + // This is an insertion or in-progress hydration. The nearest possible + // mounted fiber is the parent but we need to continue to figure out + // if that one is still mounted. + nearestMounted = node.return; } - } + + nextNode = node.return; + } while (nextNode); } else { while (node.return) { node = node.return; } } + if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. - return MOUNTED; - } - // If we didn't hit the root, that means that we're in an disconnected tree + return nearestMounted; + } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. - return UNMOUNTED; + + return null; } function isFiberMounted(fiber) { - return isFiberMountedImpl(fiber) === MOUNTED; + return getNearestMountedFiber(fiber) === fiber; } - function isMounted(component) { { var owner = ReactCurrentOwner$1.current; + if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; @@ -3153,90 +3294,93 @@ function isMounted(component) { } var fiber = get(component); + if (!fiber) { return false; } - return isFiberMountedImpl(fiber) === MOUNTED; + + return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { - (function() { - if (!(isFiberMountedImpl(fiber) === MOUNTED)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); - } - })(); + if (!(getNearestMountedFiber(fiber) === fiber)) { + throw Error("Unable to find node on an unmounted component."); + } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; + if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. - var state = isFiberMountedImpl(fiber); - (function() { - if (!(state !== UNMOUNTED)) { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - if (state === MOUNTING) { + var nearestMounted = getNearestMountedFiber(fiber); + + if (!(nearestMounted !== null)) { + throw Error("Unable to find node on an unmounted component."); + } + + if (nearestMounted !== fiber) { return null; } + return fiber; - } - // If we have two possible branches, we'll walk backwards up to the root + } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. + var a = fiber; var b = alternate; + while (true) { var parentA = a.return; + if (parentA === null) { // We're at the root. break; } + var parentB = parentA.alternate; + if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; + if (nextParent !== null) { a = b = nextParent; continue; - } - // If there's no parent, we're at the root. - break; - } + } // If there's no parent, we're at the root. - // If both copies of the parent fiber point to the same child, we can + break; + } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. + if (parentA.child === parentB.child) { var child = parentA.child; + while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } + if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } + child = child.sibling; - } - // We should never have an alternate for any mounting node. So the only + } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); + + { + throw Error("Unable to find node on an unmounted component."); + } } if (a.return !== b.return) { @@ -3254,6 +3398,7 @@ function findCurrentFiberUsingSlowPath(fiber) { // Search parent A's child set var didFindChild = false; var _child = parentA.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3261,17 +3406,21 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentB; break; } + if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } + _child = _child.sibling; } + if (!didFindChild) { // Search parent B's child set _child = parentB.child; + while (_child) { if (_child === a) { didFindChild = true; @@ -3279,59 +3428,53 @@ function findCurrentFiberUsingSlowPath(fiber) { b = parentA; break; } + if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } + _child = _child.sibling; } - (function() { - if (!didFindChild) { - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) - ); - } - })(); + + if (!didFindChild) { + 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." + ); + } } } - (function() { - if (!(a.alternate === b)) { - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - (function() { - if (!(a.tag === HostRoot)) { - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (!(a.alternate === b)) { + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - })(); + } // If the root is not a host container, we're in a disconnected tree. I.e. + // unmounted. + + if (!(a.tag === HostRoot)) { + throw Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; - } - // Otherwise B has to be current branch. + } // Otherwise B has to be current branch. + return alternate; } - function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); + if (!currentParent) { return null; - } + } // Next we'll drill down this component to find the first HostComponent/Text. - // Next we'll drill down this component to find the first HostComponent/Text. var node = currentParent; + while (true) { if (node.tag === HostComponent || node.tag === HostText) { return node; @@ -3340,26 +3483,29 @@ function findCurrentHostFiber(parent) { node = node.child; continue; } + if (node === currentParent) { return null; } + while (!node.sibling) { if (!node.return || node.return === currentParent) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; - } - // Flow needs the return null here, but ESLint complains about it. + } // Flow needs the return null here, but ESLint complains about it. // eslint-disable-next-line no-unreachable + return null; } // Modules provided by RN: var emptyObject = {}; - /** * Create a payload that contains all the updates between two sets of props. * @@ -3390,6 +3536,7 @@ function restoreDeletedValuesInNestedArray( ) { if (Array.isArray(node)) { var i = node.length; + while (i-- && removedKeyCount > 0) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3399,16 +3546,20 @@ function restoreDeletedValuesInNestedArray( } } else if (node && removedKeyCount > 0) { var obj = node; + for (var propKey in removedKeys) { if (!removedKeys[propKey]) { continue; } + var nextProp = obj[propKey]; + if (nextProp === undefined) { continue; } var attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3416,6 +3567,7 @@ function restoreDeletedValuesInNestedArray( if (typeof nextProp === "function") { nextProp = true; } + if (typeof nextProp === "undefined") { nextProp = null; } @@ -3434,6 +3586,7 @@ function restoreDeletedValuesInNestedArray( : nextProp; updatePayload[propKey] = nextValue; } + removedKeys[propKey] = false; removedKeyCount--; } @@ -3448,7 +3601,8 @@ function diffNestedArrayProperty( ) { var minLength = prevArray.length < nextArray.length ? prevArray.length : nextArray.length; - var i = void 0; + var i; + for (i = 0; i < minLength; i++) { // Diff any items in the array in the forward direction. Repeated keys // will be overwritten by later values. @@ -3459,6 +3613,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < prevArray.length; i++) { // Clear out all remaining properties. updatePayload = clearNestedProperty( @@ -3467,6 +3622,7 @@ function diffNestedArrayProperty( validAttributes ); } + for (; i < nextArray.length; i++) { // Add all remaining properties. updatePayload = addNestedProperty( @@ -3475,6 +3631,7 @@ function diffNestedArrayProperty( validAttributes ); } + return updatePayload; } @@ -3494,9 +3651,11 @@ function diffNestedProperty( if (nextProp) { return addNestedProperty(updatePayload, nextProp, validAttributes); } + if (prevProp) { return clearNestedProperty(updatePayload, prevProp, validAttributes); } + return updatePayload; } @@ -3517,10 +3676,8 @@ function diffNestedProperty( if (Array.isArray(prevProp)) { return diffProperties( - updatePayload, - // $FlowFixMe - We know that this is always an object when the input is. - ReactNativePrivateInterface.flattenStyle(prevProp), - // $FlowFixMe - We know that this isn't an array because of above flow. + updatePayload, // $FlowFixMe - We know that this is always an object when the input is. + ReactNativePrivateInterface.flattenStyle(prevProp), // $FlowFixMe - We know that this isn't an array because of above flow. nextProp, validAttributes ); @@ -3528,18 +3685,17 @@ function diffNestedProperty( return diffProperties( updatePayload, - prevProp, - // $FlowFixMe - We know that this is always an object when the input is. + prevProp, // $FlowFixMe - We know that this is always an object when the input is. ReactNativePrivateInterface.flattenStyle(nextProp), validAttributes ); } - /** * addNestedProperty takes a single set of props and valid attribute * attribute configurations. It processes each prop and adds it to the * updatePayload. */ + function addNestedProperty(updatePayload, nextProp, validAttributes) { if (!nextProp) { return updatePayload; @@ -3561,11 +3717,11 @@ function addNestedProperty(updatePayload, nextProp, validAttributes) { return updatePayload; } - /** * clearNestedProperty takes a single set of props and valid attributes. It * adds a null sentinel to the updatePayload, for each prop key. */ + function clearNestedProperty(updatePayload, prevProp, validAttributes) { if (!prevProp) { return updatePayload; @@ -3584,44 +3740,45 @@ function clearNestedProperty(updatePayload, prevProp, validAttributes) { validAttributes ); } + return updatePayload; } - /** * diffProperties takes two sets of props and a set of valid attributes * and write to updatePayload the values that changed or were deleted. * If no updatePayload is provided, a new one is created and returned if * anything changed. */ + function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { - var attributeConfig = void 0; - var nextProp = void 0; - var prevProp = void 0; + var attributeConfig; + var nextProp; + var prevProp; for (var propKey in nextProps) { attributeConfig = validAttributes[propKey]; + if (!attributeConfig) { continue; // not a valid native prop } prevProp = prevProps[propKey]; - nextProp = nextProps[propKey]; - - // functions are converted to booleans as markers that the associated + nextProp = nextProps[propKey]; // functions are converted to booleans as markers that the associated // events should be sent from native. + if (typeof nextProp === "function") { - nextProp = true; - // If nextProp is not a function, then don't bother changing prevProp + nextProp = true; // If nextProp is not a function, then don't bother changing prevProp // since nextProp will win and go into the updatePayload regardless. + if (typeof prevProp === "function") { prevProp = true; } - } - - // An explicit value of undefined is treated as a null because it overrides + } // An explicit value of undefined is treated as a null because it overrides // any other preceding value. + if (typeof nextProp === "undefined") { nextProp = null; + if (typeof prevProp === "undefined") { prevProp = null; } @@ -3636,7 +3793,6 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // value diffed. Since we're now later in the nested arrays our value is // more important so we need to calculate it and override the existing // value. It doesn't matter if nothing changed, we'll set it anyway. - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case @@ -3652,14 +3808,14 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { : nextProp; updatePayload[propKey] = nextValue; } + continue; } if (prevProp === nextProp) { continue; // nothing changed - } + } // Pattern match on: attributeConfig - // Pattern match on: attributeConfig if (typeof attributeConfig !== "object") { // case: !Object is the default case if (defaultDiffer(prevProp, nextProp)) { @@ -3676,25 +3832,28 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { (typeof attributeConfig.diff === "function" ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); + if (shouldUpdate) { var _nextValue = typeof attributeConfig.process === "function" ? attributeConfig.process(nextProp) : nextProp; + (updatePayload || (updatePayload = {}))[propKey] = _nextValue; } } else { // default: fallthrough case when nested properties are defined removedKeys = null; - removedKeyCount = 0; - // We think that attributeConfig is not CustomAttributeConfiguration at + removedKeyCount = 0; // We think that attributeConfig is not CustomAttributeConfiguration at // this point so we assume it must be AttributeConfiguration. + updatePayload = diffNestedProperty( updatePayload, prevProp, nextProp, attributeConfig ); + if (removedKeyCount > 0 && updatePayload) { restoreDeletedValuesInNestedArray( updatePayload, @@ -3704,16 +3863,17 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { removedKeys = null; } } - } - - // Also iterate through all the previous props to catch any that have been + } // Also iterate through all the previous props to catch any that have been // removed and make sure native gets the signal so it can reset them to the // default. + for (var _propKey in prevProps) { if (nextProps[_propKey] !== undefined) { continue; // we've already covered this key in the previous pass } + attributeConfig = validAttributes[_propKey]; + if (!attributeConfig) { continue; // not a valid native prop } @@ -3724,10 +3884,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { } prevProp = prevProps[_propKey]; + if (prevProp === undefined) { continue; // was already empty anyway - } - // Pattern match on: attributeConfig + } // Pattern match on: attributeConfig + if ( typeof attributeConfig !== "object" || typeof attributeConfig.diff === "function" || @@ -3736,9 +3897,11 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { // case: CustomAttributeConfiguration | !Object // Flag the leaf property for removal by sending a sentinel. (updatePayload || (updatePayload = {}))[_propKey] = null; + if (!removedKeys) { removedKeys = {}; } + if (!removedKeys[_propKey]) { removedKeys[_propKey] = true; removedKeyCount++; @@ -3754,21 +3917,22 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ); } } + return updatePayload; } - /** * addProperties adds all the valid props to the payload after being processed. */ + function addProperties(updatePayload, props, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, emptyObject, props, validAttributes); } - /** * clearProperties clears all the previous props by adding a null sentinel * to the payload for each valid key. */ + function clearProperties(updatePayload, prevProps, validAttributes) { // TODO: Fast path return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); @@ -3781,7 +3945,6 @@ function create(props, validAttributes) { validAttributes ); } - function diff(prevProps, nextProps, validAttributes) { return diffProperties( null, // updatePayload @@ -3799,24 +3962,20 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return function() { if (!callback) { return undefined; - } - // This protects against createClass() components. + } // This protects against createClass() components. // We don't know if there is code depending on it. // We intentionally don't use isMounted() because even accessing // isMounted property on a React ES6 class will trigger a warning. + if (typeof context.__isMounted === "boolean") { if (!context.__isMounted) { return undefined; } - } - - // FIXME: there used to be other branches that protected + } // FIXME: there used to be other branches that protected // against unmounted host components. But RN host components don't // define isMounted() anymore, so those checks didn't do anything. - // They caused false positive warning noise so we removed them: // https://github.com/facebook/react-native/issues/18868#issuecomment-413579095 - // However, this means that the callback is NOT guaranteed to be safe // for host components. The solution we should implement is to make // UIManager.measure() and similar calls truly cancelable. Then we @@ -3825,7 +3984,6 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { return callback.apply(context, arguments); }; } - function throwOnStylesProp(component, props) { if (props.styles !== undefined) { var owner = component._owner || null; @@ -3835,6 +3993,7 @@ function throwOnStylesProp(component, props) { name + "`, did " + "you mean `style` (singular)?"; + if (owner && owner.constructor && owner.constructor.displayName) { msg += "\n\nCheck the `" + @@ -3842,10 +4001,10 @@ function throwOnStylesProp(component, props) { "` parent " + " component."; } + throw new Error(msg); } } - function warnForStyleProps(props, validAttributes) { for (var key in validAttributes.style) { if (!(validAttributes[key] || props[key] === undefined)) { @@ -3862,12 +4021,6 @@ function warnForStyleProps(props, validAttributes) { } } -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - // Modules provided by RN: /** * This component defines the same methods as NativeMethodsMixin but without the @@ -3877,119 +4030,103 @@ function _classCallCheck(instance, Constructor) { * ReactNativeFiber). */ -var ReactNativeFiberHostComponent = (function() { - function ReactNativeFiberHostComponent(tag, viewConfig) { - _classCallCheck(this, ReactNativeFiberHostComponent); - - this._nativeTag = tag; - this._children = []; - this.viewConfig = viewConfig; - } - - ReactNativeFiberHostComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); - }; - - ReactNativeFiberHostComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); - }; - - ReactNativeFiberHostComponent.prototype.measure = function measure(callback) { - ReactNativePrivateInterface.UIManager.measure( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - - ReactNativeFiberHostComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - ReactNativePrivateInterface.UIManager.measureInWindow( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; +var ReactNativeFiberHostComponent = + /*#__PURE__*/ + (function() { + function ReactNativeFiberHostComponent(tag, viewConfig) { + this._nativeTag = tag; + this._children = []; + this.viewConfig = viewConfig; + } - ReactNativeFiberHostComponent.prototype.measureLayout = function measureLayout( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var relativeNode = void 0; + var _proto = ReactNativeFiberHostComponent.prototype; - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } else if ( - /* $FlowFixMe canonical doesn't exist on the node. - I think this branch is dead and will remove it in a followup */ - relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag - ) { - /* $FlowFixMe canonical doesn't exist on the node. - I think this branch is dead and will remove it in a followup */ - relativeNode = relativeToNativeNode.canonical._nativeTag; - } + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); + }; - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + this._nativeTag ); + }; - return; - } + _proto.measure = function measure(callback) { + ReactNativePrivateInterface.UIManager.measure( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactNativePrivateInterface.UIManager.measureLayout( - this._nativeTag, - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; + _proto.measureInWindow = function measureInWindow(callback) { + ReactNativePrivateInterface.UIManager.measureInWindow( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) /* currently unused */ { - warnForStyleProps(nativeProps, this.viewConfig.validAttributes); - } + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } - var updatePayload = create(nativeProps, this.viewConfig.validAttributes); + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( + ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, - this.viewConfig.uiViewClassName, - updatePayload + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); - } - }; + }; + + _proto.setNativeProps = function setNativeProps(nativeProps) { + { + warnForStyleProps(nativeProps, this.viewConfig.validAttributes); + } + + var updatePayload = create(nativeProps, this.viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + this._nativeTag, + this.viewConfig.uiViewClassName, + updatePayload + ); + } + }; - return ReactNativeFiberHostComponent; -})(); + return ReactNativeFiberHostComponent; + })(); // eslint-disable-next-line no-unused-expressions -// Renderers that don't support persistence // can re-export everything from this module. function shim() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} + { + throw Error( + "The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Persistence (when unsupported) -// Persistence (when unsupported) var supportsPersistence = false; var cloneInstance = shim; var cloneFundamentalInstance = shim; @@ -4000,22 +4137,15 @@ var replaceContainerChildren = shim; var cloneHiddenInstance = shim; var cloneHiddenTextInstance = shim; -// Renderers that don't support hydration // can re-export everything from this module. function shim$1() { - (function() { - { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); -} - -// Hydration (when unsupported) + { + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } +} // Hydration (when unsupported) var supportsHydration = false; var canHydrateInstance = shim$1; @@ -4028,7 +4158,10 @@ var getNextHydratableSibling = shim$1; var getFirstHydratableChild = shim$1; var hydrateInstance = shim$1; var hydrateTextInstance = shim$1; +var hydrateSuspenseInstance = shim$1; var getNextHydratableInstanceAfterSuspenseInstance = shim$1; +var commitHydratedContainer = shim$1; +var commitHydratedSuspenseInstance = shim$1; var clearSuspenseBoundary = shim$1; var clearSuspenseBoundaryFromContainer = shim$1; var didNotMatchHydratedContainerTextInstance = shim$1; @@ -4042,25 +4175,25 @@ var didNotFindHydratableInstance = shim$1; var didNotFindHydratableTextInstance = shim$1; var didNotFindHydratableSuspenseInstance = shim$1; -// Modules provided by RN: var getViewConfigForType = - ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; // Unused -// Unused - + ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; var UPDATE_SIGNAL = {}; + { Object.freeze(UPDATE_SIGNAL); -} - -// Counter for uniquely identifying views. +} // Counter for uniquely identifying views. // % 10 === 1 means it is a rootTag. // % 2 === 0 means it is a Fabric tag. + var nextReactTag = 3; + function allocateTag() { var tag = nextReactTag; + if (tag % 10 === 1) { tag += 2; } + nextReactTag = tag + 2; return tag; } @@ -4079,7 +4212,6 @@ function recursivelyUncacheFiberNode(node) { function appendInitialChild(parentInstance, child) { parentInstance._children.push(child); } - function createInstance( type, props, @@ -4101,52 +4233,41 @@ function createInstance( } var updatePayload = create(props, viewConfig.validAttributes); - ReactNativePrivateInterface.UIManager.createView( tag, // reactTag viewConfig.uiViewClassName, // viewName rootContainerInstance, // rootTag updatePayload // props ); - var component = new ReactNativeFiberHostComponent(tag, viewConfig); - precacheFiberNode(internalInstanceHandle, tag); - updateFiberProps(tag, props); - - // Not sure how to avoid this cast. Flow is okay if the component is defined + updateFiberProps(tag, props); // Not sure how to avoid this cast. Flow is okay if the component is defined // in the same file but if it's external it can't see the types. + return component; } - function createTextInstance( text, rootContainerInstance, hostContext, internalInstanceHandle ) { - (function() { - if (!hostContext.isInAParentText) { - throw ReactError( - Error("Text strings must be rendered within a component.") - ); - } - })(); + if (!hostContext.isInAParentText) { + throw Error("Text strings must be rendered within a component."); + } var tag = allocateTag(); - ReactNativePrivateInterface.UIManager.createView( tag, // reactTag "RCTRawText", // viewName rootContainerInstance, // rootTag - { text: text } // props + { + text: text + } // props ); - precacheFiberNode(internalInstanceHandle, tag); - return tag; } - function finalizeInitialChildren( parentInstance, type, @@ -4157,10 +4278,9 @@ function finalizeInitialChildren( // Don't send a no-op message over the bridge. if (parentInstance._children.length === 0) { return false; - } - - // Map from child objects to native tags. + } // Map from child objects to native tags. // Either way we need to pass a copy of the Array to prevent it from being frozen. + var nativeTags = parentInstance._children.map(function(child) { return typeof child === "number" ? child // Leaf node (eg text) @@ -4171,14 +4291,13 @@ function finalizeInitialChildren( parentInstance._nativeTag, // containerTag nativeTags // reactTags ); - return false; } - function getRootHostContext(rootContainerInstance) { - return { isInAParentText: false }; + return { + isInAParentText: false + }; } - function getChildHostContext(parentHostContext, type, rootContainerInstance) { var prevIsInAParentText = parentHostContext.isInAParentText; var isInAParentText = @@ -4189,20 +4308,19 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { type === "RCTVirtualText"; if (prevIsInAParentText !== isInAParentText) { - return { isInAParentText: isInAParentText }; + return { + isInAParentText: isInAParentText + }; } else { return parentHostContext; } } - function getPublicInstance(instance) { return instance; } - function prepareForCommit(containerInfo) { // Noop } - function prepareUpdate( instance, type, @@ -4213,22 +4331,17 @@ function prepareUpdate( ) { return UPDATE_SIGNAL; } - function resetAfterCommit(containerInfo) { // Noop } - var isPrimaryRenderer = true; var warnsIfNotActing = true; - var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; var noTimeout = -1; - function shouldDeprioritizeSubtree(type, props) { return false; } - function shouldSetTextContent(type, props) { // TODO (bvaughn) Revisit this decision. // Always returning false simplifies the createInstance() implementation, @@ -4237,14 +4350,11 @@ function shouldSetTextContent(type, props) { // It's not clear to me which is better so I'm deferring for now. // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 return false; -} - -// ------------------- +} // ------------------- // Mutation // ------------------- var supportsMutation = true; - function appendChild(parentInstance, child) { var childTag = typeof child === "number" ? child : child._nativeTag; var children = parentInstance._children; @@ -4253,7 +4363,6 @@ function appendChild(parentInstance, child) { if (index >= 0) { children.splice(index, 1); children.push(child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerTag [index], // moveFromIndices @@ -4264,7 +4373,6 @@ function appendChild(parentInstance, child) { ); } else { children.push(child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerTag [], // moveFromIndices @@ -4275,7 +4383,6 @@ function appendChild(parentInstance, child) { ); } } - function appendChildToContainer(parentInstance, child) { var childTag = typeof child === "number" ? child : child._nativeTag; ReactNativePrivateInterface.UIManager.setChildren( @@ -4283,12 +4390,13 @@ function appendChildToContainer(parentInstance, child) { [childTag] // reactTags ); } - function commitTextUpdate(textInstance, oldText, newText) { ReactNativePrivateInterface.UIManager.updateView( textInstance, // reactTag "RCTRawText", // viewName - { text: newText } // props + { + text: newText + } // props ); } @@ -4301,14 +4409,11 @@ function commitUpdate( internalInstanceHandle ) { var viewConfig = instance.viewConfig; - updateFiberProps(instance._nativeTag, newProps); - - var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( instance._nativeTag, // reactTag @@ -4317,17 +4422,14 @@ function commitUpdate( ); } } - function insertBefore(parentInstance, child, beforeChild) { var children = parentInstance._children; - var index = children.indexOf(child); + var index = children.indexOf(child); // Move existing child or add new child? - // Move existing child or add new child? if (index >= 0) { children.splice(index, 1); var beforeChildIndex = children.indexOf(beforeChild); children.splice(beforeChildIndex, 0, child); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [index], // moveFromIndices @@ -4338,10 +4440,9 @@ function insertBefore(parentInstance, child, beforeChild) { ); } else { var _beforeChildIndex = children.indexOf(beforeChild); - children.splice(_beforeChildIndex, 0, child); + children.splice(_beforeChildIndex, 0, child); var childTag = typeof child === "number" ? child : child._nativeTag; - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [], // moveFromIndices @@ -4352,28 +4453,20 @@ function insertBefore(parentInstance, child, beforeChild) { ); } } - function insertInContainerBefore(parentInstance, child, beforeChild) { // TODO (bvaughn): Remove this check when... // We create a wrapper object for the container in ReactNative render() // Or we refactor to remove wrapper objects entirely. // For more info on pros/cons see PR #8560 description. - (function() { - if (!(typeof parentInstance !== "number")) { - throw ReactError( - Error("Container does not support insertBefore operation") - ); - } - })(); + if (!(typeof parentInstance !== "number")) { + throw Error("Container does not support insertBefore operation"); + } } - function removeChild(parentInstance, child) { recursivelyUncacheFiberNode(child); var children = parentInstance._children; var index = children.indexOf(child); - children.splice(index, 1); - ReactNativePrivateInterface.UIManager.manageChildren( parentInstance._nativeTag, // containerID [], // moveFromIndices @@ -4383,7 +4476,6 @@ function removeChild(parentInstance, child) { [index] // removeAtIndices ); } - function removeChildFromContainer(parentInstance, child) { recursivelyUncacheFiberNode(child); ReactNativePrivateInterface.UIManager.manageChildren( @@ -4395,15 +4487,17 @@ function removeChildFromContainer(parentInstance, child) { [0] // removeAtIndices ); } - function resetTextContent(instance) { // Noop } - function hideInstance(instance) { var viewConfig = instance.viewConfig; var updatePayload = create( - { style: { display: "none" } }, + { + style: { + display: "none" + } + }, viewConfig.validAttributes ); ReactNativePrivateInterface.UIManager.updateView( @@ -4412,15 +4506,20 @@ function hideInstance(instance) { updatePayload ); } - function hideTextInstance(textInstance) { throw new Error("Not yet implemented."); } - function unhideInstance(instance, props) { var viewConfig = instance.viewConfig; var updatePayload = diff( - Object.assign({}, props, { style: [props.style, { display: "none" }] }), + Object.assign({}, props, { + style: [ + props.style, + { + display: "none" + } + ] + }), props, viewConfig.validAttributes ); @@ -4430,60 +4529,57 @@ function unhideInstance(instance, props) { updatePayload ); } - function unhideTextInstance(textInstance, text) { throw new Error("Not yet implemented."); } - function mountResponderInstance( responder, responderInstance, props, state, - instance, - rootContainerInstance + instance ) { throw new Error("Not yet implemented."); } - function unmountResponderInstance(responderInstance) { throw new Error("Not yet implemented."); } - function getFundamentalComponentInstance(fundamentalInstance) { throw new Error("Not yet implemented."); } - function mountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function shouldUpdateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function updateFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } - function unmountFundamentalComponent(fundamentalInstance) { throw new Error("Not yet implemented."); } +function getInstanceFromNode$1(node) { + throw new Error("Not yet implemented."); +} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; - var describeComponentFrame = function(name, source, ownerName) { var sourceInfo = ""; + if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ""); + { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); + if (match) { var pathBeforeSlash = match[1]; + if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ""); fileName = folderName + "/" + fileName; @@ -4491,10 +4587,12 @@ var describeComponentFrame = function(name, source, ownerName) { } } } + sourceInfo = " (at " + fileName + ":" + source.lineNumber + ")"; } else if (ownerName) { sourceInfo = " (created by " + ownerName + ")"; } + return "\n in " + (name || "Unknown") + sourceInfo; }; @@ -4509,14 +4607,17 @@ function describeFiber(fiber) { case ContextProvider: case ContextConsumer: return ""; + default: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName(fiber.type); var ownerName = null; + if (owner) { ownerName = getComponentName(owner.type); } + return describeComponentFrame(name, source, ownerName); } } @@ -4524,41 +4625,43 @@ function describeFiber(fiber) { function getStackByFiberInDevAndProd(workInProgress) { var info = ""; var node = workInProgress; + do { info += describeFiber(node); node = node.return; } while (node); + return info; } - var current = null; var phase = null; - function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { return getComponentName(owner.type); } } + return null; } - function getCurrentFiberStackInDev() { { if (current === null) { return ""; - } - // Safe because if current fiber exists, we are reconciling, + } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. + return getStackByFiberInDevAndProd(current); } + return ""; } - function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; @@ -4566,7 +4669,6 @@ function resetCurrentFiber() { phase = null; } } - function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; @@ -4574,7 +4676,6 @@ function setCurrentFiber(fiber) { phase = null; } } - function setCurrentPhase(lifeCyclePhase) { { phase = lifeCyclePhase; @@ -4590,28 +4691,26 @@ var supportsUserTiming = 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. + typeof performance.clearMeasures === "function"; // Keep track of current fiber so that we know the path to unwind on pause. // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? -var currentFiber = null; -// If we're in the middle of user code, which fiber and method is it? + +var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). + var currentPhase = null; -var currentPhaseFiber = null; -// Did lifecycle hook schedule an update? This is often a performance problem, +var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. + var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; -var isWaitingForCallback = false; -// During commits, we only show a measurement once per method name // to avoid stretch the commit phase with measurement overhead. + var labelsInCurrentCommit = new Set(); var formatMarkName = function(markName) { @@ -4635,14 +4734,14 @@ var clearMark = function(markName) { var endMark = function(label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); + try { performance.measure(formattedLabel, formattedMarkName); - } catch (err) {} - // If previous mark was missing for some reason, this will throw. + } catch (err) {} // If previous mark was missing for some reason, this will throw. // This could only happen if React crashed in an unexpected place earlier. // Don't pile on with more errors. - // Clear marks immediately to avoid growing buffer. + performance.clearMarks(formattedMarkName); performance.clearMeasures(formattedLabel); }; @@ -4673,8 +4772,8 @@ var beginFiberMark = function(fiber, phase) { // want to stretch the commit phase beyond necessary. return false; } - labelsInCurrentCommit.add(label); + labelsInCurrentCommit.add(label); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; @@ -4711,6 +4810,7 @@ var shouldIgnoreFiber = function(fiber) { case ContextConsumer: case Mode: return true; + default: return false; } @@ -4720,6 +4820,7 @@ var clearPendingPhaseMeasurement = function() { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } + currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; @@ -4729,10 +4830,12 @@ var pauseTimers = function() { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; + while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } + fiber = fiber.return; } }; @@ -4741,6 +4844,7 @@ var resumeTimersRecursively = function(fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } + if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } @@ -4758,12 +4862,12 @@ function recordEffect() { effectCountInCurrentCommit++; } } - function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } + if ( currentPhase !== null && currentPhase !== "componentWillMount" && @@ -4774,143 +4878,125 @@ function recordScheduleUpdate() { } } -function startRequestCallbackTimer() { - if (enableUserTimingAPI) { - if (supportsUserTiming && !isWaitingForCallback) { - isWaitingForCallback = true; - beginMark("(Waiting for async callback...)"); - } - } -} - -function stopRequestCallbackTimer(didExpire) { - if (enableUserTimingAPI) { - if (supportsUserTiming) { - isWaitingForCallback = false; - var warning = didExpire - ? "Update expired; will flush synchronously" - : null; - endMark( - "(Waiting for async callback...)", - "(Waiting for async callback...)", - warning - ); - } - } -} - function startWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, this is the fiber to unwind from. + } // If we pause, this is the fiber to unwind from. + currentFiber = fiber; + if (!beginFiberMark(fiber, null)) { return; } + fiber._debugIsCurrentlyTiming = true; } } - function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // Remember we shouldn't complete measurement for this fiber. + } // Remember we shouldn't complete measurement for this fiber. // Otherwise flamechart will be deep even for small updates. + fiber._debugIsCurrentlyTiming = false; clearFiberMark(fiber, null); } } - function stopWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; endFiberMark(fiber, null, null); } } - function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; - } - // If we pause, its parent is the fiber to unwind from. + } // If we pause, its parent is the fiber to unwind from. + currentFiber = fiber.return; + if (!fiber._debugIsCurrentlyTiming) { return; } + fiber._debugIsCurrentlyTiming = false; var warning = - fiber.tag === SuspenseComponent || - fiber.tag === DehydratedSuspenseComponent + fiber.tag === SuspenseComponent ? "Rendering was suspended" : "An error was thrown inside this error boundary"; endFiberMark(fiber, null, warning); } } - function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + clearPendingPhaseMeasurement(); + if (!beginFiberMark(fiber, phase)) { return; } + currentPhaseFiber = fiber; currentPhase = phase; } } - function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? "Scheduled a cascading update" : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } + currentPhase = null; currentPhaseFiber = null; } } - function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; + if (!supportsUserTiming) { return; } - commitCountInCurrentWorkLoop = 0; - // This is top level call. + + commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. - beginMark("(React Tree Reconciliation)"); - // Resume any measurements that were in progress during the last loop. + + beginMark("(React Tree Reconciliation)"); // Resume any measurements that were in progress during the last loop. + resumeTimers(); } } - function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var warning = null; + if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = "A top-level update interrupted the previous render"; @@ -4922,28 +5008,28 @@ function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { } else if (commitCountInCurrentWorkLoop > 1) { warning = "There were cascading updates"; } + commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? "(React Tree Reconciliation: Completed Root)" - : "(React Tree Reconciliation: Yielded)"; - // Pause any measurements until the next loop. + : "(React Tree Reconciliation: Yielded)"; // Pause any measurements until the next loop. + pauseTimers(); endMark(label, "(React Tree Reconciliation)", warning); } } - function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark("(Committing Changes)"); } } - function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { @@ -4951,35 +5037,36 @@ function stopCommitTimer() { } var warning = null; + if (hasScheduledUpdateInCurrentCommit) { warning = "Lifecycle hook scheduled a cascading update"; } else if (commitCountInCurrentWorkLoop > 0) { warning = "Caused by a cascading update in earlier commit"; } + hasScheduledUpdateInCurrentCommit = false; commitCountInCurrentWorkLoop++; isCommitting = false; labelsInCurrentCommit.clear(); - endMark("(Committing Changes)", "(Committing Changes)", warning); } } - function startCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Snapshot Effects)"); } } - function stopCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -4989,22 +5076,22 @@ function stopCommitSnapshotEffectsTimer() { ); } } - function startCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Committing Host Effects)"); } } - function stopCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5014,22 +5101,22 @@ function stopCommitHostEffectsTimer() { ); } } - function startCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + effectCountInCurrentCommit = 0; beginMark("(Calling Lifecycle Methods)"); } } - function stopCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } + var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark( @@ -5041,8 +5128,7 @@ function stopCommitLifeCyclesTimer() { } var valueStack = []; - -var fiberStack = void 0; +var fiberStack; { fiberStack = []; @@ -5061,6 +5147,7 @@ function pop(cursor, fiber) { { warningWithoutStack$1(false, "Unexpected pop."); } + return; } @@ -5071,7 +5158,6 @@ function pop(cursor, fiber) { } cursor.current = valueStack[index]; - valueStack[index] = null; { @@ -5083,7 +5169,6 @@ function pop(cursor, fiber) { function push(cursor, value, fiber) { index++; - valueStack[index] = cursor.current; { @@ -5093,24 +5178,24 @@ function push(cursor, value, fiber) { cursor.current = value; } -var warnedAboutMissingGetChildContext = void 0; +var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; + { Object.freeze(emptyContextObject); -} +} // A cursor to the current merged context object on the stack. + +var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. -// A cursor to the current merged context object on the stack. -var contextStackCursor = createCursor(emptyContextObject); -// A cursor to a boolean indicating whether the context has changed. -var didPerformWorkStackCursor = createCursor(false); -// Keep track of the previous context object that was on the stack. +var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. + var previousContext = emptyContextObject; function getUnmaskedContext( @@ -5128,6 +5213,7 @@ function getUnmaskedContext( // previous (parent) context instead for a context provider. return previousContext; } + return contextStackCursor.current; } } @@ -5148,14 +5234,15 @@ function getMaskedContext(workInProgress, unmaskedContext) { } else { var type = workInProgress.type; var contextTypes = type.contextTypes; + if (!contextTypes) { return emptyContextObject; - } - - // Avoid recreating masked context unless unmasked context has changed. + } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. + var instance = workInProgress.stateNode; + if ( instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext @@ -5164,6 +5251,7 @@ function getMaskedContext(workInProgress, unmaskedContext) { } var context = {}; + for (var key in contextTypes) { context[key] = unmaskedContext[key]; } @@ -5177,10 +5265,9 @@ function getMaskedContext(workInProgress, unmaskedContext) { name, getCurrentFiberStackInDev ); - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. + if (instance) { cacheContext(workInProgress, unmaskedContext, context); } @@ -5228,15 +5315,11 @@ function pushTopLevelContextObject(fiber, context, didChange) { if (disableLegacyContext) { return; } else { - (function() { - if (!(contextStackCursor.current === emptyContextObject)) { - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(contextStackCursor.current === emptyContextObject)) { + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." + ); + } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -5248,10 +5331,9 @@ function processChildContext(fiber, type, parentContext) { return parentContext; } else { var instance = fiber.stateNode; - var childContextTypes = type.childContextTypes; - - // TODO (bvaughn) Replace this behavior with an invariant() in the future. + var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== "function") { { var componentName = getComponentName(type) || "Unknown"; @@ -5268,41 +5350,42 @@ function processChildContext(fiber, type, parentContext) { ); } } + return parentContext; } - var childContext = void 0; + var childContext; + { setCurrentPhase("getChildContext"); } + startPhaseTimer(fiber, "getChildContext"); childContext = instance.getChildContext(); stopPhaseTimer(); + { setCurrentPhase(null); } + for (var contextKey in childContext) { - (function() { - if (!(contextKey in childContextTypes)) { - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) - ); - } - })(); + if (!(contextKey in childContextTypes)) { + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } } + { var name = getComponentName(type) || "Unknown"; checkPropTypes( childContextTypes, childContext, "child context", - name, - // In practice, there is one case in which we won't get a stack. It's when + name, // In practice, there is one case in which we won't get a stack. It's when // somebody calls unstable_renderSubtreeIntoContainer() and we process // context from the parent component instance. The stack will be missing // because it's outside of the reconciliation, and so the pointer has not @@ -5311,7 +5394,7 @@ function processChildContext(fiber, type, parentContext) { ); } - return Object.assign({}, parentContext, childContext); + return Object.assign({}, parentContext, {}, childContext); } } @@ -5319,16 +5402,15 @@ function pushContextProvider(workInProgress) { if (disableLegacyContext) { return false; } else { - var instance = workInProgress.stateNode; - // We push the context as early as possible to ensure stack integrity. + var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. + var memoizedMergedChildContext = (instance && instance.__reactInternalMemoizedMergedChildContext) || - emptyContextObject; - - // Remember the parent context so we can merge with it later. + emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. + previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push( @@ -5336,7 +5418,6 @@ function pushContextProvider(workInProgress) { didPerformWorkStackCursor.current, workInProgress ); - return true; } } @@ -5346,15 +5427,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { return; } else { var instance = workInProgress.stateNode; - (function() { - if (!instance) { - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!instance) { + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." + ); + } if (didChange) { // Merge parent and own context. @@ -5365,13 +5443,12 @@ function invalidateContextProvider(workInProgress, type, didChange) { type, previousContext ); - instance.__reactInternalMemoizedMergedChildContext = mergedContext; - - // Replace the old (or empty) context with the new one. + instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. + pop(didPerformWorkStackCursor, workInProgress); - pop(contextStackCursor, workInProgress); - // Now push the new context and mark that it has changed. + pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. + push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { @@ -5387,40 +5464,38 @@ function findCurrentUnmaskedContext(fiber) { } else { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - (function() { - if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + 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." + ); + } var node = fiber; + do { switch (node.tag) { case HostRoot: return node.stateNode.context; + case ClassComponent: { var Component = node.type; + if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } + break; } } + node = node.return; } while (node !== null); - (function() { - { - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } } @@ -5428,43 +5503,6 @@ var LegacyRoot = 0; var BatchedRoot = 1; var ConcurrentRoot = 2; -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warning = warningWithoutStack$1; - -{ - warning = function(condition, format) { - if (condition) { - return; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - // eslint-disable-next-line react-internal/warning-and-invariant-args - - for ( - var _len = arguments.length, - args = Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key]; - } - - warningWithoutStack$1.apply( - undefined, - [false, format + "%s"].concat(args, [stack]) - ); - }; -} - -var warning$1 = warning; - // Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority; @@ -5485,77 +5523,69 @@ if (enableSchedulerTracing) { // Provide explicit error message when production+profiling bundle of e.g. // react-dom is used with production (non-profiling) bundle of // scheduler/tracing - (function() { - if ( - !( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null - ) - ) { - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) - ); - } - })(); + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + 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" + ); + } } -var fakeCallbackNode = {}; - -// Except for NoPriority, these correspond to Scheduler priorities. We use +var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use // ascending numbers so we can compare them like numbers. They start at 90 to // avoid clashing with Scheduler's priorities. + var ImmediatePriority = 99; var UserBlockingPriority = 98; var NormalPriority = 97; var LowPriority = 96; -var IdlePriority = 95; -// NoPriority is the absence of priority. Also React-only. -var NoPriority = 90; +var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only. +var NoPriority = 90; var shouldYield = Scheduler_shouldYield; -var requestPaint = - // Fall back gracefully if we're running an older version of Scheduler. +var requestPaint = // Fall back gracefully if we're running an older version of Scheduler. Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function() {}; - var syncQueue = null; var immediateQueueCallbackNode = null; var isFlushingSyncQueue = false; -var initialTimeMs = Scheduler_now(); - -// If the initial timestamp is reasonably small, use Scheduler's `now` directly. +var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly. // This will be the case for modern browsers that support `performance.now`. In // older browsers, Scheduler falls back to `Date.now`, which returns a Unix // timestamp. In that case, subtract the module initialization time to simulate // the behavior of performance.now and keep our times small enough to fit // within 32 bits. // TODO: Consider lifting this into Scheduler. + var now = initialTimeMs < 10000 ? Scheduler_now : function() { return Scheduler_now() - initialTimeMs; }; - function getCurrentPriorityLevel() { switch (Scheduler_getCurrentPriorityLevel()) { case Scheduler_ImmediatePriority: return ImmediatePriority; + case Scheduler_UserBlockingPriority: return UserBlockingPriority; + case Scheduler_NormalPriority: return NormalPriority; + case Scheduler_LowPriority: return LowPriority; + case Scheduler_IdlePriority: return IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5563,20 +5593,22 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { switch (reactPriorityLevel) { case ImmediatePriority: return Scheduler_ImmediatePriority; + case UserBlockingPriority: return Scheduler_UserBlockingPriority; + case NormalPriority: return Scheduler_NormalPriority; + case LowPriority: return Scheduler_LowPriority; + case IdlePriority: return Scheduler_IdlePriority; - default: - (function() { - { - throw ReactError(Error("Unknown priority level.")); - } - })(); + + default: { + throw Error("Unknown priority level."); + } } } @@ -5584,18 +5616,16 @@ function runWithPriority(reactPriorityLevel, fn) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_runWithPriority(priorityLevel, fn); } - function scheduleCallback(reactPriorityLevel, callback, options) { var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); return Scheduler_scheduleCallback(priorityLevel, callback, options); } - function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { - syncQueue = [callback]; - // Flush the queue in the next tick, at the earliest. + syncQueue = [callback]; // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl @@ -5605,19 +5635,21 @@ function scheduleSyncCallback(callback) { // we already scheduled one when we created the queue. syncQueue.push(callback); } + return fakeCallbackNode; } - function cancelCallback(callbackNode) { if (callbackNode !== fakeCallbackNode) { Scheduler_cancelCallback(callbackNode); } } - function flushSyncCallbackQueue() { if (immediateQueueCallbackNode !== null) { - Scheduler_cancelCallback(immediateQueueCallbackNode); + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); } + flushSyncCallbackQueueImpl(); } @@ -5626,12 +5658,14 @@ function flushSyncCallbackQueueImpl() { // Prevent re-entrancy. isFlushingSyncQueue = true; var i = 0; + try { var _isSync = true; var queue = syncQueue; runWithPriority(ImmediatePriority, function() { for (; i < queue.length; i++) { var callback = queue[i]; + do { callback = callback(_isSync); } while (callback !== null); @@ -5642,8 +5676,8 @@ function flushSyncCallbackQueueImpl() { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); - } - // Resume flushing in the next tick + } // Resume flushing in the next tick + Scheduler_scheduleCallback( Scheduler_ImmediatePriority, flushSyncCallbackQueue @@ -5656,9 +5690,9 @@ function flushSyncCallbackQueueImpl() { } var NoMode = 0; -var StrictMode = 1; -// TODO: Remove BatchedMode and ConcurrentMode by reading from the root +var StrictMode = 1; // TODO: Remove BatchedMode and ConcurrentMode by reading from the root // tag instead + var BatchedMode = 2; var ConcurrentMode = 4; var ProfileMode = 8; @@ -5668,20 +5702,27 @@ var ProfileMode = 8; // 0b111111111111111111111111111111 var MAX_SIGNED_31_BIT_INT = 1073741823; -var NoWork = 0; -var Never = 1; +var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that +// Never work can be committed in an inconsistent state without tearing the UI. +// The main example is offscreen content, like a hidden subtree. So one possible +// name is Offscreen. However, it also includes dehydrated Suspense boundaries, +// which are inconsistent in the sense that they haven't finished yet, but +// aren't visibly inconsistent because the server rendered HTML matches what the +// hydrated tree would look like. + +var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in +// order to be consistent. + +var Idle = 2; // Continuous Hydration is a moving priority. It is slightly higher than Idle var Sync = MAX_SIGNED_31_BIT_INT; var Batched = Sync - 1; - var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = Batched - 1; +var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms. -// 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0); } - function expirationTimeToMs(expirationTime) { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } @@ -5698,13 +5739,11 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { bucketSizeMs / UNIT_SIZE ) ); -} - -// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update +} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update // the names to reflect. + var LOW_PRIORITY_EXPIRATION = 5000; var LOW_PRIORITY_BATCH_SIZE = 250; - function computeAsyncExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -5712,7 +5751,6 @@ function computeAsyncExpiration(currentTime) { LOW_PRIORITY_BATCH_SIZE ); } - function computeSuspenseExpiration(currentTime, timeoutMs) { // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time? return computeExpirationBucket( @@ -5720,9 +5758,7 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { timeoutMs, LOW_PRIORITY_BATCH_SIZE ); -} - -// We intentionally set a higher expiration time for interactive updates in +} // We intentionally set a higher expiration time for interactive updates in // dev than in production. // // If the main thread is being blocked so long that you hit the expiration, @@ -5733,9 +5769,9 @@ function computeSuspenseExpiration(currentTime, timeoutMs) { // // In production we opt for better UX at the risk of masking scheduling // problems, by expiring fast. + var HIGH_PRIORITY_EXPIRATION = 500; var HIGH_PRIORITY_BATCH_SIZE = 100; - function computeInteractiveExpiration(currentTime) { return computeExpirationBucket( currentTime, @@ -5748,24 +5784,27 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (expirationTime === Sync) { return ImmediatePriority; } - if (expirationTime === Never) { + + if (expirationTime === Never || expirationTime === Idle) { return IdlePriority; } + var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime); + if (msUntil <= 0) { return ImmediatePriority; } + if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) { return UserBlockingPriority; } + if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) { return NormalPriority; - } - - // TODO: Handle LowPriority - + } // TODO: Handle LowPriority // Assume anything lower has idle priority + return IdlePriority; } @@ -5779,15 +5818,17 @@ function is(x, y) { ); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = typeof Object.is === "function" ? Object.is : is; +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ + function shallowEqual(objA, objB) { - if (is(objA, objB)) { + if (is$1(objA, objB)) { return true; } @@ -5805,13 +5846,12 @@ function shallowEqual(objA, objB) { if (keysA.length !== keysB.length) { return false; - } + } // Test for A's keys different from B. - // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if ( !hasOwnProperty.call(objB, keysA[i]) || - !is(objA[keysA[i]], objB[keysA[i]]) + !is$1(objA[keysA[i]], objB[keysA[i]]) ) { return false; } @@ -5833,14 +5873,13 @@ function shallowEqual(objA, objB) { * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ - -var lowPriorityWarning = function() {}; +var lowPriorityWarningWithoutStack = function() {}; { var printWarning = function(format) { for ( var _len = arguments.length, - args = Array(_len > 1 ? _len - 1 : 0), + args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ @@ -5854,9 +5893,11 @@ var lowPriorityWarning = function() {}; format.replace(/%s/g, function() { return args[argIndex++]; }); + if (typeof console !== "undefined") { console.warn(message); } + try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack @@ -5865,17 +5906,18 @@ var lowPriorityWarning = function() {}; } catch (x) {} }; - lowPriorityWarning = function(condition, format) { + lowPriorityWarningWithoutStack = function(condition, format) { if (format === undefined) { throw new Error( - "`lowPriorityWarning(condition, format, ...args)` requires a warning " + + "`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning " + "message argument" ); } + if (!condition) { for ( var _len2 = arguments.length, - args = Array(_len2 > 2 ? _len2 - 2 : 0), + args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++ @@ -5883,12 +5925,12 @@ var lowPriorityWarning = function() {}; args[_key2 - 2] = arguments[_key2]; } - printWarning.apply(undefined, [format].concat(args)); + printWarning.apply(void 0, [format].concat(args)); } }; } -var lowPriorityWarning$1 = lowPriorityWarning; +var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack; var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function(fiber, instance) {}, @@ -5901,12 +5943,13 @@ var ReactStrictModeWarnings = { { var findStrictRoot = function(fiber) { var maybeStrictRoot = null; - var node = fiber; + while (node !== null) { if (node.mode & StrictMode) { maybeStrictRoot = node; } + node = node.return; } @@ -5926,9 +5969,8 @@ var ReactStrictModeWarnings = { var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; - var pendingUNSAFE_ComponentWillUpdateWarnings = []; + var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function( @@ -5941,8 +5983,7 @@ var ReactStrictModeWarnings = { } if ( - typeof instance.componentWillMount === "function" && - // Don't warn about react-lifecycles-compat polyfilled components. + typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true ) { pendingComponentWillMountWarnings.push(fiber); @@ -5987,6 +6028,7 @@ var ReactStrictModeWarnings = { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); + if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function(fiber) { componentWillMountUniqueNames.add( @@ -5998,6 +6040,7 @@ var ReactStrictModeWarnings = { } var UNSAFE_componentWillMountUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) { UNSAFE_componentWillMountUniqueNames.add( @@ -6009,6 +6052,7 @@ var ReactStrictModeWarnings = { } var componentWillReceivePropsUniqueNames = new Set(); + if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function(fiber) { componentWillReceivePropsUniqueNames.add( @@ -6016,11 +6060,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add( @@ -6028,11 +6072,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); + if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function(fiber) { componentWillUpdateUniqueNames.add( @@ -6040,11 +6084,11 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); + if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) { UNSAFE_componentWillUpdateUniqueNames.add( @@ -6052,18 +6096,16 @@ var ReactStrictModeWarnings = { ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); - pendingUNSAFE_ComponentWillUpdateWarnings = []; - } - - // Finally, we flush all the warnings + } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' + if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); warningWithoutStack$1( false, "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6074,11 +6116,12 @@ var ReactStrictModeWarnings = { var _sortedNames = setToSortedString( UNSAFE_componentWillReceivePropsUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6092,11 +6135,12 @@ var ReactStrictModeWarnings = { var _sortedNames2 = setToSortedString( UNSAFE_componentWillUpdateUniqueNames ); + warningWithoutStack$1( false, "Using UNSAFE_componentWillUpdate in strict mode is not recommended " + "and may indicate bugs in your code. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 @@ -6106,10 +6150,10 @@ var ReactStrictModeWarnings = { if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillMount has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6125,10 +6169,10 @@ var ReactStrictModeWarnings = { componentWillReceivePropsUniqueNames ); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillReceiveProps has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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 " + @@ -6145,10 +6189,10 @@ var ReactStrictModeWarnings = { if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); - lowPriorityWarning$1( + lowPriorityWarningWithoutStack$1( false, "componentWillUpdate has been renamed, and is not recommended for use. " + - "See https://fb.me/react-async-component-lifecycle-hooks for details.\n\n" + + "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. " + @@ -6160,9 +6204,8 @@ var ReactStrictModeWarnings = { } }; - var pendingLegacyContextWarning = new Map(); + var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. - // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function( @@ -6170,6 +6213,7 @@ var ReactStrictModeWarnings = { instance ) { var strictRoot = findStrictRoot(fiber); + if (strictRoot === null) { warningWithoutStack$1( false, @@ -6177,9 +6221,8 @@ var ReactStrictModeWarnings = { "This error is likely caused by a bug in React. Please file an issue." ); return; - } + } // Dedup strategy: Warn once per component. - // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } @@ -6195,6 +6238,7 @@ var ReactStrictModeWarnings = { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } + warningsForRoot.push(fiber); } }; @@ -6206,20 +6250,18 @@ var ReactStrictModeWarnings = { uniqueNames.add(getComponentName(fiber.type) || "Component"); didWarnAboutLegacyContext.add(fiber.type); }); - var sortedNames = setToSortedString(uniqueNames); var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); - warningWithoutStack$1( false, - "Legacy context API has been detected within a strict-mode tree: %s" + + "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:" + - "\nhttps://fb.me/react-legacy-context", - strictRootComponentStack, - sortedNames + "\n\nLearn more about this warning here: https://fb.me/react-legacy-context" + + "%s", + sortedNames, + strictRootComponentStack ); }); }; @@ -6235,47 +6277,43 @@ var ReactStrictModeWarnings = { }; } -// Resolves type to a family. - -// Used by React Refresh runtime through DevTools Global Hook. +var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. -var resolveFamily = null; -// $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; - var setRefreshHandler = function(handler) { { resolveFamily = handler; } }; - function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } - function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } + var family = resolveFamily(type); + if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if ( @@ -6287,24 +6325,27 @@ function resolveForwardRefForHotReloading(type) { // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); + if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; + if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } + return syntheticType; } } + return type; - } - // Use the latest known implementation. + } // Use the latest known implementation. + return family.current; } } - function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { @@ -6313,11 +6354,9 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } var prevType = fiber.elementType; - var nextType = element.type; + var nextType = element.type; // If we got here, we know types aren't === equal. - // If we got here, we know types aren't === equal. var needsCompareFamilies = false; - var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof @@ -6328,8 +6367,10 @@ function isCompatibleFamilyForHotReloading(fiber, element) { if (typeof nextType === "function") { needsCompareFamilies = true; } + break; } + case FunctionComponent: { if (typeof nextType === "function") { needsCompareFamilies = true; @@ -6340,16 +6381,20 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } + break; } + case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { @@ -6359,13 +6404,14 @@ function isCompatibleFamilyForHotReloading(fiber, element) { } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } + break; } + default: return false; - } + } // Check if both types have a family and it's the same one. - // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. @@ -6373,50 +6419,52 @@ function isCompatibleFamilyForHotReloading(fiber, element) { // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } + return false; } } - function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } + if (typeof WeakSet !== "function") { return; } + if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } + failedBoundaries.add(fiber); } } - var scheduleRefresh = function(root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } - var _staleFamilies = update.staleFamilies, - _updatedFamilies = update.updatedFamilies; + var staleFamilies = update.staleFamilies, + updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function() { scheduleFibersWithFamiliesRecursively( root.current, - _updatedFamilies, - _staleFamilies + updatedFamilies, + staleFamilies ); }); } }; - var scheduleRoot = function(root, element) { { if (root.context !== emptyContextObject) { @@ -6425,8 +6473,11 @@ var scheduleRoot = function(root, element) { // Just ignore. We'll delete this with _renderSubtree code path later. return; } + flushPassiveEffects(); - updateContainerAtExpirationTime(element, root, null, Sync, null); + syncUpdates(function() { + updateContainer(element, root, null, null); + }); } }; @@ -6441,17 +6492,19 @@ function scheduleFibersWithFamiliesRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } @@ -6462,8 +6515,10 @@ function scheduleFibersWithFamiliesRecursively( var needsRender = false; var needsRemount = false; + if (candidateType !== null) { var family = resolveFamily(candidateType); + if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; @@ -6476,6 +6531,7 @@ function scheduleFibersWithFamiliesRecursively( } } } + if (failedBoundaries !== null) { if ( failedBoundaries.has(fiber) || @@ -6488,9 +6544,11 @@ function scheduleFibersWithFamiliesRecursively( if (needsRemount) { fiber._debugNeedsRemount = true; } + if (needsRemount || needsRender) { scheduleWork(fiber, Sync); } + if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively( child, @@ -6498,6 +6556,7 @@ function scheduleFibersWithFamiliesRecursively( staleFamilies ); } + if (sibling !== null) { scheduleFibersWithFamiliesRecursively( sibling, @@ -6535,22 +6594,25 @@ function findHostInstancesForMatchingFibersRecursively( sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; - var candidateType = null; + switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; + case ForwardRef: candidateType = type.render; break; + default: break; } var didMatch = false; + if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; @@ -6589,26 +6651,32 @@ function findHostInstancesForFiberShallowly(fiber, hostInstances) { fiber, hostInstances ); + if (foundHostInstances) { return; - } - // If we didn't find any host children, fallback to closest host parent. + } // If we didn't find any host children, fallback to closest host parent. + var node = fiber; + while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; + case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; + case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } + if (node.return === null) { throw new Error("Expected to reach root first."); } + node = node.return; } } @@ -6618,30 +6686,35 @@ function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; + while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; - hostInstances.add(node.stateNode); - // There may still be more, so keep searching. + hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === fiber) { return foundHostInstances; } + while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } + return false; } @@ -6650,78 +6723,31 @@ function resolveDefaultProps(Component, baseProps) { // Resolve default props. Taken from ReactElement var props = Object.assign({}, baseProps); var defaultProps = Component.defaultProps; + for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } + return props; } + return baseProps; } - function readLazyComponentType(lazyComponent) { - var status = lazyComponent._status; - var result = lazyComponent._result; - switch (status) { - case Resolved: { - var Component = result; - return Component; - } - case Rejected: { - var error = result; - throw error; - } - case Pending: { - var thenable = result; - throw thenable; - } - default: { - lazyComponent._status = Pending; - var ctor = lazyComponent._ctor; - var _thenable = ctor(); - _thenable.then( - function(moduleObject) { - if (lazyComponent._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === undefined) { - 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 - ); - } - } - lazyComponent._status = Resolved; - lazyComponent._result = defaultExport; - } - }, - function(error) { - if (lazyComponent._status === Pending) { - lazyComponent._status = Rejected; - lazyComponent._result = error; - } - } - ); - // Handle synchronous thenables. - switch (lazyComponent._status) { - case Resolved: - return lazyComponent._result; - case Rejected: - throw lazyComponent._result; - } - lazyComponent._result = _thenable; - throw _thenable; - } + initializeLazyComponentType(lazyComponent); + + if (lazyComponent._status !== Resolved) { + throw lazyComponent._result; } + + return lazyComponent._result; } var valueCursor = createCursor(null); +var rendererSigil; -var rendererSigil = void 0; { // Use this to detect multiple renderers using the same context rendererSigil = {}; @@ -6730,39 +6756,35 @@ var rendererSigil = void 0; var currentlyRenderingFiber = null; var lastContextDependency = null; var lastContextWithAllBitsObserved = null; - var isDisallowedContextReadInDEV = false; - function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; + { isDisallowedContextReadInDEV = false; } } - function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } - function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } - function pushProvider(providerFiber, nextValue) { var context = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); - context._currentValue = nextValue; + { !( context._currentRenderer === undefined || @@ -6779,8 +6801,8 @@ function pushProvider(providerFiber, nextValue) { } } else { push(valueCursor, context._currentValue2, providerFiber); - context._currentValue2 = nextValue; + { !( context._currentRenderer2 === undefined || @@ -6797,22 +6819,19 @@ function pushProvider(providerFiber, nextValue) { } } } - function popProvider(providerFiber) { var currentValue = valueCursor.current; - pop(valueCursor, providerFiber); - var context = providerFiber.type._context; + if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } - function calculateChangedBits(context, newValue, oldValue) { - if (is(oldValue, newValue)) { + if (is$1(oldValue, newValue)) { // No change return 0; } else { @@ -6831,18 +6850,21 @@ function calculateChangedBits(context, newValue, oldValue) { ) : void 0; } + return changedBits | 0; } } - function scheduleWorkOnParentPath(parent, renderExpirationTime) { // Update the child expiration time of all the ancestors, including // the alternates. var node = parent; + while (node !== null) { var alternate = node.alternate; + if (node.childExpirationTime < renderExpirationTime) { node.childExpirationTime = renderExpirationTime; + if ( alternate !== null && alternate.childExpirationTime < renderExpirationTime @@ -6859,10 +6881,10 @@ function scheduleWorkOnParentPath(parent, renderExpirationTime) { // ancestor path already has sufficient priority. break; } + node = node.return; } } - function propagateContextChange( workInProgress, context, @@ -6870,19 +6892,21 @@ function propagateContextChange( renderExpirationTime ) { var fiber = workInProgress.child; + if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } + while (fiber !== null) { - var nextFiber = void 0; + var nextFiber = void 0; // Visit this fiber. - // Visit this fiber. var list = fiber.dependencies; + if (list !== null) { nextFiber = fiber.child; - var dependency = list.firstContext; + while (dependency !== null) { // Check if the context matches. if ( @@ -6890,22 +6914,23 @@ function propagateContextChange( (dependency.observedBits & changedBits) !== 0 ) { // Match! Schedule an update on this fiber. - if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var update = createUpdate(renderExpirationTime, null); - update.tag = ForceUpdate; - // TODO: Because we don't have a work-in-progress, this will add the + update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. + enqueueUpdate(fiber, update); } if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } + var alternate = fiber.alternate; + if ( alternate !== null && alternate.expirationTime < renderExpirationTime @@ -6913,17 +6938,16 @@ function propagateContextChange( alternate.expirationTime = renderExpirationTime; } - scheduleWorkOnParentPath(fiber.return, renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. - // Mark the expiration time on the list, too. if (list.expirationTime < renderExpirationTime) { list.expirationTime = renderExpirationTime; - } - - // Since we already found a match, we can stop traversing the + } // Since we already found a match, we can stop traversing the // dependency list. + break; } + dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { @@ -6931,26 +6955,36 @@ function propagateContextChange( nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if ( enableSuspenseServerRenderer && - fiber.tag === DehydratedSuspenseComponent + fiber.tag === DehydratedFragment ) { - // If a dehydrated suspense component is in this subtree, we don't know + // If a dehydrated suspense bounudary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is - // mark it as having updates on its children. - if (fiber.expirationTime < renderExpirationTime) { - fiber.expirationTime = renderExpirationTime; + // mark it as having updates. + var parentSuspense = fiber.return; + + if (!(parentSuspense !== null)) { + throw Error( + "We just came from a parent so we must have had a parent. This is a bug in React." + ); + } + + if (parentSuspense.expirationTime < renderExpirationTime) { + parentSuspense.expirationTime = renderExpirationTime; } - var _alternate = fiber.alternate; + + var _alternate = parentSuspense.alternate; + if ( _alternate !== null && _alternate.expirationTime < renderExpirationTime ) { _alternate.expirationTime = renderExpirationTime; - } - // This is intentionally passing this fiber as the parent + } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. - scheduleWorkOnParentPath(fiber, renderExpirationTime); + + scheduleWorkOnParentPath(parentSuspense, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. @@ -6963,46 +6997,49 @@ function propagateContextChange( } else { // No child. Traverse to next sibling. nextFiber = fiber; + while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } + var sibling = nextFiber.sibling; + if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; - } - // No more siblings. Traverse up. + } // No more siblings. Traverse up. + nextFiber = nextFiber.return; } } + fiber = nextFiber; } } - function prepareToReadContext(workInProgress, renderExpirationTime) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; - var dependencies = workInProgress.dependencies; + if (dependencies !== null) { var firstContext = dependencies.firstContext; + if (firstContext !== null) { if (dependencies.expirationTime >= renderExpirationTime) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); - } - // Reset the work-in-progress list + } // Reset the work-in-progress list + dependencies.firstContext = null; } } } - function readContext(context, observedBits) { { // This warning would fire if you read context inside a Hook like useMemo. @@ -7023,7 +7060,8 @@ function readContext(context, observedBits) { } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { - var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. + var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types. + if ( typeof observedBits !== "number" || observedBits === MAX_SIGNED_31_BIT_INT @@ -7042,17 +7080,12 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - (function() { - if (!(currentlyRenderingFiber !== null)) { - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) - ); - } - })(); + if (!(currentlyRenderingFiber !== null)) { + 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()." + ); + } // This is the first dependency for this component. Create a new list. - // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { expirationTime: NoWork, @@ -7064,6 +7097,7 @@ function readContext(context, observedBits) { lastContextDependency = lastContextDependency.next = contextItem; } } + return isPrimaryRenderer ? context._currentValue : context._currentValue2; } @@ -7143,19 +7177,16 @@ function readContext(context, observedBits) { // updates when preceding updates are skipped, the final result is deterministic // regardless of priority. Intermediate state may vary according to system // resources, but the final state is always the same. - var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; -var CaptureUpdate = 3; - -// Global state that is reset at the beginning of calling `processUpdateQueue`. +var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. -var hasForceUpdate = false; -var didWarnUpdateInsideUpdate = void 0; -var currentlyProcessingQueue = void 0; +var hasForceUpdate = false; +var didWarnUpdateInsideUpdate; +var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; @@ -7182,15 +7213,12 @@ function cloneUpdateQueue(currentQueue) { baseState: currentQueue.baseState, firstUpdate: currentQueue.firstUpdate, lastUpdate: currentQueue.lastUpdate, - // TODO: With resuming, if we bail out and resuse the child tree, we should // keep these effects. firstCapturedUpdate: null, lastCapturedUpdate: null, - firstEffect: null, lastEffect: null, - firstCapturedEffect: null, lastCapturedEffect: null }; @@ -7201,17 +7229,17 @@ function createUpdate(expirationTime, suspenseConfig) { var update = { expirationTime: expirationTime, suspenseConfig: suspenseConfig, - tag: UpdateState, payload: null, callback: null, - next: null, nextEffect: null }; + { update.priority = getCurrentPriorityLevel(); } + return update; } @@ -7229,12 +7257,14 @@ function appendUpdateToQueue(queue, update) { function enqueueUpdate(fiber, update) { // Update queues are created lazily. var alternate = fiber.alternate; - var queue1 = void 0; - var queue2 = void 0; + var queue1; + var queue2; + if (alternate === null) { // There's only one fiber. queue1 = fiber.updateQueue; queue2 = null; + if (queue1 === null) { queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); } @@ -7242,6 +7272,7 @@ function enqueueUpdate(fiber, update) { // There are two owners. queue1 = fiber.updateQueue; queue2 = alternate.updateQueue; + if (queue1 === null) { if (queue2 === null) { // Neither fiber has an update queue. Create new ones. @@ -7262,6 +7293,7 @@ function enqueueUpdate(fiber, update) { } } } + if (queue2 === null || queue1 === queue2) { // There's only a single queue. appendUpdateToQueue(queue1, update); @@ -7276,8 +7308,8 @@ function enqueueUpdate(fiber, update) { } else { // Both queues are non-empty. The last update is the same in both lists, // because of structural sharing. So, only append to one of the lists. - appendUpdateToQueue(queue1, update); - // But we still need to update the `lastUpdate` pointer of queue2. + appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2. + queue2.lastUpdate = update; } } @@ -7300,11 +7332,11 @@ function enqueueUpdate(fiber, update) { } } } - function enqueueCapturedUpdate(workInProgress, update) { // Captured updates go into a separate list, and only on the work-in- // progress queue. var workInProgressQueue = workInProgress.updateQueue; + if (workInProgressQueue === null) { workInProgressQueue = workInProgress.updateQueue = createUpdateQueue( workInProgress.memoizedState @@ -7317,9 +7349,8 @@ function enqueueCapturedUpdate(workInProgress, update) { workInProgress, workInProgressQueue ); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. if (workInProgressQueue.lastCapturedUpdate === null) { // This is the first render phase update workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update; @@ -7331,6 +7362,7 @@ function enqueueCapturedUpdate(workInProgress, update) { function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { var current = workInProgress.alternate; + if (current !== null) { // If the work-in-progress queue is equal to the current queue, // we need to clone it first. @@ -7338,6 +7370,7 @@ function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { queue = workInProgress.updateQueue = cloneUpdateQueue(queue); } } + return queue; } @@ -7351,68 +7384,82 @@ function getStateFromUpdate( ) { switch (update.tag) { case ReplaceState: { - var _payload = update.payload; - if (typeof _payload === "function") { + var payload = update.payload; + + if (typeof payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload.call(instance, prevState, nextProps); + payload.call(instance, prevState, nextProps); } } - var nextState = _payload.call(instance, prevState, nextProps); + + var nextState = payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } + return nextState; - } - // State object - return _payload; + } // State object + + return payload; } + case CaptureUpdate: { workInProgress.effectTag = (workInProgress.effectTag & ~ShouldCapture) | DidCapture; } // Intentional fallthrough + case UpdateState: { - var _payload2 = update.payload; - var partialState = void 0; - if (typeof _payload2 === "function") { + var _payload = update.payload; + var partialState; + + if (typeof _payload === "function") { // Updater function { enterDisallowedContextReadInDEV(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) ) { - _payload2.call(instance, prevState, nextProps); + _payload.call(instance, prevState, nextProps); } } - partialState = _payload2.call(instance, prevState, nextProps); + + partialState = _payload.call(instance, prevState, nextProps); + { exitDisallowedContextReadInDEV(); } } else { // Partial state object - partialState = _payload2; + partialState = _payload; } + if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + return Object.assign({}, prevState, partialState); } + case ForceUpdate: { hasForceUpdate = true; return prevState; } } + return prevState; } @@ -7424,50 +7471,47 @@ function processUpdateQueue( renderExpirationTime ) { hasForceUpdate = false; - queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue); { currentlyProcessingQueue = queue; - } + } // These values may change as we process the queue. - // These values may change as we process the queue. var newBaseState = queue.baseState; var newFirstUpdate = null; - var newExpirationTime = NoWork; + var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result. - // Iterate through the list of updates to compute the result. var update = queue.firstUpdate; var resultState = newBaseState; + while (update !== null) { var updateExpirationTime = update.expirationTime; + if (updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstUpdate === null) { // This is the first skipped update. It will be the first update in // the new list. - newFirstUpdate = update; - // Since this is the first update that was skipped, the current result + newFirstUpdate = update; // Since this is the first update that was skipped, the current result // is the new base state. + newBaseState = resultState; - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < updateExpirationTime) { newExpirationTime = updateExpirationTime; } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. // TODO: We should skip this update if it was already committed but currently // we have no way of detecting the difference between a committed and suspended // update here. - markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); + markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process it and compute a new result. - // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -7476,11 +7520,13 @@ function processUpdateQueue( props, instance ); - var _callback = update.callback; - if (_callback !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var callback = update.callback; + + if (callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastEffect === null) { queue.firstEffect = queue.lastEffect = update; } else { @@ -7488,30 +7534,31 @@ function processUpdateQueue( queue.lastEffect = update; } } - } - // Continue to the next update. + } // Continue to the next update. + update = update.next; - } + } // Separately, iterate though the list of captured updates. - // Separately, iterate though the list of captured updates. var newFirstCapturedUpdate = null; update = queue.firstCapturedUpdate; + while (update !== null) { var _updateExpirationTime = update.expirationTime; + if (_updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstCapturedUpdate === null) { // This is the first skipped captured update. It will be the first // update in the new list. - newFirstCapturedUpdate = update; - // If this is the first update that was skipped, the current result is + newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is // the new base state. + if (newFirstUpdate === null) { newBaseState = resultState; } - } - // Since this update will remain in the list, update the remaining + } // Since this update will remain in the list, update the remaining // expiration time. + if (newExpirationTime < _updateExpirationTime) { newExpirationTime = _updateExpirationTime; } @@ -7526,11 +7573,13 @@ function processUpdateQueue( props, instance ); - var _callback2 = update.callback; - if (_callback2 !== null) { - workInProgress.effectTag |= Callback; - // Set this to null, in case it was mutated during an aborted render. + var _callback = update.callback; + + if (_callback !== null) { + workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. + update.nextEffect = null; + if (queue.lastCapturedEffect === null) { queue.firstCapturedEffect = queue.lastCapturedEffect = update; } else { @@ -7539,17 +7588,20 @@ function processUpdateQueue( } } } + update = update.next; } if (newFirstUpdate === null) { queue.lastUpdate = null; } + if (newFirstCapturedUpdate === null) { queue.lastCapturedUpdate = null; } else { workInProgress.effectTag |= Callback; } + if (newFirstUpdate === null && newFirstCapturedUpdate === null) { // We processed every update, without skipping. That means the new base // state is the same as the result state. @@ -7558,15 +7610,15 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; - queue.firstCapturedUpdate = newFirstCapturedUpdate; - - // Set the remaining expiration time to be whatever is remaining in the queue. + queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. + + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; @@ -7576,27 +7628,22 @@ function processUpdateQueue( } function callCallback(callback, context) { - (function() { - if (!(typeof callback === "function")) { - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - callback - ) - ); - } - })(); + if (!(typeof callback === "function")) { + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } - function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } - function commitUpdateQueue( finishedWork, finishedQueue, @@ -7612,53 +7659,50 @@ function commitUpdateQueue( if (finishedQueue.lastUpdate !== null) { finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate; finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate; - } - // Clear the list of captured updates. + } // Clear the list of captured updates. + finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null; - } + } // Commit the effects - // Commit the effects commitUpdateEffects(finishedQueue.firstEffect, instance); finishedQueue.firstEffect = finishedQueue.lastEffect = null; - commitUpdateEffects(finishedQueue.firstCapturedEffect, instance); finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null; } function commitUpdateEffects(effect, instance) { while (effect !== null) { - var _callback3 = effect.callback; - if (_callback3 !== null) { + var callback = effect.callback; + + if (callback !== null) { effect.callback = null; - callCallback(_callback3, instance); + callCallback(callback, instance); } + effect = effect.nextEffect; } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; - function requestCurrentSuspenseConfig() { return ReactCurrentBatchConfig.suspense; } var fakeInternalInstance = {}; -var isArray$1 = Array.isArray; - -// React.Component uses a shared frozen object by default. +var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. -var emptyRefsObject = new React.Component().refs; -var didWarnAboutStateAssignmentForComponent = void 0; -var didWarnAboutUninitializedState = void 0; -var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; -var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; -var didWarnAboutUndefinedDerivedState = void 0; -var warnOnUndefinedDerivedState = void 0; -var warnOnInvalidCallback = void 0; -var didWarnAboutDirectlyAssigningPropsToState = void 0; -var didWarnAboutContextTypeAndContextTypes = void 0; -var didWarnAboutInvalidateContextType = void 0; +var emptyRefsObject = new React.Component().refs; +var didWarnAboutStateAssignmentForComponent; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; { didWarnAboutStateAssignmentForComponent = new Set(); @@ -7669,14 +7713,15 @@ var didWarnAboutInvalidateContextType = void 0; didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); - var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function(callback, callerName) { if (callback === null || typeof callback === "function") { return; } + var key = callerName + "_" + callback; + if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); warningWithoutStack$1( @@ -7692,6 +7737,7 @@ var didWarnAboutInvalidateContextType = void 0; warnOnUndefinedDerivedState = function(type, partialState) { if (partialState === undefined) { var componentName = getComponentName(type) || "Component"; + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); warningWithoutStack$1( @@ -7702,25 +7748,20 @@ var didWarnAboutInvalidateContextType = void 0; ); } } - }; - - // This is so gross but it's at least non-critical and can be removed if + }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. + Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - (function() { - { - throw ReactError( - Error( - "_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)." - ) - ); - } - })(); + { + 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)." + ); + } } }); Object.freeze(fakeInternalInstance); @@ -7749,22 +7790,21 @@ function applyDerivedStateFromProps( { warnOnUndefinedDerivedState(ctor, partialState); - } - // Merge the partial state and the previous state. + } // Merge the partial state and the previous state. + var memoizedState = partialState === null || partialState === undefined ? prevState : Object.assign({}, prevState, partialState); - workInProgress.memoizedState = memoizedState; - - // Once the update queue is empty, persist the derived state onto the + workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. + var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null && workInProgress.expirationTime === NoWork) { updateQueue.baseState = memoizedState; } } - var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { @@ -7776,19 +7816,17 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.payload = payload; + if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, "setState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -7801,7 +7839,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ReplaceState; update.payload = payload; @@ -7810,12 +7847,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "replaceState"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, @@ -7828,7 +7863,6 @@ var classComponentUpdater = { fiber, suspenseConfig ); - var update = createUpdate(expirationTime, suspenseConfig); update.tag = ForceUpdate; @@ -7836,12 +7870,10 @@ var classComponentUpdater = { { warnOnInvalidCallback(callback, "forceUpdate"); } + update.callback = callback; } - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); } @@ -7857,6 +7889,7 @@ function checkShouldComponentUpdate( nextContext ) { var instance = workInProgress.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { startPhaseTimer(workInProgress, "shouldComponentUpdate"); var shouldUpdate = instance.shouldComponentUpdate( @@ -7891,6 +7924,7 @@ function checkShouldComponentUpdate( function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; + { var name = getComponentName(ctor) || "Component"; var renderPresent = instance.render; @@ -7966,6 +8000,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (ctor.contextTypes) { warningWithoutStack$1( false, @@ -8012,6 +8047,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ) : void 0; + if ( ctor.prototype && ctor.prototype.isPureReactComponent && @@ -8025,6 +8061,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { getComponentName(ctor) || "A pure component" ); } + var noComponentDidUnmount = typeof instance.componentDidUnmount !== "function"; !noComponentDidUnmount @@ -8135,6 +8172,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { ) : void 0; var _state = instance.state; + if (_state && (typeof _state !== "object" || isArray$1(_state))) { warningWithoutStack$1( false, @@ -8142,6 +8180,7 @@ function checkClassInstance(workInProgress, ctor, newProps) { name ); } + if (typeof instance.getChildContext === "function") { !(typeof ctor.childContextTypes === "object") ? warningWithoutStack$1( @@ -8157,9 +8196,10 @@ function checkClassInstance(workInProgress, ctor, newProps) { function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; - workInProgress.stateNode = instance; - // The instance needs access to the fiber so that it can schedule updates + workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates + set(instance, workInProgress); + { instance._reactInternalInstance = fakeInternalInstance; } @@ -8178,8 +8218,7 @@ function constructClassInstance( { if ("contextType" in ctor) { - var isValid = - // Allow null for conditional declaration + var isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && @@ -8187,8 +8226,8 @@ function constructClassInstance( if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); - var addendum = ""; + if (contextType === undefined) { addendum = " However, it is set to undefined. " + @@ -8208,6 +8247,7 @@ function constructClassInstance( Object.keys(contextType).join(", ") + "}."; } + warningWithoutStack$1( false, "%s defines an invalid contextType. " + @@ -8229,9 +8269,8 @@ function constructClassInstance( context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; - } + } // Instantiate twice to help detect side-effects. - // Instantiate twice to help detect side-effects. { if ( debugRenderPhaseSideEffects || @@ -8252,6 +8291,7 @@ function constructClassInstance( { if (typeof ctor.getDerivedStateFromProps === "function" && state === null) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); warningWithoutStack$1( @@ -8265,11 +8305,10 @@ function constructClassInstance( componentName ); } - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. + } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. + if ( typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function" @@ -8277,6 +8316,7 @@ function constructClassInstance( var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; + if ( typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true @@ -8285,6 +8325,7 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillMount === "function") { foundWillMountName = "UNSAFE_componentWillMount"; } + if ( typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true @@ -8295,6 +8336,7 @@ function constructClassInstance( ) { foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps"; } + if ( typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true @@ -8303,16 +8345,19 @@ function constructClassInstance( } else if (typeof instance.UNSAFE_componentWillUpdate === "function") { foundWillUpdateName = "UNSAFE_componentWillUpdate"; } + if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { var _componentName = getComponentName(ctor) || "Component"; + var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()"; + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); warningWithoutStack$1( @@ -8320,7 +8365,7 @@ function constructClassInstance( "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n" + "%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n" + "The above lifecycles should be removed. Learn more about this warning here:\n" + - "https://fb.me/react-async-component-lifecycle-hooks", + "https://fb.me/react-unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", @@ -8332,10 +8377,9 @@ function constructClassInstance( } } } - } - - // Cache unmasked context so we can avoid recreating masked context unless necessary. + } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. + if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } @@ -8350,6 +8394,7 @@ function callComponentWillMount(workInProgress, instance) { if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } @@ -8366,6 +8411,7 @@ function callComponentWillMount(workInProgress, instance) { getComponentName(workInProgress.type) || "Component" ); } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } @@ -8378,17 +8424,21 @@ function callComponentWillReceiveProps( ) { var oldState = instance.state; startPhaseTimer(workInProgress, "componentWillReceiveProps"); + if (typeof instance.componentWillReceiveProps === "function") { instance.componentWillReceiveProps(newProps, nextContext); } + if (typeof instance.UNSAFE_componentWillReceiveProps === "function") { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } + stopPhaseTimer(); if (instance.state !== oldState) { { var componentName = getComponentName(workInProgress.type) || "Component"; + if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); warningWithoutStack$1( @@ -8400,11 +8450,11 @@ function callComponentWillReceiveProps( ); } } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } -} +} // Invokes the mount life-cycles on a previously never rendered instance. -// Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance( workInProgress, ctor, @@ -8419,8 +8469,8 @@ function mountClassInstance( instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; - var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { instance.context = readContext(contextType); } else if (disableLegacyContext) { @@ -8433,6 +8483,7 @@ function mountClassInstance( { if (instance.state === newProps) { var componentName = getComponentName(ctor) || "Component"; + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); warningWithoutStack$1( @@ -8461,6 +8512,7 @@ function mountClassInstance( } var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8473,6 +8525,7 @@ function mountClassInstance( } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -8481,20 +8534,20 @@ function mountClassInstance( newProps ); instance.state = workInProgress.memoizedState; - } - - // In order to support react-lifecycles-compat polyfilled components, + } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function") ) { - callComponentWillMount(workInProgress, instance); - // If we had additional state updates during this life-cycle, let's + callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. + updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8519,13 +8572,12 @@ function resumeMountClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = oldProps; - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8540,14 +8592,12 @@ function resumeMountClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8564,10 +8614,10 @@ function resumeMountClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8578,6 +8628,7 @@ function resumeMountClassInstance( ); newState = workInProgress.memoizedState; } + if ( oldProps === newProps && oldState === newState && @@ -8589,6 +8640,7 @@ function resumeMountClassInstance( if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } + return false; } @@ -8623,14 +8675,18 @@ function resumeMountClassInstance( typeof instance.componentWillMount === "function") ) { startPhaseTimer(workInProgress, "componentWillMount"); + if (typeof instance.componentWillMount === "function") { instance.componentWillMount(); } + if (typeof instance.UNSAFE_componentWillMount === "function") { instance.UNSAFE_componentWillMount(); } + stopPhaseTimer(); } + if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; } @@ -8639,24 +8695,20 @@ function resumeMountClassInstance( // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === "function") { workInProgress.effectTag |= Update; - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; -} +} // Invokes the update life-cycles and returns false if it shouldn't rerender. -// Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance( current, workInProgress, @@ -8665,16 +8717,15 @@ function updateClassInstance( renderExpirationTime ) { var instance = workInProgress.stateNode; - var oldProps = workInProgress.memoizedProps; instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); - var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; + if (typeof contextType === "object" && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { @@ -8685,14 +8736,12 @@ function updateClassInstance( var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || - typeof instance.getSnapshotBeforeUpdate === "function"; - - // Note: During these life-cycles, instance.props/instance.state are what + typeof instance.getSnapshotBeforeUpdate === "function"; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. - // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. + if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || @@ -8709,10 +8758,10 @@ function updateClassInstance( } resetHasForceUpdateBeforeProcessing(); - var oldState = workInProgress.memoizedState; var newState = (instance.state = oldState); var updateQueue = workInProgress.updateQueue; + if (updateQueue !== null) { processUpdateQueue( workInProgress, @@ -8740,6 +8789,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -8748,6 +8798,7 @@ function updateClassInstance( workInProgress.effectTag |= Snapshot; } } + return false; } @@ -8782,17 +8833,22 @@ function updateClassInstance( typeof instance.componentWillUpdate === "function") ) { startPhaseTimer(workInProgress, "componentWillUpdate"); + if (typeof instance.componentWillUpdate === "function") { instance.componentWillUpdate(newProps, newState, nextContext); } + if (typeof instance.UNSAFE_componentWillUpdate === "function") { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } + stopPhaseTimer(); } + if (typeof instance.componentDidUpdate === "function") { workInProgress.effectTag |= Update; } + if (typeof instance.getSnapshotBeforeUpdate === "function") { workInProgress.effectTag |= Snapshot; } @@ -8807,6 +8863,7 @@ function updateClassInstance( workInProgress.effectTag |= Update; } } + if (typeof instance.getSnapshotBeforeUpdate === "function") { if ( oldProps !== current.memoizedProps || @@ -8814,40 +8871,38 @@ function updateClassInstance( ) { workInProgress.effectTag |= Snapshot; } - } - - // If shouldComponentUpdate returned false, we should still update the + } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. + workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; - } - - // Update the existing instance's state, props, and context pointers even + } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. + instance.props = newProps; instance.state = newState; instance.context = nextContext; - return shouldUpdate; } -var didWarnAboutMaps = void 0; -var didWarnAboutGenerators = void 0; -var didWarnAboutStringRefs = void 0; -var ownerHasKeyUseWarning = void 0; -var ownerHasFunctionTypeWarning = void 0; +var didWarnAboutMaps; +var didWarnAboutGenerators; +var didWarnAboutStringRefs; +var ownerHasKeyUseWarning; +var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; - /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ + ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; @@ -8855,30 +8910,29 @@ var warnForMissingKey = function(child) {}; if (child === null || typeof child !== "object") { return; } + if (!child._store || child._store.validated || child.key != null) { return; } - (function() { - if (!(typeof child._store === "object")) { - throw ReactError( - Error( - "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - child._store.validated = true; + if (!(typeof child._store === "object")) { + throw Error( + "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." + ); + } + + child._store.validated = true; var currentComponentErrorInfo = "Each child in a list should have a unique " + '"key" prop. See https://fb.me/react-warning-keys for ' + "more information." + getCurrentFiberStackInDev(); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning$1( false, "Each child in a list should have a unique " + @@ -8892,6 +8946,7 @@ var isArray = Array.isArray; function coerceRef(returnFiber, current$$1, element) { var mixedRef = element.ref; + if ( mixedRef !== null && typeof mixedRef !== "function" && @@ -8902,16 +8957,16 @@ function coerceRef(returnFiber, current$$1, element) { // everyone, because the strict mode case will no longer be relevant if (returnFiber.mode & StrictMode || warnAboutStringRefs) { var componentName = getComponentName(returnFiber.type) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { if (warnAboutStringRefs) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://fb.me/react-strict-mode-string-ref%s", componentName, mixedRef, getStackByFiberInDevAndProd(returnFiber) @@ -8921,14 +8976,14 @@ function coerceRef(returnFiber, current$$1, element) { 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." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-string-ref", + "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) ); } + didWarnAboutStringRefs[componentName] = true; } } @@ -8936,33 +8991,30 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { var owner = element._owner; - var inst = void 0; + var inst; + if (owner) { var ownerFiber = owner; - (function() { - if (!(ownerFiber.tag === ClassComponent)) { - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) - ); - } - })(); - inst = ownerFiber.stateNode; - } - (function() { - if (!inst) { - throw ReactError( - Error( - "Missing owner for string ref " + - mixedRef + - ". This error is likely caused by a bug in React. Please file an issue." - ) + + if (!(ownerFiber.tag === ClassComponent)) { + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); } - })(); - var stringRef = "" + mixedRef; - // Check if previous string ref matches new string ref + + inst = ownerFiber.stateNode; + } + + if (!inst) { + throw Error( + "Missing owner for string ref " + + mixedRef + + ". This error is likely caused by a bug in React. Please file an issue." + ); + } + + var stringRef = "" + mixedRef; // Check if previous string ref matches new string ref + if ( current$$1 !== null && current$$1.ref !== null && @@ -8971,69 +9023,65 @@ function coerceRef(returnFiber, current$$1, element) { ) { return current$$1.ref; } + var ref = function(value) { var refs = inst.refs; + if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = inst.refs = {}; } + if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; + ref._stringRef = stringRef; return ref; } else { - (function() { - if (!(typeof mixedRef === "string")) { - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) - ); - } - })(); - (function() { - if (!element._owner) { - throw ReactError( - Error( - "Element ref was specified as a string (" + - mixedRef + - ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information." - ) - ); - } - })(); + if (!(typeof mixedRef === "string")) { + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + + if (!element._owner) { + 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." + ); + } } } + return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { if (returnFiber.type !== "textarea") { var addendum = ""; + { addendum = " If you meant to render a collection of children, use an array " + "instead." + getCurrentFiberStackInDev(); } - (function() { - { - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - (Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." + - addendum - ) - ); - } - })(); + + { + 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 + ); + } } } @@ -9047,38 +9095,39 @@ function warnOnFunctionType() { if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } - ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; + ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning$1( false, "Functions are not valid as a React child. This may happen if " + "you return a Component instead of from render. " + "Or maybe you meant to call this function rather than return it." ); -} - -// This wrapper function exists because I expect to clone the code in each path +} // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. + function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; - } - // Deletions are added in reversed order so we add it to the front. + } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } + childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } @@ -9087,32 +9136,36 @@ function ChildReconciler(shouldTrackSideEffects) { if (!shouldTrackSideEffects) { // Noop. return null; - } - - // TODO: For the shouldClone case, this could be micro-optimized a bit by + } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. + var childToDelete = currentFirstChild; + while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } + return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index + // instead. var existingChildren = new Map(); - var existingChild = currentFirstChild; + while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } + existingChild = existingChild.sibling; } + return existingChildren; } @@ -9127,13 +9180,17 @@ function ChildReconciler(shouldTrackSideEffects) { function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; + if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } + var current$$1 = newFiber.alternate; + if (current$$1 !== null) { var oldIndex = current$$1.index; + if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; @@ -9155,6 +9212,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } + return newFiber; } @@ -9184,18 +9242,19 @@ function ChildReconciler(shouldTrackSideEffects) { function updateElement(returnFiber, current$$1, element, expirationTime) { if ( current$$1 !== null && - (current$$1.elementType === element.type || - // Keep this check inline so it only runs on the false path: + (current$$1.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current$$1, element)) ) { // Move based on index var existing = useFiber(current$$1, element.props, expirationTime); existing.ref = coerceRef(returnFiber, current$$1, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { // Insert @@ -9284,16 +9343,19 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } + case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal( newChild, returnFiber.mode, expirationTime ); + _created2.return = returnFiber; return _created2; } @@ -9306,6 +9368,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime, null ); + _created3.return = returnFiber; return _created3; } @@ -9324,7 +9387,6 @@ function ChildReconciler(shouldTrackSideEffects) { function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { // Update the fiber if the keys match, otherwise return null. - var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === "string" || typeof newChild === "number") { @@ -9334,6 +9396,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (key !== null) { return null; } + return updateTextNode( returnFiber, oldFiber, @@ -9355,6 +9418,7 @@ function ChildReconciler(shouldTrackSideEffects) { key ); } + return updateElement( returnFiber, oldFiber, @@ -9365,6 +9429,7 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } } + case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal( @@ -9431,6 +9496,7 @@ function ChildReconciler(shouldTrackSideEffects) { existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment( returnFiber, @@ -9440,6 +9506,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChild.key ); } + return updateElement( returnFiber, _matchedFiber, @@ -9447,11 +9514,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ); } + case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get( newChild.key === null ? newIdx : newChild.key ) || null; + return updatePortal( returnFiber, _matchedFiber2, @@ -9463,6 +9532,7 @@ function ChildReconciler(shouldTrackSideEffects) { if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; + return updateFragment( returnFiber, _matchedFiber3, @@ -9483,32 +9553,37 @@ function ChildReconciler(shouldTrackSideEffects) { return null; } - /** * Warns if there is a duplicate or missing key */ + function warnOnInvalidKey(child, knownKeys) { { if (typeof child !== "object" || child === null) { return knownKeys; } + switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); var key = child.key; + if (typeof key !== "string") { break; } + if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } + if (!knownKeys.has(key)) { knownKeys.add(key); break; } + warning$1( false, "Encountered two children with the same key, `%s`. " + @@ -9519,10 +9594,12 @@ function ChildReconciler(shouldTrackSideEffects) { key ); break; + default: break; } } + return knownKeys; } @@ -9536,7 +9613,6 @@ function ChildReconciler(shouldTrackSideEffects) { // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. - // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in @@ -9544,16 +9620,14 @@ function ChildReconciler(shouldTrackSideEffects) { // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. - // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. - // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. - { // First, validate keys. var knownKeys = null; + for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9562,11 +9636,11 @@ function ChildReconciler(shouldTrackSideEffects) { var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; + for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; @@ -9574,12 +9648,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, newChildren[newIdx], expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -9588,8 +9664,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -9597,7 +9675,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -9608,6 +9688,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -9627,25 +9708,28 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber === null) { continue; } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } + previousNewFiber = _newFiber; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap( existingChildren, @@ -9654,6 +9738,7 @@ function ChildReconciler(shouldTrackSideEffects) { newChildren[newIdx], expirationTime ); + if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { @@ -9666,12 +9751,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } + previousNewFiber = _newFiber2; } } @@ -9695,24 +9783,19 @@ function ChildReconciler(shouldTrackSideEffects) { ) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. - var iteratorFn = getIteratorFn(newChildrenIterable); - (function() { - if (!(typeof iteratorFn === "function")) { - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(typeof iteratorFn === "function")) { + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); + } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if ( - typeof Symbol === "function" && - // $FlowFixMe Flow doesn't know about toStringTag + typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === "Generator" ) { !didWarnAboutGenerators @@ -9726,9 +9809,8 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutGenerators = true; - } + } // Warn about using Maps as children - // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { !didWarnAboutMaps ? warning$1( @@ -9739,14 +9821,16 @@ function ChildReconciler(shouldTrackSideEffects) { ) : void 0; didWarnAboutMaps = true; - } - - // First, validate keys. + } // First, validate keys. // We'll get a different iterator later for the main pass. + var _newChildren = iteratorFn.call(newChildrenIterable); + if (_newChildren) { var knownKeys = null; + var _step = _newChildren.next(); + for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys); @@ -9755,21 +9839,19 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - (function() { - if (!(newChildren != null)) { - throw ReactError(Error("An iterable object provided no iterator.")); - } - })(); + + if (!(newChildren != null)) { + throw Error("An iterable object provided no iterator."); + } var resultingFirstChild = null; var previousNewFiber = null; - var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; - var step = newChildren.next(); + for ( ; oldFiber !== null && !step.done; @@ -9781,12 +9863,14 @@ function ChildReconciler(shouldTrackSideEffects) { } else { nextOldFiber = oldFiber.sibling; } + var newFiber = updateSlot( returnFiber, oldFiber, step.value, expirationTime ); + if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need @@ -9795,8 +9879,10 @@ function ChildReconciler(shouldTrackSideEffects) { if (oldFiber === null) { oldFiber = nextOldFiber; } + break; } + if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we @@ -9804,7 +9890,9 @@ function ChildReconciler(shouldTrackSideEffects) { deleteChild(returnFiber, oldFiber); } } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; @@ -9815,6 +9903,7 @@ function ChildReconciler(shouldTrackSideEffects) { // with the previous one. previousNewFiber.sibling = newFiber; } + previousNewFiber = newFiber; oldFiber = nextOldFiber; } @@ -9830,25 +9919,28 @@ function ChildReconciler(shouldTrackSideEffects) { // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, expirationTime); + if (_newFiber3 === null) { continue; } + lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } + previousNewFiber = _newFiber3; } + return resultingFirstChild; - } + } // Add all children to a key map for quick lookups. - // Add all children to a key map for quick lookups. - var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. - // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap( existingChildren, @@ -9857,6 +9949,7 @@ function ChildReconciler(shouldTrackSideEffects) { step.value, expirationTime ); + if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { @@ -9869,12 +9962,15 @@ function ChildReconciler(shouldTrackSideEffects) { ); } } + lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } + previousNewFiber = _newFiber4; } } @@ -9905,9 +10001,9 @@ function ChildReconciler(shouldTrackSideEffects) { var existing = useFiber(currentFirstChild, textContent, expirationTime); existing.return = returnFiber; return existing; - } - // The existing first child is not a text node so we need to create one + } // The existing first child is not a text node so we need to create one // and delete the existing ones. + deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText( textContent, @@ -9926,6 +10022,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = element.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -9933,8 +10030,7 @@ function ChildReconciler(shouldTrackSideEffects) { 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: + : child.elementType === element.type || // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) { deleteRemainingChildren(returnFiber, child.sibling); @@ -9947,10 +10043,12 @@ function ChildReconciler(shouldTrackSideEffects) { ); existing.ref = coerceRef(returnFiber, child, element); existing.return = returnFiber; + { existing._debugSource = element._source; existing._debugOwner = element._owner; } + return existing; } else { deleteRemainingChildren(returnFiber, child); @@ -9959,6 +10057,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -9977,6 +10076,7 @@ function ChildReconciler(shouldTrackSideEffects) { returnFiber.mode, expirationTime ); + _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; @@ -9991,6 +10091,7 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var key = portal.key; var child = currentFirstChild; + while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. @@ -10011,6 +10112,7 @@ function ChildReconciler(shouldTrackSideEffects) { } else { deleteChild(returnFiber, child); } + child = child.sibling; } @@ -10021,11 +10123,10 @@ function ChildReconciler(shouldTrackSideEffects) { ); created.return = returnFiber; return created; - } - - // This API will tag the children with the side-effect of the reconciliation + } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. + function reconcileChildFibers( returnFiber, currentFirstChild, @@ -10036,7 +10137,6 @@ function ChildReconciler(shouldTrackSideEffects) { // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. - // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]} and <>.... // We treat the ambiguous cases above the same. @@ -10045,11 +10145,11 @@ function ChildReconciler(shouldTrackSideEffects) { newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; - } + } // Handle object types - // Handle object types var isObject = typeof newChild === "object" && newChild !== null; if (isObject) { @@ -10063,6 +10163,7 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) ); + case REACT_PORTAL_TYPE: return placeSingleChild( reconcileSinglePortal( @@ -10113,6 +10214,7 @@ function ChildReconciler(shouldTrackSideEffects) { warnOnFunctionType(); } } + if (typeof newChild === "undefined" && !isUnkeyedTopLevelFragment) { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, @@ -10121,6 +10223,7 @@ function ChildReconciler(shouldTrackSideEffects) { case ClassComponent: { { var instance = returnFiber.stateNode; + if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; @@ -10130,23 +10233,20 @@ function ChildReconciler(shouldTrackSideEffects) { // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough + case FunctionComponent: { var Component = returnFiber.type; - (function() { - { - throw ReactError( - Error( - (Component.displayName || Component.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) - ); - } - })(); + + { + 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." + ); + } } } - } + } // Remaining cases are all treated as empty. - // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } @@ -10155,13 +10255,10 @@ function ChildReconciler(shouldTrackSideEffects) { var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); - function cloneChildFibers(current$$1, workInProgress) { - (function() { - if (!(current$$1 === null || workInProgress.child === current$$1.child)) { - throw ReactError(Error("Resuming work not yet implemented.")); - } - })(); + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw Error("Resuming work not yet implemented."); + } if (workInProgress.child === null) { return; @@ -10174,8 +10271,8 @@ function cloneChildFibers(current$$1, workInProgress) { currentChild.expirationTime ); workInProgress.child = newChild; - newChild.return = workInProgress; + while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress( @@ -10185,12 +10282,13 @@ function cloneChildFibers(current$$1, workInProgress) { ); newChild.return = workInProgress; } + newChild.sibling = null; -} +} // Reset a workInProgress child set to prepare it for a second pass. -// Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, renderExpirationTime) { var child = workInProgress.child; + while (child !== null) { resetWorkInProgress(child, renderExpirationTime); child = child.sibling; @@ -10198,21 +10296,17 @@ function resetChildFibers(workInProgress, renderExpirationTime) { } var NO_CONTEXT = {}; - var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - (function() { - if (!(c !== NO_CONTEXT)) { - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(c !== NO_CONTEXT)) { + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + return c; } @@ -10224,19 +10318,18 @@ function getRootHostContainer() { function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. - push(rootInstanceStackCursor, nextRootInstance, fiber); - // Track the context and the Fiber that provided it. + push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. - push(contextFiberStackCursor, fiber, fiber); - // Finally, we need to push the host context to the stack. + push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. + push(contextStackCursor$1, NO_CONTEXT, fiber); - var nextRootContext = getRootHostContext(nextRootInstance); - // Now that we know this function doesn't throw, replace it. + var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. + pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } @@ -10255,15 +10348,13 @@ function getHostContext() { function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); - var nextContext = getChildHostContext(context, fiber.type, rootInstance); + var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. - // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; - } - - // Track the context and the Fiber that provided it. + } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. + push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } @@ -10279,98 +10370,100 @@ function popHostContext(fiber) { pop(contextFiberStackCursor, fiber); } -var DefaultSuspenseContext = 0; - -// The Suspense Context is split into two parts. The lower bits is +var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. -var SubtreeSuspenseContextMask = 1; - -// Subtree Flags: +var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. -var InvisibleParentSuspenseContext = 1; - -// Shallow Flags: +var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. -var ForceSuspenseFallback = 2; +var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); - function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } - function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } - function setShallowSuspenseContext(parentContext, shallowContext) { return (parentContext & SubtreeSuspenseContextMask) | shallowContext; } - function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } - function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } - function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } -// TODO: This is now an empty object. Should we switch this to a boolean? -// Alternatively we can make this use an effect tag similar to SuspenseList. - function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the + // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + // A dehydrated boundary always captures. + return true; + } + return false; } - var props = workInProgress.memoizedProps; - // In order to capture, the Suspense component must have a fallback prop. + + var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop. + if (props.fallback === undefined) { return false; - } - // Regular boundaries always capture. + } // Regular boundaries always capture. + if (props.unstable_avoidThisFallback !== true) { return true; - } - // If it's a boundary we should avoid, then we prefer to bubble up to the + } // If it's a boundary we should avoid, then we prefer to bubble up to the // parent boundary if it is currently invisible. + if (hasInvisibleParent) { return false; - } - // If the parent is not able to handle it, we must handle it. + } // If the parent is not able to handle it, we must handle it. + return true; } - function findFirstSuspended(row) { var node = row; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - return node; + var dehydrated = state.dehydrated; + + if ( + dehydrated === null || + isSuspenseInstancePending(dehydrated) || + isSuspenseInstanceFallback(dehydrated) + ) { + return node; + } } } else if ( - node.tag === SuspenseListComponent && - // revealOrder undefined can't be trusted because it don't + node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { var didSuspend = (node.effectTag & DidCapture) !== NoEffect; + if (didSuspend) { return node; } @@ -10379,37 +10472,32 @@ function findFirstSuspended(row) { node = node.child; continue; } + if (node === row) { return null; } + while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - return null; -} -function createResponderListener(responder, props) { - var eventResponderListener = { - responder: responder, - props: props - }; - { - Object.freeze(eventResponderListener); - } - return eventResponderListener; + return null; } +var emptyObject$1 = {}; +var isArray$2 = Array.isArray; function createResponderInstance( responder, responderProps, responderState, - target, fiber ) { return { @@ -10417,75 +10505,263 @@ function createResponderInstance( props: responderProps, responder: responder, rootEventTypes: null, - state: responderState, - target: target + state: responderState + }; +} + +function mountEventResponder( + responder, + responderProps, + fiber, + respondersMap, + rootContainerInstance +) { + var responderState = emptyObject$1; + var getInitialState = responder.getInitialState; + + if (getInitialState !== null) { + responderState = getInitialState(responderProps); + } + + var responderInstance = createResponderInstance( + responder, + responderProps, + responderState, + fiber + ); + + if (!rootContainerInstance) { + var node = fiber; + + while (node !== null) { + var tag = node.tag; + + if (tag === HostComponent) { + rootContainerInstance = node.stateNode; + break; + } else if (tag === HostRoot) { + rootContainerInstance = node.stateNode.containerInfo; + break; + } + + node = node.return; + } + } + + mountResponderInstance( + responder, + responderInstance, + responderProps, + responderState, + rootContainerInstance + ); + respondersMap.set(responder, responderInstance); +} + +function updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance +) { + var responder; + var props; + + if (listener) { + responder = listener.responder; + props = listener.props; + } + + if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { + throw Error( + "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponder()." + ); + } + + var listenerProps = props; + + if (visistedResponders.has(responder)) { + // show warning + { + 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 + ); + } + + return; + } + + visistedResponders.add(responder); + var responderInstance = respondersMap.get(responder); + + if (responderInstance === undefined) { + // Mount (happens in either complete or commit phase) + mountEventResponder( + responder, + listenerProps, + fiber, + respondersMap, + rootContainerInstance + ); + } else { + // Update (happens during commit phase only) + responderInstance.props = listenerProps; + responderInstance.fiber = fiber; + } +} + +function updateEventListeners(listeners, fiber, rootContainerInstance) { + var visistedResponders = new Set(); + var dependencies = fiber.dependencies; + + if (listeners != null) { + if (dependencies === null) { + dependencies = fiber.dependencies = { + expirationTime: NoWork, + firstContext: null, + responders: new Map() + }; + } + + var respondersMap = dependencies.responders; + + if (respondersMap === null) { + respondersMap = new Map(); + } + + if (isArray$2(listeners)) { + for (var i = 0, length = listeners.length; i < length; i++) { + var listener = listeners[i]; + updateEventListener( + listener, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } else { + updateEventListener( + listeners, + fiber, + visistedResponders, + respondersMap, + rootContainerInstance + ); + } + } + + if (dependencies !== null) { + var _respondersMap = dependencies.responders; + + if (_respondersMap !== null) { + // Unmount + var mountedResponders = Array.from(_respondersMap.keys()); + + for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { + var mountedResponder = mountedResponders[_i]; + + if (!visistedResponders.has(mountedResponder)) { + var responderInstance = _respondersMap.get(mountedResponder); + + unmountResponderInstance(responderInstance); + + _respondersMap.delete(mountedResponder); + } + } + } + } +} +function createResponderListener(responder, props) { + var eventResponderListener = { + responder: responder, + props: props }; + + { + Object.freeze(eventResponderListener); + } + + return eventResponderListener; } -var NoEffect$1 = /* */ 0; -var UnmountSnapshot = /* */ 2; -var UnmountMutation = /* */ 4; -var MountMutation = /* */ 8; -var UnmountLayout = /* */ 16; -var MountLayout = /* */ 32; -var MountPassive = /* */ 64; -var UnmountPassive = /* */ 128; +var NoEffect$1 = + /* */ + 0; +var UnmountSnapshot = + /* */ + 2; +var UnmountMutation = + /* */ + 4; +var MountMutation = + /* */ + 8; +var UnmountLayout = + /* */ + 16; +var MountLayout = + /* */ + 32; +var MountPassive = + /* */ + 64; +var UnmountPassive = + /* */ + 128; var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var didWarnAboutMismatchedHooksForComponent; -var didWarnAboutMismatchedHooksForComponent = void 0; { didWarnAboutMismatchedHooksForComponent = new Set(); } // These are set right before calling the component. -var renderExpirationTime$1 = NoWork; -// The work-in-progress fiber. I've named it differently to distinguish it from +var renderExpirationTime$1 = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. -var currentlyRenderingFiber$1 = null; -// Hooks are stored as a linked list on the fiber's memoizedState field. The +var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. + var currentHook = null; var nextCurrentHook = null; var firstWorkInProgressHook = null; var workInProgressHook = null; var nextWorkInProgressHook = null; - var remainingExpirationTime = NoWork; var componentUpdateQueue = null; -var sideEffectTag = 0; - -// Updates scheduled during render will trigger an immediate re-render at the +var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the // end of the current pass. We can't store these updates on the normal queue, // because if the work is aborted, they should be discarded. Because this is // a relatively rare case, we also don't want to add an additional field to // either the hook or queue object types. So we store them in a lazily create // map of queue -> render-phase updates, which are discarded once the component // completes without re-rendering. - // Whether an update was scheduled during the currently executing render pass. -var didScheduleRenderPhaseUpdate = false; -// Lazily created map of render-phase updates -var renderPhaseUpdates = null; -// Counter to prevent infinite loops. -var numberOfReRenders = 0; -var RE_RENDER_LIMIT = 25; -// In DEV, this is the name of the currently executing primitive hook -var currentHookNameInDev = null; +var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook -// In DEV, this list ensures that hooks are called in the same order between renders. +var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. -var hookTypesDev = null; -var hookTypesUpdateIndexDev = -1; -// In DEV, this tracks whether currently rendering component needs to ignore +var hookTypesDev = null; +var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. + var ignorePreviousDependencies = false; function mountHookTypesDev() { @@ -10506,6 +10782,7 @@ function updateHookTypesDev() { if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } @@ -10532,29 +10809,26 @@ function checkDepsAreArrayDev(deps) { function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentName(currentlyRenderingFiber$1.type); + if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ""; - var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; - - var row = i + 1 + ". " + oldHookName; - - // Extra space so second column lines up + var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { row += " "; } row += newHookName + "\n"; - table += row; } @@ -10576,15 +10850,11 @@ function warnOnHookMismatchInDev(currentHookName) { } function throwInvalidHookError() { - (function() { - { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) - ); - } - })(); + { + 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." + ); + } } function areHookInputsEqual(nextDeps, prevDeps) { @@ -10605,6 +10875,7 @@ function areHookInputsEqual(nextDeps, prevDeps) { currentHookNameInDev ); } + return false; } @@ -10624,12 +10895,15 @@ function areHookInputsEqual(nextDeps, prevDeps) { ); } } + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { - if (is(nextDeps[i], prevDeps[i])) { + if (is$1(nextDeps[i], prevDeps[i])) { continue; } + return false; } + return true; } @@ -10647,31 +10921,26 @@ function renderWithHooks( { hookTypesDev = current !== null ? current._debugHookTypes : null; - hookTypesUpdateIndexDev = -1; - // Used for hot reloading: + hookTypesUpdateIndexDev = -1; // Used for hot reloading: + ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; - } - - // The following should have already been reset + } // The following should have already been reset // currentHook = null; // workInProgressHook = null; - // remainingExpirationTime = NoWork; // componentUpdateQueue = null; - // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; // sideEffectTag = 0; - // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because nextCurrentHook === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) - // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so nextCurrentHook would be null during updates and mounts. + { if (nextCurrentHook !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; @@ -10693,16 +10962,15 @@ function renderWithHooks( do { didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; + { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; - } + } // Start over from the beginning of the list - // Start over from the beginning of the list nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; - currentHook = null; workInProgressHook = null; componentUpdateQueue = null; @@ -10713,20 +10981,16 @@ function renderWithHooks( } ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; - children = Component(props, refOrContext); } while (didScheduleRenderPhaseUpdate); renderPhaseUpdates = null; numberOfReRenders = 0; - } - - // We can assume the previous dispatcher is always this one, since we set it + } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; var renderedWork = currentlyRenderingFiber$1; - renderedWork.memoizedState = firstWorkInProgressHook; renderedWork.expirationTime = remainingExpirationTime; renderedWork.updateQueue = componentUpdateQueue; @@ -10734,15 +10998,12 @@ function renderWithHooks( { renderedWork._debugHookTypes = hookTypesDev; - } - - // This check uses currentHook so that it works the same in DEV and prod bundles. + } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. - var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -10757,45 +11018,36 @@ function renderWithHooks( remainingExpirationTime = NoWork; componentUpdateQueue = null; - sideEffectTag = 0; - - // These were reset above + sideEffectTag = 0; // These were reset above // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; - (function() { - if (!!didRenderTooFewHooks) { - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) - ); - } - })(); + if (!!didRenderTooFewHooks) { + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } return children; } - function bailoutHooks(current, workInProgress, expirationTime) { workInProgress.updateQueue = current.updateQueue; workInProgress.effectTag &= ~(Passive | Update); + if (current.expirationTime <= expirationTime) { current.expirationTime = NoWork; } } - function resetHooks() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. - ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; - - // This is used to reset the state of this module when a component throws. + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws. // It's also called inside mountIndeterminateComponent if we determine the // component is a module-style component. + renderExpirationTime$1 = NoWork; currentlyRenderingFiber$1 = null; - currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; @@ -10805,14 +11057,12 @@ function resetHooks() { { hookTypesDev = null; hookTypesUpdateIndexDev = -1; - currentHookNameInDev = null; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -10821,11 +11071,9 @@ function resetHooks() { function mountWorkInProgressHook() { var hook = { memoizedState: null, - baseState: null, queue: null, baseUpdate: null, - next: null }; @@ -10836,6 +11084,7 @@ function mountWorkInProgressHook() { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } + return workInProgressHook; } @@ -10849,27 +11098,20 @@ function updateWorkInProgressHook() { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; - currentHook = nextCurrentHook; nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - (function() { - if (!(nextCurrentHook !== null)) { - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); - } - })(); - currentHook = nextCurrentHook; + if (!(nextCurrentHook !== null)) { + throw Error("Rendered more hooks than during the previous render."); + } + currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, - baseState: currentHook.baseState, queue: currentHook.queue, baseUpdate: currentHook.baseUpdate, - next: null }; @@ -10880,8 +11122,10 @@ function updateWorkInProgressHook() { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } + nextCurrentHook = currentHook.next; } + return workInProgressHook; } @@ -10897,12 +11141,14 @@ function basicStateReducer(state, action) { function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); - var initialState = void 0; + var initialState; + if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -10911,8 +11157,7 @@ function mountReducer(reducer, initialArg, init) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -10922,68 +11167,67 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - (function() { - if (!(queue !== null)) { - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(queue !== null)) { + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + } queue.lastRenderedReducer = reducer; if (numberOfReRenders > 0) { // This is a re-render. Apply the new render phase updates to the previous + // work-in-progress hook. var _dispatch = queue.dispatch; + if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = hook.memoizedState; var update = firstRenderPhaseUpdate; + do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. - var _action = update.action; - newState = reducer(newState, _action); + var action = update.action; + newState = reducer(newState, action); update = update.next; - } while (update !== null); - - // Mark that the fiber performed work, but only if the new state is + } while (update !== null); // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(newState, hook.memoizedState)) { + + if (!is$1(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } - hook.memoizedState = newState; - // Don't persist the state accumulated from the render phase updates to + hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. + if (hook.baseUpdate === queue.last) { hook.baseState = newState; } queue.lastRenderedState = newState; - return [newState, _dispatch]; } } + return [hook.memoizedState, _dispatch]; - } + } // The last update in the entire queue + + var last = queue.last; // The last update that is part of the base state. - // The last update in the entire queue - var last = queue.last; - // The last update that is part of the base state. var baseUpdate = hook.baseUpdate; - var baseState = hook.baseState; + var baseState = hook.baseState; // Find the first unprocessed update. + + var first; - // Find the first unprocessed update. - var first = void 0; if (baseUpdate !== null) { if (last !== null) { // For the first update, the queue is a circular linked list where @@ -10991,10 +11235,12 @@ function updateReducer(reducer, initialArg, init) { // the `baseUpdate` is no longer empty, we can unravel the list. last.next = null; } + first = baseUpdate.next; } else { first = last !== null ? last.next : null; } + if (first !== null) { var _newState = baseState; var newBaseState = null; @@ -11002,8 +11248,10 @@ function updateReducer(reducer, initialArg, init) { var prevUpdate = baseUpdate; var _update = first; var didSkip = false; + do { var updateExpirationTime = _update.expirationTime; + if (updateExpirationTime < renderExpirationTime$1) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base @@ -11012,14 +11260,14 @@ function updateReducer(reducer, initialArg, init) { didSkip = true; newBaseUpdate = prevUpdate; newBaseState = _newState; - } - // Update the remaining priority in the queue. + } // Update the remaining priority in the queue. + if (updateExpirationTime > remainingExpirationTime) { remainingExpirationTime = updateExpirationTime; + markUnprocessedUpdateTime(remainingExpirationTime); } } else { // This update does have sufficient priority. - // Mark the event time of this update as relevant to this render pass. // TODO: This should ideally use the true event time of this update rather than // its priority which is a derived and not reverseable value. @@ -11029,18 +11277,18 @@ function updateReducer(reducer, initialArg, init) { markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig - ); + ); // Process this update. - // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the // current reducer, we can use the eagerly computed state. _newState = _update.eagerState; } else { - var _action2 = _update.action; - _newState = reducer(_newState, _action2); + var _action = _update.action; + _newState = reducer(_newState, _action); } } + prevUpdate = _update; _update = _update.next; } while (_update !== null && _update !== first); @@ -11048,18 +11296,16 @@ function updateReducer(reducer, initialArg, init) { if (!didSkip) { newBaseUpdate = prevUpdate; newBaseState = _newState; - } - - // Mark that the fiber performed work, but only if the new state is + } // Mark that the fiber performed work, but only if the new state is // different from the current state. - if (!is(_newState, hook.memoizedState)) { + + if (!is$1(_newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = _newState; hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.lastRenderedState = _newState; } @@ -11069,9 +11315,11 @@ function updateReducer(reducer, initialArg, init) { function mountState(initialState) { var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { initialState = initialState(); } + hook.memoizedState = hook.baseState = initialState; var queue = (hook.queue = { last: null, @@ -11080,8 +11328,7 @@ function mountState(initialState) { lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( - null, - // Flow doesn't know this is non-null, but we do. + null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue )); @@ -11101,29 +11348,36 @@ function pushEffect(tag, create, destroy, deps) { // Circular next: null }; + if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); componentUpdateQueue.lastEffect = effect.next = effect; } else { - var _lastEffect = componentUpdateQueue.lastEffect; - if (_lastEffect === null) { + var lastEffect = componentUpdateQueue.lastEffect; + + if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { - var firstEffect = _lastEffect.next; - _lastEffect.next = effect; + var firstEffect = lastEffect.next; + lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } + return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); - var ref = { current: initialValue }; + var ref = { + current: initialValue + }; + { Object.seal(ref); } + hook.memoizedState = ref; return ref; } @@ -11148,8 +11402,10 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; + if (nextDeps !== null) { var prevDeps = prevEffect.deps; + if (areHookInputsEqual(nextDeps, prevDeps)) { pushEffect(NoEffect$1, create, destroy, nextDeps); return; @@ -11168,6 +11424,7 @@ function mountEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return mountEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11183,6 +11440,7 @@ function updateEffect(create, deps) { warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1); } } + return updateEffectImpl( Update | Passive, UnmountPassive | MountPassive, @@ -11202,13 +11460,16 @@ function updateLayoutEffect(create, deps) { function imperativeHandleEffect(create, ref) { if (typeof ref === "function") { var refCallback = ref; + var _inst = create(); + refCallback(_inst); return function() { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; + { !refObject.hasOwnProperty("current") ? warning$1( @@ -11219,7 +11480,9 @@ function imperativeHandleEffect(create, ref) { ) : void 0; } + var _inst2 = create(); + refObject.current = _inst2; return function() { refObject.current = null; @@ -11237,12 +11500,10 @@ function mountImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return mountEffectImpl( Update, UnmountMutation | MountLayout, @@ -11261,12 +11522,10 @@ function updateImperativeHandle(ref, create, deps) { create !== null ? typeof create : "null" ) : void 0; - } + } // TODO: If deps are provided, should we skip comparing the ref itself? - // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; - return updateEffectImpl( Update, UnmountMutation | MountLayout, @@ -11294,14 +11553,17 @@ function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + hook.memoizedState = [callback, nextDeps]; return callback; } @@ -11318,33 +11580,32 @@ function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; + if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; + if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } + var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function dispatchAction(fiber, queue, action) { - (function() { - if (!(numberOfReRenders < RE_RENDER_LIMIT)) { - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) - ); - } - })(); + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } { - !(arguments.length <= 3) + !(typeof arguments[3] !== "function") ? warning$1( false, "State updates from the useState() and useReducer() Hooks don't support the " + @@ -11355,6 +11616,7 @@ function dispatchAction(fiber, queue, action) { } var alternate = fiber.alternate; + if ( fiber === currentlyRenderingFiber$1 || (alternate !== null && alternate === currentlyRenderingFiber$1) @@ -11371,39 +11633,40 @@ function dispatchAction(fiber, queue, action) { eagerState: null, next: null }; + { update.priority = getCurrentPriorityLevel(); } + if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } + lastRenderPhaseUpdate.next = update; } } else { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } - var currentTime = requestCurrentTime(); - var _suspenseConfig = requestCurrentSuspenseConfig(); - var _expirationTime = computeExpirationForFiber( + var suspenseConfig = requestCurrentSuspenseConfig(); + var expirationTime = computeExpirationForFiber( currentTime, fiber, - _suspenseConfig + suspenseConfig ); - var _update2 = { - expirationTime: _expirationTime, - suspenseConfig: _suspenseConfig, + expirationTime: expirationTime, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, @@ -11412,21 +11675,24 @@ function dispatchAction(fiber, queue, action) { { _update2.priority = getCurrentPriorityLevel(); - } + } // Append the update to the end of the list. - // Append the update to the end of the list. - var _last = queue.last; - if (_last === null) { + var last = queue.last; + + if (last === null) { // This is the first update. Create a circular list. _update2.next = _update2; } else { - var first = _last.next; + var first = last.next; + if (first !== null) { // Still circular. _update2.next = first; } - _last.next = _update2; + + last.next = _update2; } + queue.last = _update2; if ( @@ -11436,23 +11702,27 @@ function dispatchAction(fiber, queue, action) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. - var _lastRenderedReducer = queue.lastRenderedReducer; - if (_lastRenderedReducer !== null) { - var prevDispatcher = void 0; + var lastRenderedReducer = queue.lastRenderedReducer; + + if (lastRenderedReducer !== null) { + var prevDispatcher; + { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } + try { var currentState = queue.lastRenderedState; - var _eagerState = _lastRenderedReducer(currentState, action); - // Stash the eagerly computed state, and the reducer used to compute + var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. - _update2.eagerReducer = _lastRenderedReducer; - _update2.eagerState = _eagerState; - if (is(_eagerState, currentState)) { + + _update2.eagerReducer = lastRenderedReducer; + _update2.eagerState = eagerState; + + if (is$1(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that @@ -11468,6 +11738,7 @@ function dispatchAction(fiber, queue, action) { } } } + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -11475,13 +11746,13 @@ function dispatchAction(fiber, queue, action) { warnIfNotCurrentlyActingUpdatesInDev(fiber); } } - scheduleWork(fiber, _expirationTime); + + scheduleWork(fiber, expirationTime); } } var ContextOnlyDispatcher = { readContext: readContext, - useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, @@ -11494,7 +11765,6 @@ var ContextOnlyDispatcher = { useDebugValue: throwInvalidHookError, useResponder: throwInvalidHookError }; - var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; @@ -11561,6 +11831,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11572,6 +11843,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11588,6 +11860,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11605,7 +11878,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -11640,6 +11912,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11651,6 +11924,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11667,6 +11941,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11684,7 +11959,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - HooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { return readContext(context, observedBits); @@ -11719,6 +11993,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -11730,6 +12005,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -11746,6 +12022,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -11763,7 +12040,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -11805,6 +12081,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountMemo(create, deps); } finally { @@ -11817,6 +12094,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountReducer(reducer, initialArg, init); } finally { @@ -11835,6 +12113,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { return mountState(initialState); } finally { @@ -11854,7 +12133,6 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; return createResponderListener(responder, props); } }; - InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function(context, observedBits) { warnInvalidContextAccess(); @@ -11896,6 +12174,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateMemo(create, deps); } finally { @@ -11908,6 +12187,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateReducer(reducer, initialArg, init); } finally { @@ -11926,6 +12206,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; + try { return updateState(initialState); } finally { @@ -11947,10 +12228,9 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }; } -// Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. -var now$1 = Scheduler.unstable_now; +var now$1 = Scheduler.unstable_now; var commitTime = 0; var profilerStartTime = -1; @@ -11962,6 +12242,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } + commitTime = now$1(); } @@ -11981,6 +12262,7 @@ function stopProfilerTimerIfRunning(fiber) { if (!enableProfilerTimer) { return; } + profilerStartTime = -1; } @@ -11992,15 +12274,17 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } + profilerStartTime = -1; } } -// The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. + var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; @@ -12028,12 +12312,14 @@ function enterHydrationState(fiber) { return true; } -function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) { +function reenterHydrationStateFromDehydratedSuspenseInstance( + fiber, + suspenseInstance +) { if (!supportsHydration) { return false; } - var suspenseInstance = fiber.stateNode; nextHydratableInstance = getNextHydratableSibling(suspenseInstance); popToNextHostParent(fiber); isHydrating = true; @@ -12049,6 +12335,7 @@ function deleteHydratableInstance(returnFiber, instance) { instance ); break; + case HostComponent: didNotHydrateInstance( returnFiber.type, @@ -12063,13 +12350,12 @@ function deleteHydratableInstance(returnFiber, instance) { var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; - childToDelete.effectTag = Deletion; - - // This might seem like it belongs on progressedFirstDeletion. However, + childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However, // these children are not part of the reconciliation list of children. // Even if we abort and rereconcile the children, that will try to hydrate // again and the nodes are still in the host tree so these will be // recreated. + if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; @@ -12079,31 +12365,38 @@ function deleteHydratableInstance(returnFiber, instance) { } function insertNonHydratedInstance(returnFiber, fiber) { - fiber.effectTag |= Placement; + fiber.effectTag = (fiber.effectTag & ~Hydrating) | Placement; + { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; + switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableContainerInstance(parentContainer, type, props); break; + case HostText: var text = fiber.pendingProps; didNotFindHydratableContainerTextInstance(parentContainer, text); break; + case SuspenseComponent: didNotFindHydratableContainerSuspenseInstance(parentContainer); break; } + break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; + switch (fiber.tag) { case HostComponent: var _type = fiber.type; @@ -12116,6 +12409,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _props ); break; + case HostText: var _text = fiber.pendingProps; didNotFindHydratableTextInstance( @@ -12125,6 +12419,7 @@ function insertNonHydratedInstance(returnFiber, fiber) { _text ); break; + case SuspenseComponent: didNotFindHydratableSuspenseInstance( parentType, @@ -12133,8 +12428,10 @@ function insertNonHydratedInstance(returnFiber, fiber) { ); break; } + break; } + default: return; } @@ -12147,33 +12444,53 @@ function tryHydrate(fiber, nextInstance) { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type, props); + if (instance !== null) { fiber.stateNode = instance; return true; } + return false; } + case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); + if (textInstance !== null) { fiber.stateNode = textInstance; return true; } + return false; } + case SuspenseComponent: { if (enableSuspenseServerRenderer) { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); + if (suspenseInstance !== null) { - // Downgrade the tag to a dehydrated component until we've hydrated it. - fiber.tag = DehydratedSuspenseComponent; - fiber.stateNode = suspenseInstance; + var suspenseState = { + dehydrated: suspenseInstance, + retryTime: Never + }; + fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. + // This simplifies the code for getHostSibling and deleting nodes, + // since it doesn't have to consider all Suspense boundaries and + // check if they're dehydrated ones or not. + + var dehydratedFragment = createFiberFromDehydratedFragment( + suspenseInstance + ); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; return true; } } + return false; } + default: return false; } @@ -12183,7 +12500,9 @@ function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } + var nextInstance = nextHydratableInstance; + if (!nextInstance) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); @@ -12191,25 +12510,29 @@ function tryToClaimNextHydratableInstance(fiber) { hydrationParentFiber = fiber; return; } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; - } - // We matched the next one, we'll now assume that the first one was + } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. + deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance); } + hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(nextInstance); } @@ -12220,15 +12543,11 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var instance = fiber.stateNode; @@ -12239,38 +12558,37 @@ function prepareToHydrateHostInstance( rootContainerInstance, hostContext, fiber - ); - // TODO: Type this specific to this type of component. - fiber.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. + if (updatePayload !== null) { return true; } + return false; } function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); + { if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { @@ -12282,6 +12600,7 @@ function prepareToHydrateHostTextInstance(fiber) { ); break; } + case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; @@ -12299,46 +12618,66 @@ function prepareToHydrateHostTextInstance(fiber) { } } } + return shouldUpdate; } -function skipPastDehydratedSuspenseInstance(fiber) { +function prepareToHydrateHostSuspenseInstance(fiber) { if (!supportsHydration) { - (function() { - { - throw ReactError( - Error( - "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + throw Error( + "Expected prepareToHydrateHostSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } } - var suspenseInstance = fiber.stateNode; - (function() { - if (!suspenseInstance) { - throw ReactError( - Error( - "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." - ) + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + hydrateSuspenseInstance(suspenseInstance, fiber); +} + +function skipPastDehydratedSuspenseInstance(fiber) { + if (!supportsHydration) { + { + throw Error( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." ); } - })(); - nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( - suspenseInstance - ); + } + + var suspenseState = fiber.memoizedState; + var suspenseInstance = + suspenseState !== null ? suspenseState.dehydrated : null; + + if (!suspenseInstance) { + throw Error( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + + return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; + while ( parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && - parent.tag !== DehydratedSuspenseComponent + parent.tag !== SuspenseComponent ) { parent = parent.return; } + hydrationParentFiber = parent; } @@ -12346,11 +12685,13 @@ function popHydrationState(fiber) { if (!supportsHydration) { return false; } + if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } + if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our @@ -12360,13 +12701,12 @@ function popHydrationState(fiber) { return false; } - var type = fiber.type; - - // If we have any remaining hydratable nodes, we need to delete them now. + var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. // TODO: Better heuristic. + if ( fiber.tag !== HostComponent || (type !== "head" && @@ -12374,6 +12714,7 @@ function popHydrationState(fiber) { !shouldSetTextContent(type, fiber.memoizedProps)) ) { var nextInstance = nextHydratableInstance; + while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); @@ -12381,9 +12722,15 @@ function popHydrationState(fiber) { } popToNextHostParent(fiber); - nextHydratableInstance = hydrationParentFiber - ? getNextHydratableSibling(fiber.stateNode) - : null; + + if (fiber.tag === SuspenseComponent) { + nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); + } else { + nextHydratableInstance = hydrationParentFiber + ? getNextHydratableSibling(fiber.stateNode) + : null; + } + return true; } @@ -12398,19 +12745,17 @@ function resetHydrationState() { } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; - var didReceiveUpdate = false; - -var didWarnAboutBadClass = void 0; -var didWarnAboutModulePatternComponent = void 0; -var didWarnAboutContextTypeOnFunctionComponent = void 0; -var didWarnAboutGetDerivedStateOnFunctionComponent = void 0; -var didWarnAboutFunctionRefs = void 0; -var didWarnAboutReassigningProps = void 0; -var didWarnAboutMaxDuration = void 0; -var didWarnAboutRevealOrder = void 0; -var didWarnAboutTailOptions = void 0; -var didWarnAboutDefaultPropsOnFunctionComponent = void 0; +var didWarnAboutBadClass; +var didWarnAboutModulePatternComponent; +var didWarnAboutContextTypeOnFunctionComponent; +var didWarnAboutGetDerivedStateOnFunctionComponent; +var didWarnAboutFunctionRefs; +var didWarnAboutReassigningProps; +var didWarnAboutMaxDuration; +var didWarnAboutRevealOrder; +var didWarnAboutTailOptions; +var didWarnAboutDefaultPropsOnFunctionComponent; { didWarnAboutBadClass = {}; @@ -12446,7 +12791,6 @@ function reconcileChildren( // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. - // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers( @@ -12477,11 +12821,11 @@ function forceUnmountCurrentAndReconcile( current$$1.child, null, renderExpirationTime - ); - // In the second pass, we mount the new children. The trick here is that we + ); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their their // identity matches. + workInProgress.child = reconcileChildFibers( workInProgress, null, @@ -12500,12 +12844,12 @@ function updateForwardRef( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12519,11 +12863,11 @@ function updateForwardRef( } var render = Component.render; - var ref = workInProgress.ref; + var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent - // The rest is a fork of updateFunctionComponent - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12535,6 +12879,7 @@ function updateForwardRef( ref, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12552,6 +12897,7 @@ function updateForwardRef( ); } } + setCurrentPhase(null); } @@ -12562,9 +12908,8 @@ function updateForwardRef( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -12585,24 +12930,27 @@ function updateMemoComponent( ) { if (current$$1 === null) { var type = Component.type; + if ( isSimpleFunctionComponent(type) && - Component.compare === null && - // SimpleMemoComponent codepath doesn't resolve outer props either. + Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined ) { var resolvedType = type; + { resolvedType = resolveFunctionForHotReloading(type); - } - // If this is a plain function component without default props, + } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. + workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; + { validateFunctionComponentInDev(workInProgress, type); } + return updateSimpleMemoComponent( current$$1, workInProgress, @@ -12612,8 +12960,10 @@ function updateMemoComponent( renderExpirationTime ); } + { var innerPropTypes = type.propTypes; + if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -12626,6 +12976,7 @@ function updateMemoComponent( ); } } + var child = createFiberFromTypeAndProps( Component.type, null, @@ -12639,9 +12990,11 @@ function updateMemoComponent( workInProgress.child = child; return child; } + { var _type = Component.type; var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. @@ -12654,14 +13007,17 @@ function updateMemoComponent( ); } } + var currentChild = current$$1.child; // This is always exactly one child + if (updateExpirationTime < renderExpirationTime) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. - var prevProps = currentChild.memoizedProps; - // Default to shallow comparison + var prevProps = currentChild.memoizedProps; // Default to shallow comparison + var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; + if ( compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref @@ -12672,8 +13028,8 @@ function updateMemoComponent( renderExpirationTime ); } - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; var newChild = createWorkInProgress( currentChild, @@ -12697,19 +13053,21 @@ function updateSimpleMemoComponent( // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. - { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. outerMemoType = refineResolvedLazyComponent(outerMemoType); } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -12718,19 +13076,20 @@ function updateSimpleMemoComponent( getComponentName(outerMemoType), getCurrentFiberStackInDev ); - } - // Inner propTypes will be validated in the function component path. + } // Inner propTypes will be validated in the function component path. } } + if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; + if ( shallowEqual(prevProps, nextProps) && - current$$1.ref === workInProgress.ref && - // Prevent bailout if the implementation changed due to hot reload: + current$$1.ref === workInProgress.ref && // Prevent bailout if the implementation changed due to hot reload: workInProgress.type === current$$1.type ) { didReceiveUpdate = false; + if (updateExpirationTime < renderExpirationTime) { return bailoutOnAlreadyFinishedWork( current$$1, @@ -12740,6 +13099,7 @@ function updateSimpleMemoComponent( } } } + return updateFunctionComponent( current$$1, workInProgress, @@ -12775,6 +13135,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren( @@ -12788,6 +13149,7 @@ function updateProfiler(current$$1, workInProgress, renderExpirationTime) { function markRef(current$$1, workInProgress) { var ref = workInProgress.ref; + if ( (current$$1 === null && ref !== null) || (current$$1 !== null && current$$1.ref !== ref) @@ -12809,6 +13171,7 @@ function updateFunctionComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12821,14 +13184,16 @@ function updateFunctionComponent( } } - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } - var nextChildren = void 0; + var nextChildren; prepareToReadContext(workInProgress, renderExpirationTime); + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); @@ -12840,6 +13205,7 @@ function updateFunctionComponent( context, renderExpirationTime ); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -12857,6 +13223,7 @@ function updateFunctionComponent( ); } } + setCurrentPhase(null); } @@ -12867,9 +13234,8 @@ function updateFunctionComponent( workInProgress, renderExpirationTime ); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -12892,6 +13258,7 @@ function updateClassComponent( // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; + if (innerPropTypes) { checkPropTypes( innerPropTypes, @@ -12902,22 +13269,23 @@ function updateClassComponent( ); } } - } - - // Push context providers early to prevent context stack mismatches. + } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); var instance = workInProgress.stateNode; - var shouldUpdate = void 0; + var shouldUpdate; + if (instance === null) { if (current$$1 !== null) { // An class component without an instance only mounts if it suspended @@ -12925,11 +13293,11 @@ function updateClassComponent( // tree it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current$$1.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; - } - // In the initial pass we might need to construct the instance. + } // In the initial pass we might need to construct the instance. + constructClassInstance( workInProgress, Component, @@ -12960,6 +13328,7 @@ function updateClassComponent( renderExpirationTime ); } + var nextUnitOfWork = finishClassComponent( current$$1, workInProgress, @@ -12968,8 +13337,10 @@ function updateClassComponent( hasContext, renderExpirationTime ); + { var inst = workInProgress.stateNode; + if (inst.props !== nextProps) { !didWarnAboutReassigningProps ? warning$1( @@ -12982,6 +13353,7 @@ function updateClassComponent( didWarnAboutReassigningProps = true; } } + return nextUnitOfWork; } @@ -12995,7 +13367,6 @@ function finishClassComponent( ) { // Refs should update even if shouldComponentUpdate returns false markRef(current$$1, workInProgress); - var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect; if (!shouldUpdate && !didCaptureError) { @@ -13011,11 +13382,11 @@ function finishClassComponent( ); } - var instance = workInProgress.stateNode; + var instance = workInProgress.stateNode; // Rerender - // Rerender ReactCurrentOwner$3.current = workInProgress; - var nextChildren = void 0; + var nextChildren; + if ( didCaptureError && typeof Component.getDerivedStateFromError !== "function" @@ -13034,6 +13405,7 @@ function finishClassComponent( { setCurrentPhase("render"); nextChildren = instance.render(); + if ( debugRenderPhaseSideEffects || (debugRenderPhaseSideEffectsForStrictMode && @@ -13041,12 +13413,13 @@ function finishClassComponent( ) { instance.render(); } + setCurrentPhase(null); } - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; + if (current$$1 !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children @@ -13065,13 +13438,11 @@ function finishClassComponent( nextChildren, renderExpirationTime ); - } - - // Memoize state using the values we just used to render. + } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. - workInProgress.memoizedState = instance.state; - // The context might have changed so we need to recalculate it. + workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. + if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } @@ -13081,6 +13452,7 @@ function finishClassComponent( function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; + if (root.pendingContext) { pushTopLevelContextObject( workInProgress, @@ -13091,21 +13463,20 @@ function pushHostRootContext(workInProgress) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } + pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - (function() { - if (!(updateQueue !== null)) { - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!(updateQueue !== null)) { + 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." + ); + } + var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState !== null ? prevState.element : null; @@ -13116,10 +13487,11 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { null, renderExpirationTime ); - var nextState = workInProgress.memoizedState; - // Caution: React DevTools currently depends on this property + var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property // being called "element". + var nextChildren = nextState.element; + if (nextChildren === prevChildren) { // If the state is the same as before, that's a bailout because we had // no work that expires at this time. @@ -13130,32 +13502,33 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + var root = workInProgress.stateNode; - if ( - (current$$1 === null || current$$1.child === null) && - root.hydrate && - enterHydrationState(workInProgress) - ) { + + if (root.hydrate && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. - - // This is a bit of a hack. We track the host root as a placement to - // know that we're currently in a mounting state. That way isMounted - // works as expected. We must reset this before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag |= Placement; - - // Ensure that children mount into this root without tracking - // side-effects. This ensures that we don't store Placement effects on - // nodes that will be hydrated. - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + workInProgress.child = child; + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag = (node.effectTag & ~Placement) | Hydrating; + node = node.sibling; + } } else { // Otherwise reset hydration state in case we aborted and resumed another // root. @@ -13167,6 +13540,7 @@ function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { ); resetHydrationState(); } + return workInProgress.child; } @@ -13180,7 +13554,6 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current$$1 !== null ? current$$1.memoizedProps : null; - var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); @@ -13196,9 +13569,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { workInProgress.effectTag |= ContentReset; } - markRef(current$$1, workInProgress); + markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden. - // Check the host config to see if the children are offscreen/hidden. if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -13206,8 +13578,8 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } @@ -13224,9 +13596,9 @@ function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { function updateHostText(current$$1, workInProgress) { if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); - } - // Nothing to do here. This is terminal. We'll do the completion step + } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. + return null; } @@ -13243,22 +13615,23 @@ function mountLazyComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } - var props = workInProgress.pendingProps; - // We can't start a User Timing measurement with correct label yet. + var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet. // Cancel and resume right after we know the tag. + cancelWorkTimer(workInProgress); - var Component = readLazyComponentType(elementType); - // Store the unwrapped component in the type. + var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type. + workInProgress.type = Component; var resolvedTag = (workInProgress.tag = resolveLazyComponentTag(Component)); startWorkTimer(workInProgress); var resolvedProps = resolveDefaultProps(Component, props); - var child = void 0; + var child; + switch (resolvedTag) { case FunctionComponent: { { @@ -13267,6 +13640,7 @@ function mountLazyComponent( Component ); } + child = updateFunctionComponent( null, workInProgress, @@ -13276,12 +13650,14 @@ function mountLazyComponent( ); break; } + case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading( Component ); } + child = updateClassComponent( null, workInProgress, @@ -13291,12 +13667,14 @@ function mountLazyComponent( ); break; } + case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading( Component ); } + child = updateForwardRef( null, workInProgress, @@ -13306,10 +13684,12 @@ function mountLazyComponent( ); break; } + case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -13321,6 +13701,7 @@ function mountLazyComponent( } } } + child = updateMemoComponent( null, workInProgress, @@ -13331,8 +13712,10 @@ function mountLazyComponent( ); break; } + default: { var hint = ""; + { if ( Component !== null && @@ -13341,24 +13724,21 @@ function mountLazyComponent( ) { hint = " Did you wrap a component in React.lazy() more than once?"; } - } - // This message intentionally doesn't mention ForwardRef or MemoComponent + } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - (function() { - { - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - Component + - ". Lazy element type must resolve to a class or function." + - hint - ) - ); - } - })(); + + { + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } } } + return child; } @@ -13375,28 +13755,26 @@ function mountIncompleteClassComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect - workInProgress.effectTag |= Placement; - } - - // Promote the fiber to a class and try rendering again. - workInProgress.tag = ClassComponent; + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect - // The rest of this function is a fork of `updateClassComponent` + workInProgress.effectTag |= Placement; + } // Promote the fiber to a class and try rendering again. + workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. - var hasContext = void 0; + + var hasContext; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } - prepareToReadContext(workInProgress, renderExpirationTime); + prepareToReadContext(workInProgress, renderExpirationTime); constructClassInstance( workInProgress, Component, @@ -13409,7 +13787,6 @@ function mountIncompleteClassComponent( nextProps, renderExpirationTime ); - return finishClassComponent( null, workInProgress, @@ -13432,20 +13809,21 @@ function mountIndeterminateComponent( // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; - workInProgress.alternate = null; - // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect + workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; - var context = void 0; + var context; + if (!disableLegacyContext) { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderExpirationTime); - var value = void 0; + var value; { if ( @@ -13479,8 +13857,8 @@ function mountIndeterminateComponent( context, renderExpirationTime ); - } - // React DevTools reads this flag. + } // React DevTools reads this flag. + workInProgress.effectTag |= PerformedWork; if ( @@ -13491,6 +13869,7 @@ function mountIndeterminateComponent( ) { { var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { warningWithoutStack$1( false, @@ -13505,18 +13884,16 @@ function mountIndeterminateComponent( ); didWarnAboutModulePatternComponent[_componentName] = true; } - } + } // Proceed under the assumption that this is a class instance - // Proceed under the assumption that this is a class instance - workInProgress.tag = ClassComponent; + workInProgress.tag = ClassComponent; // Throw out any hooks that were used. - // Throw out any hooks that were used. - resetHooks(); - - // Push context providers early to prevent context stack mismatches. + resetHooks(); // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. + var hasContext = false; + if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); @@ -13526,8 +13903,8 @@ function mountIndeterminateComponent( workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; - var getDerivedStateFromProps = Component.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { applyDerivedStateFromProps( workInProgress, @@ -13550,6 +13927,7 @@ function mountIndeterminateComponent( } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; + { if (disableLegacyContext && Component.contextTypes) { warningWithoutStack$1( @@ -13578,10 +13956,13 @@ function mountIndeterminateComponent( } } } + reconcileChildren(null, workInProgress, value, renderExpirationTime); + { validateFunctionComponentInDev(workInProgress, Component); } + return workInProgress.child; } } @@ -13596,18 +13977,22 @@ function validateFunctionComponentInDev(workInProgress, Component) { ) : void 0; } + if (workInProgress.ref !== null) { var info = ""; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } var warningKey = ownerName || workInProgress._debugID || ""; var debugSource = workInProgress._debugSource; + if (debugSource) { warningKey = debugSource.fileName + ":" + debugSource.lineNumber; } + if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; warning$1( @@ -13667,8 +14052,10 @@ function validateFunctionComponentInDev(workInProgress, Component) { } } -// TODO: This is now an empty object. Should we just make it a boolean? -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { + dehydrated: null, + retryTime: NoWork +}; function shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) { // If the context is telling us that we should show a fallback, and we're not @@ -13685,9 +14072,8 @@ function updateSuspenseComponent( renderExpirationTime ) { var mode = workInProgress.mode; - var nextProps = workInProgress.pendingProps; + var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. - // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.effectTag |= DidCapture; @@ -13695,17 +14081,15 @@ function updateSuspenseComponent( } var suspenseContext = suspenseStackCursor.current; - - var nextState = null; var nextDidTimeout = false; + var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect; if ( - (workInProgress.effectTag & DidCapture) !== NoEffect || + didSuspend || shouldRemainOnFallback(suspenseContext, current$$1, workInProgress) ) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. - nextState = SUSPENDED_MARKER; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } else { @@ -13729,7 +14113,6 @@ function updateSuspenseComponent( } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); - pushSuspenseContext(workInProgress, suspenseContext); { @@ -13743,9 +14126,7 @@ function updateSuspenseComponent( ); } } - } - - // This next part is a bit confusing. If the children timeout, we switch to + } // This next part is a bit confusing. If the children timeout, we switch to // showing the fallback children in place of the "primary" children. // However, we don't want to delete the primary children because then their // state will be lost (both the React state and the host state, e.g. @@ -13767,35 +14148,30 @@ function updateSuspenseComponent( // custom reconciliation logic to preserve the state of the primary // children. It's essentially a very basic form of re-parenting. - // `child` points to the child fiber. In the normal case, this is the first - // fiber of the primary children set. In the timed-out case, it's a - // a fragment fiber containing the primary children. - var child = void 0; - // `next` points to the next fiber React should render. In the normal case, - // it's the same as `child`: the first fiber of the primary children set. - // In the timed-out case, it's a fragment fiber containing the *fallback* - // children -- we skip over the primary children entirely. - var next = void 0; if (current$$1 === null) { - if (enableSuspenseServerRenderer) { - // If we're currently hydrating, try to hydrate this boundary. - // But only if this has a fallback. - if (nextProps.fallback !== undefined) { - tryToClaimNextHydratableInstance(workInProgress); - // This could've changed the tag if this was a dehydrated suspense component. - if (workInProgress.tag === DehydratedSuspenseComponent) { - popSuspenseContext(workInProgress); - return updateDehydratedSuspenseComponent( - null, - workInProgress, - renderExpirationTime - ); + // If we're currently hydrating, try to hydrate this boundary. + // But only if this has a fallback. + if (nextProps.fallback !== undefined) { + tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. + + if (enableSuspenseServerRenderer) { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent( + workInProgress, + dehydrated, + renderExpirationTime + ); + } } } - } - - // This is the initial mount. This branch is pretty simple because there's + } // This is the initial mount. This branch is pretty simple because there's // no previous state that needs to be preserved. + if (nextDidTimeout) { // Mount separate fragments for primary and fallback children. var nextFallbackChildren = nextProps.fallback; @@ -13809,6 +14185,7 @@ function updateSuspenseComponent( if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var progressedState = workInProgress.memoizedState; var progressedPrimaryChild = progressedState !== null @@ -13816,6 +14193,7 @@ function updateSuspenseComponent( : workInProgress.child; primaryChildFragment.child = progressedPrimaryChild; var progressedChild = progressedPrimaryChild; + while (progressedChild !== null) { progressedChild.return = primaryChildFragment; progressedChild = progressedChild.sibling; @@ -13829,85 +14207,192 @@ function updateSuspenseComponent( null ); fallbackChildFragment.return = workInProgress; - primaryChildFragment.sibling = fallbackChildFragment; - child = primaryChildFragment; - // Skip the primary children, and continue working on the + primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the // fallback children. - next = fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = primaryChildFragment; + return fallbackChildFragment; } else { // Mount the primary children without an intermediate fragment fiber. var nextPrimaryChildren = nextProps.children; - child = next = mountChildFibers( + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( workInProgress, null, nextPrimaryChildren, renderExpirationTime - ); + )); } } else { // This is an update. This branch is more complicated because we need to // ensure the state of the primary children is preserved. var prevState = current$$1.memoizedState; - var prevDidTimeout = prevState !== null; - if (prevDidTimeout) { - // The current tree already timed out. That means each child set is + + if (prevState !== null) { + if (enableSuspenseServerRenderer) { + var _dehydrated = prevState.dehydrated; + + if (_dehydrated !== null) { + if (!didSuspend) { + return updateDehydratedSuspenseComponent( + current$$1, + workInProgress, + _dehydrated, + prevState, + renderExpirationTime + ); + } else if (workInProgress.memoizedState !== null) { + // Something suspended and we should still be in dehydrated mode. + // Leave the existing child in place. + workInProgress.child = current$$1.child; // The dehydrated completion pass expects this flag to be there + // but the normal suspense pass doesn't. + + workInProgress.effectTag |= DidCapture; + return null; + } else { + // Suspended but we should no longer be in dehydrated mode. + // Therefore we now have to render the fallback. Wrap the children + // in a fragment fiber to keep them separate from the fallback + // children. + var _nextFallbackChildren = nextProps.fallback; + + var _primaryChildFragment = createFiberFromFragment( + // It shouldn't matter what the pending props are because we aren't + // going to render this fragment. + null, + mode, + NoWork, + null + ); + + _primaryChildFragment.return = workInProgress; // This is always null since we never want the previous child + // that we're not going to hydrate. + + _primaryChildFragment.child = null; + + if ((workInProgress.mode & BatchedMode) === NoMode) { + // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. + var _progressedChild = (_primaryChildFragment.child = + workInProgress.child); + + while (_progressedChild !== null) { + _progressedChild.return = _primaryChildFragment; + _progressedChild = _progressedChild.sibling; + } + } else { + // We will have dropped the effect list which contains the deletion. + // We need to reconcile to delete the current child. + reconcileChildFibers( + workInProgress, + current$$1.child, + null, + renderExpirationTime + ); + } // Because primaryChildFragment is a new fiber that we're inserting as the + // parent of a new tree, we need to set its treeBaseDuration. + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // treeBaseDuration is the sum of all the child tree base durations. + var treeBaseDuration = 0; + var hiddenChild = _primaryChildFragment.child; + + while (hiddenChild !== null) { + treeBaseDuration += hiddenChild.treeBaseDuration; + hiddenChild = hiddenChild.sibling; + } + + _primaryChildFragment.treeBaseDuration = treeBaseDuration; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment = createFiberFromFragment( + _nextFallbackChildren, + mode, + renderExpirationTime, + null + ); + + _fallbackChildFragment.return = workInProgress; + _primaryChildFragment.sibling = _fallbackChildFragment; + _fallbackChildFragment.effectTag |= Placement; + _primaryChildFragment.childExpirationTime = NoWork; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment; // Skip the primary children, and continue working on the + // fallback children. + + return _fallbackChildFragment; + } + } + } // The current tree already timed out. That means each child set is + // wrapped in a fragment fiber. + var currentPrimaryChildFragment = current$$1.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + if (nextDidTimeout) { // Still timed out. Reuse the current primary children by cloning // its fragment. We're going to skip over these entirely. - var _nextFallbackChildren = nextProps.fallback; - var _primaryChildFragment = createWorkInProgress( + var _nextFallbackChildren2 = nextProps.fallback; + + var _primaryChildFragment2 = createWorkInProgress( currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork ); - _primaryChildFragment.return = workInProgress; + + _primaryChildFragment2.return = workInProgress; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState = workInProgress.memoizedState; + var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child; + if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) { - _primaryChildFragment.child = _progressedPrimaryChild; - var _progressedChild = _progressedPrimaryChild; - while (_progressedChild !== null) { - _progressedChild.return = _primaryChildFragment; - _progressedChild = _progressedChild.sibling; + _primaryChildFragment2.child = _progressedPrimaryChild; + var _progressedChild2 = _progressedPrimaryChild; + + while (_progressedChild2 !== null) { + _progressedChild2.return = _primaryChildFragment2; + _progressedChild2 = _progressedChild2.sibling; } } - } - - // Because primaryChildFragment is a new fiber that we're inserting as the + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var treeBaseDuration = 0; - var hiddenChild = _primaryChildFragment.child; - while (hiddenChild !== null) { - treeBaseDuration += hiddenChild.treeBaseDuration; - hiddenChild = hiddenChild.sibling; + var _treeBaseDuration = 0; + var _hiddenChild = _primaryChildFragment2.child; + + while (_hiddenChild !== null) { + _treeBaseDuration += _hiddenChild.treeBaseDuration; + _hiddenChild = _hiddenChild.sibling; } - _primaryChildFragment.treeBaseDuration = treeBaseDuration; - } - // Clone the fallback child fragment, too. These we'll continue + _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; + } // Clone the fallback child fragment, too. These we'll continue // working on. - var _fallbackChildFragment = createWorkInProgress( + + var _fallbackChildFragment2 = createWorkInProgress( currentFallbackChildFragment, - _nextFallbackChildren, + _nextFallbackChildren2, currentFallbackChildFragment.expirationTime ); - _fallbackChildFragment.return = workInProgress; - _primaryChildFragment.sibling = _fallbackChildFragment; - child = _primaryChildFragment; - _primaryChildFragment.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment2.return = workInProgress; + _primaryChildFragment2.sibling = _fallbackChildFragment2; + _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment2; + return _fallbackChildFragment2; } else { // No longer suspended. Switch back to showing the primary children, // and remove the intermediate fragment fiber. @@ -13918,26 +14403,27 @@ function updateSuspenseComponent( currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime - ); - - // If this render doesn't suspend, we need to delete the fallback + ); // If this render doesn't suspend, we need to delete the fallback // children. Wait until the complete phase, after we've confirmed the // fallback is no longer needed. // TODO: Would it be better to store the fallback fragment on // the stateNode? - // Continue rendering the children, like we normally do. - child = next = primaryChild; + + workInProgress.memoizedState = null; + return (workInProgress.child = primaryChild); } } else { // The current tree has not already timed out. That means the primary // children are not wrapped in a fragment fiber. var _currentPrimaryChild = current$$1.child; + if (nextDidTimeout) { // Timed out. Wrap the children in a fragment fiber to keep them // separate from the fallback children. - var _nextFallbackChildren2 = nextProps.fallback; - var _primaryChildFragment2 = createFiberFromFragment( + var _nextFallbackChildren3 = nextProps.fallback; + + var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't // going to render this fragment. null, @@ -13945,78 +14431,80 @@ function updateSuspenseComponent( NoWork, null ); - _primaryChildFragment2.return = workInProgress; - _primaryChildFragment2.child = _currentPrimaryChild; - if (_currentPrimaryChild !== null) { - _currentPrimaryChild.return = _primaryChildFragment2; - } - // Even though we're creating a new fiber, there are no new children, + _primaryChildFragment3.return = workInProgress; + _primaryChildFragment3.child = _currentPrimaryChild; + + if (_currentPrimaryChild !== null) { + _currentPrimaryChild.return = _primaryChildFragment3; + } // Even though we're creating a new fiber, there are no new children, // because we're reusing an already mounted tree. So we don't need to // schedule a placement. // primaryChildFragment.effectTag |= Placement; if ((workInProgress.mode & BatchedMode) === NoMode) { // Outside of batched mode, we commit the effects from the + // partially completed, timed-out tree, too. var _progressedState2 = workInProgress.memoizedState; + var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child; - _primaryChildFragment2.child = _progressedPrimaryChild2; - var _progressedChild2 = _progressedPrimaryChild2; - while (_progressedChild2 !== null) { - _progressedChild2.return = _primaryChildFragment2; - _progressedChild2 = _progressedChild2.sibling; - } - } - // Because primaryChildFragment is a new fiber that we're inserting as the + _primaryChildFragment3.child = _progressedPrimaryChild2; + var _progressedChild3 = _progressedPrimaryChild2; + + while (_progressedChild3 !== null) { + _progressedChild3.return = _primaryChildFragment3; + _progressedChild3 = _progressedChild3.sibling; + } + } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. - var _treeBaseDuration = 0; - var _hiddenChild = _primaryChildFragment2.child; - while (_hiddenChild !== null) { - _treeBaseDuration += _hiddenChild.treeBaseDuration; - _hiddenChild = _hiddenChild.sibling; + var _treeBaseDuration2 = 0; + var _hiddenChild2 = _primaryChildFragment3.child; + + while (_hiddenChild2 !== null) { + _treeBaseDuration2 += _hiddenChild2.treeBaseDuration; + _hiddenChild2 = _hiddenChild2.sibling; } - _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; - } - // Create a fragment from the fallback children, too. - var _fallbackChildFragment2 = createFiberFromFragment( - _nextFallbackChildren2, + _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2; + } // Create a fragment from the fallback children, too. + + var _fallbackChildFragment3 = createFiberFromFragment( + _nextFallbackChildren3, mode, renderExpirationTime, null ); - _fallbackChildFragment2.return = workInProgress; - _primaryChildFragment2.sibling = _fallbackChildFragment2; - _fallbackChildFragment2.effectTag |= Placement; - child = _primaryChildFragment2; - _primaryChildFragment2.childExpirationTime = NoWork; - // Skip the primary children, and continue working on the + + _fallbackChildFragment3.return = workInProgress; + _primaryChildFragment3.sibling = _fallbackChildFragment3; + _fallbackChildFragment3.effectTag |= Placement; + _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. - next = _fallbackChildFragment2; + + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = _primaryChildFragment3; + return _fallbackChildFragment3; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. + workInProgress.memoizedState = null; var _nextPrimaryChildren2 = nextProps.children; - next = child = reconcileChildFibers( + return (workInProgress.child = reconcileChildFibers( workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime - ); + )); } } - workInProgress.stateNode = current$$1.stateNode; } - - workInProgress.memoizedState = nextState; - workInProgress.child = child; - return next; } function retrySuspenseComponentWithoutHydrating( @@ -14024,90 +14512,95 @@ function retrySuspenseComponentWithoutHydrating( workInProgress, renderExpirationTime ) { - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; + // We're now not suspended nor dehydrated. + workInProgress.memoizedState = null; // Retry with the full children. - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - (function() { - if (!(returnFiber !== null)) { - throw ReactError( - Error( - "Suspense boundaries are never on the root. This is probably a bug in React." - ) + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; // This will ensure that the children get Placement effects and + // that the old child gets a Deletion effect. + // We could also call forceUnmountCurrentAndReconcile. + + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} + +function mountDehydratedSuspenseComponent( + workInProgress, + suspenseInstance, + renderExpirationTime +) { + // During the first pass, we'll bail out and not drill into the children. + // Instead, we'll leave the content in place and try to hydrate it later. + if ((workInProgress.mode & BatchedMode) === NoMode) { + { + warning$1( + false, + "Cannot hydrate Suspense in legacy mode. Switch from " + + "ReactDOM.hydrate(element, container) to " + + "ReactDOM.unstable_createSyncRoot(container, { hydrate: true })" + + ".render(element) or remove the Suspense components from " + + "the server rendered components." ); } - })(); - var last = returnFiber.lastEffect; - if (last !== null) { - last.nextEffect = current$$1; - returnFiber.lastEffect = current$$1; + + workInProgress.expirationTime = Sync; + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + // This is a client-only boundary. Since we won't get any content from the server + // for this, we need to schedule that at a higher priority based on when it would + // have timed out. In theory we could render it in this pass but it would have the + // wrong priority associated with it and will prevent hydration of parent path. + // Instead, we'll leave work left on it to render it in a separate commit. + // TODO This time should be the time at which the server rendered response that is + // a parent to this boundary was displayed. However, since we currently don't have + // a protocol to transfer that time, we'll just estimate it by using the current + // time. This will mean that Suspense timeouts are slightly shifted to later than + // they should be. + var serverDisplayTime = requestCurrentTime(); // Schedule a normal pri update to render this content. + + var newExpirationTime = computeAsyncExpiration(serverDisplayTime); + + if (enableSchedulerTracing) { + markSpawnedWork(newExpirationTime); + } + + workInProgress.expirationTime = newExpirationTime; } else { - returnFiber.firstEffect = returnFiber.lastEffect = current$$1; - } - current$$1.nextEffect = null; - current$$1.effectTag = Deletion; + // We'll continue hydrating the rest at offscreen priority since we'll already + // be showing the right content coming from the server, it is no rush. + workInProgress.expirationTime = Never; - popSuspenseContext(workInProgress); + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + } - // Upgrade this work in progress to a real Suspense component. - workInProgress.tag = SuspenseComponent; - workInProgress.stateNode = null; - workInProgress.memoizedState = null; - // This is now an insertion. - workInProgress.effectTag |= Placement; - // Retry as a real Suspense component. - return updateSuspenseComponent(null, workInProgress, renderExpirationTime); + return null; } function updateDehydratedSuspenseComponent( current$$1, workInProgress, + suspenseInstance, + suspenseState, renderExpirationTime ) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - var suspenseInstance = workInProgress.stateNode; - if (current$$1 === null) { - // During the first pass, we'll bail out and not drill into the children. - // Instead, we'll leave the content in place and try to hydrate it later. - if (isSuspenseInstanceFallback(suspenseInstance)) { - // This is a client-only boundary. Since we won't get any content from the server - // for this, we need to schedule that at a higher priority based on when it would - // have timed out. In theory we could render it in this pass but it would have the - // wrong priority associated with it and will prevent hydration of parent path. - // Instead, we'll leave work left on it to render it in a separate commit. - - // TODO This time should be the time at which the server rendered response that is - // a parent to this boundary was displayed. However, since we currently don't have - // a protocol to transfer that time, we'll just estimate it by using the current - // time. This will mean that Suspense timeouts are slightly shifted to later than - // they should be. - var serverDisplayTime = requestCurrentTime(); - // Schedule a normal pri update to render this content. - workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime); - } else { - // We'll continue hydrating the rest at offscreen priority since we'll already - // be showing the right content coming from the server, it is no rush. - workInProgress.expirationTime = Never; - } - return null; - } - - if ((workInProgress.effectTag & DidCapture) !== NoEffect) { - // Something suspended. Leave the existing children in place. - // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far? - workInProgress.child = null; - return null; - } - // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); + if ((workInProgress.mode & BatchedMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime + ); + } + if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the @@ -14117,18 +14610,38 @@ function updateDehydratedSuspenseComponent( workInProgress, renderExpirationTime ); - } - // We use childExpirationTime to indicate that a child might depend on context, so if + } // We use childExpirationTime to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. + var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime; + if (didReceiveUpdate || hasContextChanged$$1) { // This boundary has changed since the first render. This means that we are now unable to - // hydrate it. We might still be able to hydrate it using an earlier expiration time but - // during this render we can't. Instead, we're going to delete the whole subtree and - // instead inject a new real Suspense boundary to take its place, which may render content - // or fallback. The real Suspense boundary will suspend for a while so we have some time - // to ensure it can produce real content, but all state and pending events will be lost. + // hydrate it. We might still be able to hydrate it using an earlier expiration time, if + // we are rendering at lower expiration than sync. + if (renderExpirationTime < Sync) { + if (suspenseState.retryTime <= renderExpirationTime) { + // This render is even higher pri than we've seen before, let's try again + // at even higher pri. + var attemptHydrationAtExpirationTime = renderExpirationTime + 1; + suspenseState.retryTime = attemptHydrationAtExpirationTime; + scheduleWork(current$$1, attemptHydrationAtExpirationTime); // TODO: Early abort this render. + } else { + // We have already tried to ping at a higher priority than we're rendering with + // so if we got here, we must have failed to hydrate at those levels. We must + // now give up. Instead, we're going to delete the whole subtree and instead inject + // a new real Suspense boundary to take its place, which may render content + // or fallback. This might suspend for a while and if it does we might still have + // an opportunity to hydrate before this pass commits. + } + } // If we have scheduled higher pri work above, this will probably just abort the render + // since we now have higher priority work, but in case it doesn't, we need to prepare to + // render something, if we time out. Even if that requires us to delete everything and + // skip hydration. + // Delay having to do this as long as the suspense timeout allows us. + + renderDidSuspendDelayIfPossible(); return retrySuspenseComponentWithoutHydrating( current$$1, workInProgress, @@ -14144,30 +14657,61 @@ function updateDehydratedSuspenseComponent( // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). - workInProgress.effectTag |= DidCapture; - // Leave the children in place. I.e. empty. - workInProgress.child = null; - // Register a callback to retry this boundary once the server has sent the result. + workInProgress.effectTag |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. + + workInProgress.child = current$$1.child; // Register a callback to retry this boundary once the server has sent the result. + registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryDehydratedSuspenseBoundary.bind(null, current$$1) ); return null; } else { // This is the first attempt. - reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress); + reenterHydrationStateFromDehydratedSuspenseInstance( + workInProgress, + suspenseInstance + ); var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; - workInProgress.child = mountChildFibers( + var child = mountChildFibers( workInProgress, null, nextChildren, renderExpirationTime ); + var node = child; + + while (node) { + // Mark each child as hydrating. This is a fast path to know whether this + // tree is part of a hydrating tree. This is used to determine if a child + // node has fully mounted yet, and for scheduling event replaying. + // Conceptually this is similar to Placement in that a new subtree is + // inserted into the React tree here. It just happens to not need DOM + // mutations because it already exists. + node.effectTag |= Hydrating; + node = node.sibling; + } + + workInProgress.child = child; return workInProgress.child; } } +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + if (fiber.expirationTime < renderExpirationTime) { + fiber.expirationTime = renderExpirationTime; + } + + var alternate = fiber.alternate; + + if (alternate !== null && alternate.expirationTime < renderExpirationTime) { + alternate.expirationTime = renderExpirationTime; + } + + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); +} + function propagateSuspenseContextChange( workInProgress, firstChild, @@ -14177,36 +14721,39 @@ function propagateSuspenseContextChange( // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; + while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; + if (state !== null) { - if (node.expirationTime < renderExpirationTime) { - node.expirationTime = renderExpirationTime; - } - var alternate = node.alternate; - if ( - alternate !== null && - alternate.expirationTime < renderExpirationTime - ) { - alternate.expirationTime = renderExpirationTime; - } - scheduleWorkOnParentPath(node.return, renderExpirationTime); - } + scheduleWorkOnFiber(node, renderExpirationTime); + } + } else if (node.tag === SuspenseListComponent) { + // If the tail is hidden there might not be an Suspense boundaries + // to schedule work on. In this case we have to schedule it on the + // list itself. + // We don't have to traverse to the children of the list since + // the list will propagate the change when it rerenders. + scheduleWorkOnFiber(node, renderExpirationTime); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -14222,14 +14769,17 @@ function findLastContentRow(firstChild) { // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } + row = row.sibling; } + return lastContentRow; } @@ -14243,6 +14793,7 @@ function validateRevealOrder(revealOrder) { !didWarnAboutRevealOrder[revealOrder] ) { didWarnAboutRevealOrder[revealOrder] = true; + if (typeof revealOrder === "string") { switch (revealOrder.toLowerCase()) { case "together": @@ -14257,6 +14808,7 @@ function validateRevealOrder(revealOrder) { ); break; } + case "forward": case "backward": { warning$1( @@ -14268,6 +14820,7 @@ function validateRevealOrder(revealOrder) { ); break; } + default: warning$1( false, @@ -14318,6 +14871,7 @@ function validateSuspenseListNestedChild(childSlot, index) { { var isArray = Array.isArray(childSlot); var isIterable = !isArray && typeof getIteratorFn(childSlot) === "function"; + if (isArray || isIterable) { var type = isArray ? "array" : "iterable"; warning$1( @@ -14334,6 +14888,7 @@ function validateSuspenseListNestedChild(childSlot, index) { return false; } } + return true; } @@ -14353,15 +14908,19 @@ function validateSuspenseListChildren(children, revealOrder) { } } else { var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { var childrenIterator = iteratorFn.call(children); + if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; + for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } + _i++; } } @@ -14384,9 +14943,11 @@ function initSuspenseListRenderState( isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; + if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, @@ -14394,7 +14955,8 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }; } else { // We can reuse the existing object from previous renders. @@ -14404,16 +14966,16 @@ function initSuspenseListRenderState( renderState.tail = tail; renderState.tailExpiration = 0; renderState.tailMode = tailMode; + renderState.lastEffect = lastEffectBeforeRendering; } -} - -// This can end up rendering this component multiple passes. +} // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. + function updateSuspenseListComponent( current$$1, workInProgress, @@ -14423,24 +14985,21 @@ function updateSuspenseListComponent( var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; - validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); - reconcileChildren( current$$1, workInProgress, newChildren, renderExpirationTime ); - var suspenseContext = suspenseStackCursor.current; - var shouldForceFallback = hasSuspenseContext( suspenseContext, ForceSuspenseFallback ); + if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -14450,6 +15009,7 @@ function updateSuspenseListComponent( } else { var didSuspendBefore = current$$1 !== null && (current$$1.effectTag & DidCapture) !== NoEffect; + if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render @@ -14460,8 +15020,10 @@ function updateSuspenseListComponent( renderExpirationTime ); } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } + pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & BatchedMode) === NoMode) { @@ -14472,7 +15034,8 @@ function updateSuspenseListComponent( switch (revealOrder) { case "forwards": { var lastContentRow = findLastContentRow(workInProgress.child); - var tail = void 0; + var tail; + if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. @@ -14484,15 +15047,18 @@ function updateSuspenseListComponent( tail = lastContentRow.sibling; lastContentRow.sibling = null; } + initSuspenseListRenderState( workInProgress, false, // isBackwards tail, lastContentRow, - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "backwards": { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything @@ -14501,39 +15067,45 @@ function updateSuspenseListComponent( var _tail = null; var row = workInProgress.child; workInProgress.child = null; + while (row !== null) { - var currentRow = row.alternate; - // New rows can't be content rows. + var currentRow = row.alternate; // New rows can't be content rows. + if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } + var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; - } - // TODO: If workInProgress.child is null, we can continue on the tail immediately. + } // TODO: If workInProgress.child is null, we can continue on the tail immediately. + initSuspenseListRenderState( workInProgress, true, // isBackwards _tail, null, // last - tailMode + tailMode, + workInProgress.lastEffect ); break; } + case "together": { initSuspenseListRenderState( workInProgress, false, // isBackwards null, // tail null, // last - undefined + undefined, + workInProgress.lastEffect ); break; } + default: { // The default reveal order is the same as not having // a boundary. @@ -14541,6 +15113,7 @@ function updateSuspenseListComponent( } } } + return workInProgress.child; } @@ -14551,6 +15124,7 @@ function updatePortalComponent( ) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; + if (current$$1 === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal @@ -14571,6 +15145,7 @@ function updatePortalComponent( renderExpirationTime ); } + return workInProgress.child; } @@ -14581,10 +15156,8 @@ function updateContextProvider( ) { var providerType = workInProgress.type; var context = providerType._context; - var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; - var newValue = newProps.value; { @@ -14606,6 +15179,7 @@ function updateContextProvider( if (oldProps !== null) { var oldValue = oldProps.value; var changedBits = calculateChangedBits(context, newValue, oldValue); + if (changedBits === 0) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { @@ -14644,14 +15218,14 @@ function updateContextConsumer( workInProgress, renderExpirationTime ) { - var context = workInProgress.type; - // The logic below for Context differs depending on PROD or DEV mode. In + var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. + { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). @@ -14671,6 +15245,7 @@ function updateContextConsumer( context = context._context; } } + var newProps = workInProgress.pendingProps; var render = newProps.children; @@ -14688,15 +15263,15 @@ function updateContextConsumer( prepareToReadContext(workInProgress, renderExpirationTime); var newValue = readContext(context, newProps.unstable_observedBits); - var newChildren = void 0; + var newChildren; + { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase("render"); newChildren = render(newValue); setCurrentPhase(null); - } + } // React DevTools reads this flag. - // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren( current$$1, @@ -14713,12 +15288,29 @@ function updateFundamentalComponent$1( renderExpirationTime ) { var fundamentalImpl = workInProgress.type.impl; + if (fundamentalImpl.reconcileChildren === false) { return null; } + var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + return workInProgress.child; +} +function updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; reconcileChildren( current$$1, workInProgress, @@ -14749,8 +15341,14 @@ function bailoutOnAlreadyFinishedWork( stopProfilerTimerIfRunning(workInProgress); } - // Check if the children have any pending work. + var updateExpirationTime = workInProgress.expirationTime; + + if (updateExpirationTime !== NoWork) { + markUnprocessedUpdateTime(updateExpirationTime); + } // Check if the children have any pending work. + var childExpirationTime = workInProgress.childExpirationTime; + if (childExpirationTime < renderExpirationTime) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are @@ -14767,53 +15365,54 @@ function bailoutOnAlreadyFinishedWork( function remountFiber(current$$1, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { throw new Error("Cannot swap the root fiber."); - } - - // Disconnect from the old current. + } // Disconnect from the old current. // It will get deleted. + current$$1.alternate = null; - oldWorkInProgress.alternate = null; + oldWorkInProgress.alternate = null; // Connect to the new tree. - // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; - newWorkInProgress.ref = oldWorkInProgress.ref; + newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. - // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; + if (prevSibling === null) { throw new Error("Expected parent to have a child."); } + while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; + if (prevSibling === null) { throw new Error("Expected to find the previous sibling."); } } - prevSibling.sibling = newWorkInProgress; - } - // Delete the old fiber and place the new one. + prevSibling.sibling = newWorkInProgress; + } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. + var last = returnFiber.lastEffect; + if (last !== null) { last.nextEffect = current$$1; returnFiber.lastEffect = current$$1; } else { returnFiber.firstEffect = returnFiber.lastEffect = current$$1; } + current$$1.nextEffect = null; current$$1.effectTag = Deletion; + newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber. - newWorkInProgress.effectTag |= Placement; - - // Restart work from the new fiber. return newWorkInProgress; } } @@ -14845,25 +15444,26 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { if ( oldProps !== newProps || - hasContextChanged() || - // Force a re-render if the implementation changed due to hot reload: + hasContextChanged() || // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current$$1.type ) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else if (updateExpirationTime < renderExpirationTime) { - didReceiveUpdate = false; - // This fiber does not have any pending work. Bailout without entering + didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. + switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); resetHydrationState(); break; + case HostComponent: pushHostContext(workInProgress); + if ( workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && @@ -14871,45 +15471,69 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { ) { if (enableSchedulerTracing) { markSpawnedWork(Never); - } - // Schedule this fiber to re-render at offscreen priority. Then bailout. + } // Schedule this fiber to re-render at offscreen priority. Then bailout. + workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } + break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { pushContextProvider(workInProgress); } + break; } + case HostPortal: pushHostContainer( workInProgress, workInProgress.stateNode.containerInfo ); break; + case ContextProvider: { var newValue = workInProgress.memoizedProps.value; pushProvider(workInProgress, newValue); break; } + case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; } + break; + case SuspenseComponent: { var state = workInProgress.memoizedState; - var didTimeout = state !== null; - if (didTimeout) { - // If this boundary is currently timed out, we need to decide + + if (state !== null) { + if (enableSuspenseServerRenderer) { + if (state.dehydrated !== null) { + pushSuspenseContext( + workInProgress, + setDefaultShallowSuspenseContext(suspenseStackCursor.current) + ); // We know that this component will suspend again because if it has + // been unsuspended it has committed as a resolved Suspense component. + // If it needs to be retried, it should have work scheduled on it. + + workInProgress.effectTag |= DidCapture; + break; + } + } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary + // child fragment. + var primaryChildFragment = workInProgress.child; var primaryChildExpirationTime = primaryChildFragment.childExpirationTime; + if ( primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime @@ -14925,14 +15549,15 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { pushSuspenseContext( workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // The primary children do not have pending work with sufficient + ); // The primary children do not have pending work with sufficient // priority. Bailout. + var child = bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. @@ -14947,25 +15572,13 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { setDefaultShallowSuspenseContext(suspenseStackCursor.current) ); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - pushSuspenseContext( - workInProgress, - setDefaultShallowSuspenseContext(suspenseStackCursor.current) - ); - // We know that this component will suspend again because if it has - // been unsuspended it has committed as a regular Suspense component. - // If it needs to be retried, it should have work scheduled on it. - workInProgress.effectTag |= DidCapture; - } - break; - } + case SuspenseListComponent: { var didSuspendBefore = (current$$1.effectTag & DidCapture) !== NoEffect; - var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime; @@ -14981,23 +15594,24 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { workInProgress, renderExpirationTime ); - } - // If none of the children had any work, that means that none of + } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. - workInProgress.effectTag |= DidCapture; - } - // If nothing suspended before and we're rendering the same children, + workInProgress.effectTag |= DidCapture; + } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. + var renderState = workInProgress.memoizedState; + if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; } + pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (hasChildWork) { @@ -15010,17 +15624,23 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + return bailoutOnAlreadyFinishedWork( current$$1, workInProgress, renderExpirationTime ); + } else { + // An update was scheduled on this fiber, but there are no new props + // nor legacy context. Set this to false. If an update queue or context + // consumer produces a changed value, it will set this to true. Otherwise, + // the component will assume the children have not changed and bail out. + didReceiveUpdate = false; } } else { didReceiveUpdate = false; - } + } // Before entering the begin phase, clear the expiration time. - // Before entering the begin phase, clear the expiration time. workInProgress.expirationTime = NoWork; switch (workInProgress.tag) { @@ -15032,6 +15652,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent( @@ -15042,6 +15663,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FunctionComponent: { var _Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; @@ -15057,13 +15679,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case ClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; + var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps); + return updateClassComponent( current$$1, workInProgress, @@ -15072,35 +15697,43 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case HostRoot: return updateHostRoot(current$$1, workInProgress, renderExpirationTime); + case HostComponent: return updateHostComponent( current$$1, workInProgress, renderExpirationTime ); + case HostText: return updateHostText(current$$1, workInProgress); + case SuspenseComponent: return updateSuspenseComponent( current$$1, workInProgress, renderExpirationTime ); + case HostPortal: return updatePortalComponent( current$$1, workInProgress, renderExpirationTime ); + case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; + var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef( current$$1, workInProgress, @@ -15109,32 +15742,40 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case Fragment: return updateFragment(current$$1, workInProgress, renderExpirationTime); + case Mode: return updateMode(current$$1, workInProgress, renderExpirationTime); + case Profiler: return updateProfiler(current$$1, workInProgress, renderExpirationTime); + case ContextProvider: return updateContextProvider( current$$1, workInProgress, renderExpirationTime ); + case ContextConsumer: return updateContextConsumer( current$$1, workInProgress, renderExpirationTime ); + case MemoComponent: { var _type2 = workInProgress.type; - var _unresolvedProps3 = workInProgress.pendingProps; - // Resolve outer props first, then resolve inner props. + var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { checkPropTypes( outerPropTypes, @@ -15146,6 +15787,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { } } } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent( current$$1, @@ -15156,6 +15798,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case SimpleMemoComponent: { return updateSimpleMemoComponent( current$$1, @@ -15166,13 +15809,16 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case IncompleteClassComponent: { var _Component3 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; + var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4); + return mountIncompleteClassComponent( current$$1, workInProgress, @@ -15181,16 +15827,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - return updateDehydratedSuspenseComponent( - current$$1, - workInProgress, - renderExpirationTime - ); - } - break; - } + case SuspenseListComponent: { return updateSuspenseListComponent( current$$1, @@ -15198,6 +15835,7 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + case FundamentalComponent: { if (enableFundamentalAPI) { return updateFundamentalComponent$1( @@ -15206,18 +15844,30 @@ function beginWork$1(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + break; } - } - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + return updateScopeComponent( + current$$1, + workInProgress, + renderExpirationTime + ); + } + + break; } - })(); + } + + { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." + ); + } } function createFundamentalStateInstance(currentFiber, props, impl, state) { @@ -15231,8 +15881,212 @@ function createFundamentalStateInstance(currentFiber, props, impl, state) { }; } -var emptyObject$1 = {}; -var isArray$2 = Array.isArray; +function isFiberSuspenseAndTimedOut(fiber) { + return fiber.tag === SuspenseComponent && fiber.memoizedState !== null; +} + +function getSuspenseFallbackChild(fiber) { + return fiber.child.sibling.child; +} + +function collectScopedNodes(node, fn, scopedNodes) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type, memoizedProps) === true) { + scopedNodes.push(getPublicInstance(node.stateNode)); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + } +} + +function collectFirstScopedNode(node, fn) { + if (enableScopeAPI) { + if (node.tag === HostComponent) { + var _type2 = node.type, + memoizedProps = node.memoizedProps; + + if (fn(_type2, memoizedProps) === true) { + return getPublicInstance(node.stateNode); + } + } + + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + } + + return null; +} + +function collectScopedNodesFromChildren(startingChild, fn, scopedNodes) { + var child = startingChild; + + while (child !== null) { + collectScopedNodes(child, fn, scopedNodes); + child = child.sibling; + } +} + +function collectFirstScopedNodeFromChildren(startingChild, fn) { + var child = startingChild; + + while (child !== null) { + var scopedNode = collectFirstScopedNode(child, fn); + + if (scopedNode !== null) { + return scopedNode; + } + + child = child.sibling; + } + + return null; +} + +function collectNearestScopeMethods(node, scope, childrenScopes) { + if (isValidScopeNode(node, scope)) { + childrenScopes.push(node.stateNode.methods); + } else { + var child = node.child; + + if (isFiberSuspenseAndTimedOut(node)) { + child = getSuspenseFallbackChild(node); + } + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + } +} + +function collectNearestChildScopeMethods(startingChild, scope, childrenScopes) { + var child = startingChild; + + while (child !== null) { + collectNearestScopeMethods(child, scope, childrenScopes); + child = child.sibling; + } +} + +function isValidScopeNode(node, scope) { + return ( + node.tag === ScopeComponent && + node.type === scope && + node.stateNode !== null + ); +} + +function createScopeMethods(scope, instance) { + return { + getChildren: function() { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var childrenScopes = []; + + if (child !== null) { + collectNearestChildScopeMethods(child, scope, childrenScopes); + } + + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getChildrenFromRoot: function() { + var currentFiber = instance.fiber; + var node = currentFiber; + + while (node !== null) { + var parent = node.return; + + if (parent === null) { + break; + } + + node = parent; + + if (node.tag === ScopeComponent && node.type === scope) { + break; + } + } + + var childrenScopes = []; + collectNearestChildScopeMethods(node.child, scope, childrenScopes); + return childrenScopes.length === 0 ? null : childrenScopes; + }, + getParent: function() { + var node = instance.fiber.return; + + while (node !== null) { + if (node.tag === ScopeComponent && node.type === scope) { + return node.stateNode.methods; + } + + node = node.return; + } + + return null; + }, + getProps: function() { + var currentFiber = instance.fiber; + return currentFiber.memoizedProps; + }, + queryAllNodes: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + var scopedNodes = []; + + if (child !== null) { + collectScopedNodesFromChildren(child, fn, scopedNodes); + } + + return scopedNodes.length === 0 ? null : scopedNodes; + }, + queryFirstNode: function(fn) { + var currentFiber = instance.fiber; + var child = currentFiber.child; + + if (child !== null) { + return collectFirstScopedNodeFromChildren(child, fn); + } + + return null; + }, + containsNode: function(node) { + var fiber = getInstanceFromNode$1(node); + + while (fiber !== null) { + if ( + fiber.tag === ScopeComponent && + fiber.type === scope && + fiber.stateNode === instance + ) { + return true; + } + + fiber = fiber.return; + } + + return false; + } + }; +} function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into @@ -15244,13 +16098,13 @@ function markRef$1(workInProgress) { workInProgress.effectTag |= Ref; } -var appendAllChildren = void 0; -var updateHostContainer = void 0; -var updateHostComponent$1 = void 0; -var updateHostText$1 = void 0; +var appendAllChildren; +var updateHostContainer; +var updateHostComponent$1; +var updateHostText$1; + if (supportsMutation) { // Mutation mode - appendAllChildren = function( parent, workInProgress, @@ -15260,6 +16114,7 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); @@ -15274,15 +16129,19 @@ if (supportsMutation) { node = node.child; continue; } + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -15291,6 +16150,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15301,21 +16161,21 @@ if (supportsMutation) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; + if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; - } - - // If we get updated because one of our children updated, we don't + } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. + var instance = workInProgress.stateNode; - var currentHostContext = getHostContext(); - // TODO: Experiencing an error where oldProps is null. Suggests a host + var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. + var updatePayload = prepareUpdate( instance, type, @@ -15323,15 +16183,16 @@ if (supportsMutation) { newProps, rootContainerInstance, currentHostContext - ); - // TODO: Type this specific to this type of component. - workInProgress.updateQueue = updatePayload; - // If the update payload indicates that there is a change or if there + ); // TODO: Type this specific to this type of component. + + workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. + if (updatePayload) { markUpdate(workInProgress); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { @@ -15340,7 +16201,6 @@ if (supportsMutation) { }; } else if (supportsPersistence) { // Persistent host tree mode - appendAllChildren = function( parent, workInProgress, @@ -15350,33 +16210,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance = cloneHiddenTextInstance(_instance, text, node); } + appendInitialChild(parent, _instance); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance2 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props = node.memoizedProps; var _type = node.type; _instance2 = cloneHiddenInstance(_instance2, _type, _props, node); } + appendInitialChild(parent, _instance2); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15386,8 +16253,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15398,7 +16267,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15407,6 +16278,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15417,24 +16289,27 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } - }; + }; // An unfortunate fork of appendAllChildren because we have two different parent types. - // An unfortunate fork of appendAllChildren because we have two different parent types. var appendAllChildrenToContainer = function( containerChildSet, workInProgress, @@ -15444,33 +16319,40 @@ if (supportsMutation) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; + while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; instance = cloneHiddenInstance(instance, type, props, node); } + appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; _instance3 = cloneHiddenTextInstance(_instance3, text, node); } + appendChildToContainerChildSet(containerChildSet, _instance3); } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var _instance4 = node.stateNode.instance; + if (needsVisibilityToggle && isHidden) { // This child is inside a timed out tree. Hide it. var _props2 = node.memoizedProps; var _type2 = node.type; _instance4 = cloneHiddenInstance(_instance4, _type2, _props2, node); } + appendChildToContainerChildSet(containerChildSet, _instance4); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse @@ -15480,8 +16362,10 @@ if (supportsMutation) { if ((node.effectTag & Update) !== NoEffect) { // Need to toggle the visibility of the primary children. var newIsHidden = node.memoizedState !== null; + if (newIsHidden) { var primaryChildParent = node.child; + if (primaryChildParent !== null) { if (primaryChildParent.child !== null) { primaryChildParent.child.return = primaryChildParent; @@ -15492,7 +16376,9 @@ if (supportsMutation) { newIsHidden ); } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { fallbackChildParent.return = node; node = fallbackChildParent; @@ -15501,6 +16387,7 @@ if (supportsMutation) { } } } + if (node.child !== null) { // Continue traversing like normal node.child.return = node; @@ -15511,38 +16398,45 @@ if (supportsMutation) { node.child.return = node; node = node.child; continue; - } - // $FlowFixMe This is correct but Flow is confused by the labeled break. + } // $FlowFixMe This is correct but Flow is confused by the labeled break. + node = node; + if (node === workInProgress) { return; } + while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } }; + updateHostContainer = function(workInProgress) { var portalOrRoot = workInProgress.stateNode; var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged) { // No changes, just reuse the existing instance. } else { var container = portalOrRoot.containerInfo; - var newChildSet = createContainerChildSet(container); - // If children might have changed, we have to add them all to the set. + var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. + appendAllChildrenToContainer(newChildSet, workInProgress, false, false); - portalOrRoot.pendingChildren = newChildSet; - // Schedule an update on the container to swap out the container. + portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. + markUpdate(workInProgress); finalizeContainerChildren(container, newChildSet); } }; + updateHostComponent$1 = function( current, workInProgress, @@ -15551,19 +16445,22 @@ if (supportsMutation) { rootContainerInstance ) { var currentInstance = current.stateNode; - var oldProps = current.memoizedProps; - // If there are no effects associated with this node, then none of our children had any updates. + var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. // This guarantees that we can reuse all of them. + var childrenUnchanged = workInProgress.firstEffect === null; + if (childrenUnchanged && oldProps === newProps) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var recyclableInstance = workInProgress.stateNode; var currentHostContext = getHostContext(); var updatePayload = null; + if (oldProps !== newProps) { updatePayload = prepareUpdate( recyclableInstance, @@ -15574,12 +16471,14 @@ if (supportsMutation) { currentHostContext ); } + if (childrenUnchanged && updatePayload === null) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } + var newInstance = cloneInstance( currentInstance, updatePayload, @@ -15590,6 +16489,7 @@ if (supportsMutation) { childrenUnchanged, recyclableInstance ); + if ( finalizeInitialChildren( newInstance, @@ -15601,7 +16501,9 @@ if (supportsMutation) { ) { markUpdate(workInProgress); } + workInProgress.stateNode = newInstance; + if (childrenUnchanged) { // If there are no other effects in this tree, we need to flag this node as having one. // Even though we're not going to use it for anything. @@ -15612,6 +16514,7 @@ if (supportsMutation) { appendAllChildren(newInstance, workInProgress, false, false); } }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { if (oldText !== newText) { // If the text content differs, we'll create a new text instance for it. @@ -15622,9 +16525,9 @@ if (supportsMutation) { rootContainerInstance, currentHostContext, workInProgress - ); - // We'll have to mark it as having an effect, even though we won't use the effect for anything. + ); // We'll have to mark it as having an effect, even though we won't use the effect for anything. // This lets the parents know that at least one of their children has changed. + markUpdate(workInProgress); } }; @@ -15633,6 +16536,7 @@ if (supportsMutation) { updateHostContainer = function(workInProgress) { // Noop }; + updateHostComponent$1 = function( current, workInProgress, @@ -15642,6 +16546,7 @@ if (supportsMutation) { ) { // Noop }; + updateHostText$1 = function(current, workInProgress, oldText, newText) { // Noop }; @@ -15657,14 +16562,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var tailNode = renderState.tail; var lastTailNode = null; + while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } + tailNode = tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; @@ -15673,8 +16580,10 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. lastTailNode.sibling = null; } + break; } + case "collapsed": { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries @@ -15683,14 +16592,16 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; + while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } + _tailNode = _tailNode.sibling; - } - // Next we're simply going to delete all insertions after the + } // Next we're simply going to delete all insertions after the // last rendered item. + if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { @@ -15705,6 +16616,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { // inserted. _lastTailNode.sibling = null; } + break; } } @@ -15716,41 +16628,55 @@ function completeWork(current, workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case IndeterminateComponent: break; + case LazyComponent: break; + case SimpleMemoComponent: case FunctionComponent: break; + case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + break; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var fiberRoot = workInProgress.stateNode; + if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } + if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. - popHydrationState(workInProgress); - // This resets the hacky state to fix isMounted before committing. - // TODO: Delete this when we delete isMounted and findDOMNode. - workInProgress.effectTag &= ~Placement; + var wasHydrated = popHydrationState(workInProgress); + + if (wasHydrated) { + // If we hydrated, then we'll need to schedule an update for + // the commit side-effects on the root. + markUpdate(workInProgress); + } } + updateHostContainer(workInProgress); break; } + case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; + if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1( current, @@ -15763,14 +16689,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableFlareAPI) { var prevListeners = current.memoizedProps.listeners; var nextListeners = newProps.listeners; - var instance = workInProgress.stateNode; + if (prevListeners !== nextListeners) { - updateEventListeners( - nextListeners, - instance, - rootContainerInstance, - workInProgress - ); + markUpdate(workInProgress); } } @@ -15779,26 +16700,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. + break; } - var currentHostContext = getHostContext(); - // TODO: Move createInstance to beginWork and keep it on a context + var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on we want to add then top->down or // bottom->up. Top->down is faster in IE11. - var wasHydrated = popHydrationState(workInProgress); - if (wasHydrated) { + + var _wasHydrated = popHydrationState(workInProgress); + + if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if ( @@ -15812,47 +16730,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { // commit-phase we mark this as such. markUpdate(workInProgress); } + if (enableFlareAPI) { - var _instance5 = workInProgress.stateNode; var listeners = newProps.listeners; + if (listeners != null) { updateEventListeners( listeners, - _instance5, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } } } else { - var _instance6 = createInstance( + var instance = createInstance( type, newProps, rootContainerInstance, currentHostContext, workInProgress ); + appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners - appendAllChildren(_instance6, workInProgress, false, false); + workInProgress.stateNode = instance; if (enableFlareAPI) { var _listeners = newProps.listeners; + if (_listeners != null) { updateEventListeners( _listeners, - _instance6, - rootContainerInstance, - workInProgress + workInProgress, + rootContainerInstance ); } - } - - // Certain renderers require commit-time effects for initial mount. + } // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. + if ( finalizeInitialChildren( - _instance6, + instance, type, newProps, rootContainerInstance, @@ -15861,7 +16779,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { ) { markUpdate(workInProgress); } - workInProgress.stateNode = _instance6; } if (workInProgress.ref !== null) { @@ -15869,32 +16786,34 @@ function completeWork(current, workInProgress, renderExpirationTime) { markRef$1(workInProgress); } } + break; } + case HostText: { var newText = newProps; + if (current && workInProgress.stateNode != null) { - var oldText = current.memoizedProps; - // If we have an alternate, that means this is an update and we need + var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. + updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - (function() { - if (!(workInProgress.stateNode !== null)) { - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - // This can happen when we abort work. + if (!(workInProgress.stateNode !== null)) { + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." + ); + } // This can happen when we abort work. } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); - var _wasHydrated = popHydrationState(workInProgress); - if (_wasHydrated) { + + var _wasHydrated2 = popHydrationState(workInProgress); + + if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } @@ -15907,38 +16826,86 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); } } + break; } + case ForwardRef: break; + case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; + + if (enableSuspenseServerRenderer) { + if (nextState !== null && nextState.dehydrated !== null) { + if (current === null) { + var _wasHydrated3 = popHydrationState(workInProgress); + + if (!_wasHydrated3) { + throw Error( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + + prepareToHydrateHostSuspenseInstance(workInProgress); + + if (enableSchedulerTracing) { + markSpawnedWork(Never); + } + + return null; + } else { + // We should never have been in a hydration state if we didn't have a current. + // However, in some of those paths, we might have reentered a hydration state + // and then we might be inside a hydration state. In that case, we'll need to + // exit out of it. + resetHydrationState(); + + if ((workInProgress.effectTag & DidCapture) === NoEffect) { + // This boundary did not suspend so it's now hydrated and unsuspended. + workInProgress.memoizedState = null; + } // If nothing suspended, we need to schedule an effect to mark this boundary + // as having hydrated so events know that they're free be invoked. + // It's also a signal to replay events and the suspense callback. + // If something suspended, schedule an effect to attach retry listeners. + // So we might as well always mark this. + + workInProgress.effectTag |= Update; + return null; + } + } + } + if ((workInProgress.effectTag & DidCapture) !== NoEffect) { // Something suspended. Re-render with the fallback children. - workInProgress.expirationTime = renderExpirationTime; - // Do not reset the effect list. + workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list. + return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = false; + if (current === null) { - // In cases where we didn't find a suitable hydration boundary we never - // downgraded this to a DehydratedSuspenseComponent, but we still need to - // pop the hydration state since we might be inside the insertion tree. - popHydrationState(workInProgress); + if (workInProgress.memoizedProps.fallback !== undefined) { + popHydrationState(workInProgress); + } } else { var prevState = current.memoizedState; prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { // We just switched from the fallback to the normal children. // Delete the fallback. // TODO: Would it be better to store the fallback fragment on + // the stateNode during the begin phase? var currentFallbackChild = current.child.sibling; + if (currentFallbackChild !== null) { // Deletions go at the beginning of the return fiber's effect list var first = workInProgress.firstEffect; + if (first !== null) { workInProgress.firstEffect = currentFallbackChild; currentFallbackChild.nextEffect = first; @@ -15946,6 +16913,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; currentFallbackChild.nextEffect = null; } + currentFallbackChild.effectTag = Deletion; } } @@ -15968,6 +16936,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true; + if ( hasInvisibleChildContext || hasSuspenseContext( @@ -15995,6 +16964,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if (supportsMutation) { // TODO: Only schedule updates if these values are non equal, i.e. it changed. if (nextDidTimeout || prevDidTimeout) { @@ -16006,6 +16976,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.effectTag |= Update; } } + if ( enableSuspenseCallback && workInProgress.updateQueue !== null && @@ -16014,76 +16985,49 @@ function completeWork(current, workInProgress, renderExpirationTime) { // Always notify the callback workInProgress.effectTag |= Update; } + break; } + case Fragment: break; + case Mode: break; + case Profiler: break; + case HostPortal: popHostContainer(workInProgress); updateHostContainer(workInProgress); break; + case ContextProvider: // Pop provider fiber popProvider(workInProgress); break; + case ContextConsumer: break; + case MemoComponent: break; + case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; + if (isContextProvider(_Component)) { popContext(workInProgress); } + break; } - case DehydratedSuspenseComponent: { - if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (current === null) { - var _wasHydrated2 = popHydrationState(workInProgress); - (function() { - if (!_wasHydrated2) { - throw ReactError( - Error( - "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." - ) - ); - } - })(); - if (enableSchedulerTracing) { - markSpawnedWork(Never); - } - skipPastDehydratedSuspenseInstance(workInProgress); - } else { - // We should never have been in a hydration state if we didn't have a current. - // However, in some of those paths, we might have reentered a hydration state - // and then we might be inside a hydration state. In that case, we'll need to - // exit out of it. - resetHydrationState(); - if ((workInProgress.effectTag & DidCapture) === NoEffect) { - // This boundary did not suspend so it's now hydrated. - // To handle any future suspense cases, we're going to now upgrade it - // to a Suspense component. We detach it from the existing current fiber. - current.alternate = null; - workInProgress.alternate = null; - workInProgress.tag = SuspenseComponent; - workInProgress.memoizedState = null; - workInProgress.stateNode = null; - } - } - } - break; - } + case SuspenseListComponent: { popSuspenseContext(workInProgress); - var renderState = workInProgress.memoizedState; if (renderState === null) { @@ -16094,18 +17038,16 @@ function completeWork(current, workInProgress, renderExpirationTime) { var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect; - var renderedTail = renderState.rendering; + if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. - // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. - // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to @@ -16113,16 +17055,17 @@ function completeWork(current, workInProgress, renderExpirationTime) { var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect); + if (!cannotBeSuspended) { var row = workInProgress.child; + while (row !== null) { var suspended = findFirstSuspended(row); + if (suspended !== null) { didSuspendAlready = true; workInProgress.effectTag |= DidCapture; - cutOffTailIfNeeded(renderState, false); - - // If this is a newly suspended tree, it might not get committed as + cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thennables. Instead, we'll transfer its thennables to the // SuspenseList so that it can retry if they resolve. @@ -16134,21 +17077,25 @@ function completeWork(current, workInProgress, renderExpirationTime) { // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. + var newThennables = suspended.updateQueue; + if (newThennables !== null) { workInProgress.updateQueue = newThennables; workInProgress.effectTag |= Update; - } - - // Rerender the whole list, but this time, we'll force fallbacks + } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect list before doing the second pass since that's now invalid. - workInProgress.firstEffect = workInProgress.lastEffect = null; - // Reset the child fibers to their original state. - resetChildFibers(workInProgress, renderExpirationTime); - // Set up the Suspense Context to force suspense and immediately + if (renderState.lastEffect === null) { + workInProgress.firstEffect = null; + } + + workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state. + + resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately // rerender the children. + pushSuspenseContext( workInProgress, setShallowSuspenseContext( @@ -16158,42 +17105,46 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); return workInProgress.child; } + row = row.sibling; } } } else { cutOffTailIfNeeded(renderState, false); - } - // Next we're going to render the tail. + } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { workInProgress.effectTag |= DidCapture; - didSuspendAlready = true; - cutOffTailIfNeeded(renderState, true); - // This might have been modified. + didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't + // get lost if this row ends up dropped during a second pass. + + var _newThennables = _suspended.updateQueue; + + if (_newThennables !== null) { + workInProgress.updateQueue = _newThennables; + workInProgress.effectTag |= Update; + } + + cutOffTailIfNeeded(renderState, true); // This might have been modified. + if ( renderState.tail === null && renderState.tailMode === "hidden" ) { // We need to delete the row we just rendered. - // Ensure we transfer the update queue to the parent. - var _newThennables = _suspended.updateQueue; - if (_newThennables !== null) { - workInProgress.updateQueue = _newThennables; - workInProgress.effectTag |= Update; - } // Reset the effect list to what it w as before we rendered this // child. The nested children have already appended themselves. var lastEffect = (workInProgress.lastEffect = - renderState.lastEffect); - // Remove any effects that were appended after this point. + renderState.lastEffect); // Remove any effects that were appended after this point. + if (lastEffect !== null) { lastEffect.nextEffect = null; - } - // We're done. + } // We're done. + return null; } } else if ( @@ -16205,10 +17156,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { // The assumption is that this is usually faster. workInProgress.effectTag |= DidCapture; didSuspendAlready = true; - - cutOffTailIfNeeded(renderState, false); - - // Since nothing actually suspended, there will nothing to ping this + cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. If we can show // them, then they really have the same priority as this render. // So we'll pick it back up the very next render pass once we've had @@ -16216,11 +17164,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { var nextPriority = renderExpirationTime - 1; workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority; + if (enableSchedulerTracing) { markSpawnedWork(nextPriority); } } } + if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in @@ -16231,11 +17181,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; + if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } + renderState.last = renderedTail; } } @@ -16247,18 +17199,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { // until we just give up and show what we have so far. var TAIL_EXPIRATION_TIMEOUT_MS = 500; renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; - } - // Pop a row. + } // Pop a row. + var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.lastEffect = workInProgress.lastEffect; - next.sibling = null; - - // Restore the context. + next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext( suspenseContext, @@ -16267,12 +17219,15 @@ function completeWork(current, workInProgress, renderExpirationTime) { } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } - pushSuspenseContext(workInProgress, suspenseContext); - // Do a pass over the next row. + + pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. + return next; } + break; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalImpl = workInProgress.type.impl; @@ -16280,22 +17235,28 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (fundamentalInstance === null) { var getInitialState = fundamentalImpl.getInitialState; - var fundamentalState = void 0; + var fundamentalState; + if (getInitialState !== undefined) { fundamentalState = getInitialState(newProps); } + fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance( workInProgress, newProps, fundamentalImpl, fundamentalState || {} ); - var _instance7 = getFundamentalComponentInstance(fundamentalInstance); - fundamentalInstance.instance = _instance7; + + var _instance5 = getFundamentalComponentInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance5; + if (fundamentalImpl.reconcileChildren === false) { return null; } - appendAllChildren(_instance7, workInProgress, false, false); + + appendAllChildren(_instance5, workInProgress, false, false); mountFundamentalComponent(fundamentalInstance); } else { // We fire update in commit phase @@ -16303,259 +17264,177 @@ function completeWork(current, workInProgress, renderExpirationTime) { fundamentalInstance.prevProps = prevProps; fundamentalInstance.props = newProps; fundamentalInstance.currentFiber = workInProgress; + if (supportsPersistence) { - var _instance8 = cloneFundamentalInstance(fundamentalInstance); - fundamentalInstance.instance = _instance8; - appendAllChildren(_instance8, workInProgress, false, false); + var _instance6 = cloneFundamentalInstance(fundamentalInstance); + + fundamentalInstance.instance = _instance6; + appendAllChildren(_instance6, workInProgress, false, false); } + var shouldUpdate = shouldUpdateFundamentalComponent( fundamentalInstance ); + if (shouldUpdate) { markUpdate(workInProgress); } } } + break; } - default: - (function() { - { - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - } - return null; -} + case ScopeComponent: { + if (enableScopeAPI) { + if (current === null) { + var _type3 = workInProgress.type; + var scopeInstance = { + fiber: workInProgress, + methods: null + }; + workInProgress.stateNode = scopeInstance; + scopeInstance.methods = createScopeMethods(_type3, scopeInstance); -function mountEventResponder( - responder, - responderProps, - instance, - rootContainerInstance, - fiber, - respondersMap -) { - var responderState = emptyObject$1; - var getInitialState = responder.getInitialState; - if (getInitialState !== null) { - responderState = getInitialState(responderProps); - } - var responderInstance = createResponderInstance( - responder, - responderProps, - responderState, - instance, - fiber - ); - mountResponderInstance( - responder, - responderInstance, - responderProps, - responderState, - instance, - rootContainerInstance - ); - respondersMap.set(responder, responderInstance); -} + if (enableFlareAPI) { + var _listeners2 = newProps.listeners; -function updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance -) { - var responder = void 0; - var props = void 0; + if (_listeners2 != null) { + var _rootContainerInstance2 = getRootHostContainer(); - if (listener) { - responder = listener.responder; - props = listener.props; - } - (function() { - if (!(responder && responder.$$typeof === REACT_RESPONDER_TYPE)) { - throw ReactError( - Error( - "An invalid value was used as an event listener. Expect one or many event listeners created via React.unstable_useResponer()." - ) - ); + updateEventListeners( + _listeners2, + workInProgress, + _rootContainerInstance2 + ); + } + } + + if (workInProgress.ref !== null) { + markRef$1(workInProgress); + markUpdate(workInProgress); + } + } else { + if (enableFlareAPI) { + var _prevListeners = current.memoizedProps.listeners; + var _nextListeners = newProps.listeners; + + if ( + _prevListeners !== _nextListeners || + workInProgress.ref !== null + ) { + markUpdate(workInProgress); + } + } else { + if (workInProgress.ref !== null) { + markUpdate(workInProgress); + } + } + + if (current.ref !== workInProgress.ref) { + markRef$1(workInProgress); + } + } + } + + break; } - })(); - var listenerProps = props; - if (visistedResponders.has(responder)) { - // show warning - { - 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 + + default: { + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } - return; } - visistedResponders.add(responder); - var responderInstance = respondersMap.get(responder); - if (responderInstance === undefined) { - // Mount - mountEventResponder( - responder, - listenerProps, - instance, - rootContainerInstance, - fiber, - respondersMap - ); - } else { - // Update - responderInstance.props = listenerProps; - responderInstance.fiber = fiber; - } -} - -function updateEventListeners( - listeners, - instance, - rootContainerInstance, - fiber -) { - var visistedResponders = new Set(); - var dependencies = fiber.dependencies; - if (listeners != null) { - if (dependencies === null) { - dependencies = fiber.dependencies = { - expirationTime: NoWork, - firstContext: null, - responders: new Map() - }; - } - var respondersMap = dependencies.responders; - if (respondersMap === null) { - respondersMap = new Map(); - } - if (isArray$2(listeners)) { - for (var i = 0, length = listeners.length; i < length; i++) { - var listener = listeners[i]; - updateEventListener( - listener, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } else { - updateEventListener( - listeners, - fiber, - visistedResponders, - respondersMap, - instance, - rootContainerInstance - ); - } - } - if (dependencies !== null) { - var _respondersMap = dependencies.responders; - if (_respondersMap !== null) { - // Unmount - var mountedResponders = Array.from(_respondersMap.keys()); - for (var _i = 0, _length = mountedResponders.length; _i < _length; _i++) { - var mountedResponder = mountedResponders[_i]; - if (!visistedResponders.has(mountedResponder)) { - var responderInstance = _respondersMap.get(mountedResponder); - unmountResponderInstance(responderInstance); - _respondersMap.delete(mountedResponder); - } - } - } - } + return null; } function unwindWork(workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; + if (isContextProvider(Component)) { popContext(workInProgress); } + var effectTag = workInProgress.effectTag; + if (effectTag & ShouldCapture) { workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + return null; } + case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - (function() { - if (!((_effectTag & DidCapture) === NoEffect)) { - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) - ); - } - })(); + + if (!((_effectTag & DidCapture) === NoEffect)) { + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." + ); + } + workInProgress.effectTag = (_effectTag & ~ShouldCapture) | DidCapture; return workInProgress; } + case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } + case SuspenseComponent: { popSuspenseContext(workInProgress); - var _effectTag2 = workInProgress.effectTag; - if (_effectTag2 & ShouldCapture) { - workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } - return null; - } - case DehydratedSuspenseComponent: { + if (enableSuspenseServerRenderer) { - popSuspenseContext(workInProgress); - if (workInProgress.alternate === null) { - // TODO: popHydrationState - } else { + var suspenseState = workInProgress.memoizedState; + + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (!(workInProgress.alternate !== null)) { + throw Error( + "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue." + ); + } + resetHydrationState(); } - var _effectTag3 = workInProgress.effectTag; - if (_effectTag3 & ShouldCapture) { - workInProgress.effectTag = - (_effectTag3 & ~ShouldCapture) | DidCapture; - // Captured a suspense effect. Re-render the boundary. - return workInProgress; - } } + + var _effectTag2 = workInProgress.effectTag; + + if (_effectTag2 & ShouldCapture) { + workInProgress.effectTag = (_effectTag2 & ~ShouldCapture) | DidCapture; // Captured a suspense effect. Re-render the boundary. + + return workInProgress; + } + return null; } + case SuspenseListComponent: { - popSuspenseContext(workInProgress); - // SuspenseList doesn't actually catch anything. It should've been + popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. + return null; } + case HostPortal: popHostContainer(workInProgress); return null; + case ContextProvider: popProvider(workInProgress); return null; + default: return null; } @@ -16565,37 +17444,41 @@ function unwindInterruptedWork(interruptedWork) { switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } + break; } + case HostRoot: { popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); break; } + case HostComponent: { popHostContext(interruptedWork); break; } + case HostPortal: popHostContainer(interruptedWork); break; + case SuspenseComponent: popSuspenseContext(interruptedWork); break; - case DehydratedSuspenseComponent: - if (enableSuspenseServerRenderer) { - popSuspenseContext(interruptedWork); - } - break; + case SuspenseListComponent: popSuspenseContext(interruptedWork); break; + case ContextProvider: popProvider(interruptedWork); break; + default: break; } @@ -16612,18 +17495,16 @@ function createCapturedValue(value, source) { } // Module provided by RN: -(function() { - if ( - !( - typeof ReactNativePrivateInterface.ReactFiberErrorDialog - .showErrorDialog === "function" - ) - ) { - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") - ); - } -})(); +if ( + !( + typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog === + "function" + ) +) { + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." + ); +} function showErrorDialog(capturedError) { return ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog( @@ -16632,23 +17513,21 @@ function showErrorDialog(capturedError) { } function logCapturedError(capturedError) { - var logError = showErrorDialog(capturedError); - - // Allow injected showErrorDialog() to prevent default console.error logging. + var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. + if (logError === false) { return; } var error = capturedError.error; + { var componentName = capturedError.componentName, componentStack = capturedError.componentStack, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, - willRetry = capturedError.willRetry; - - // Browsers support silencing uncaught errors by calling + willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. @@ -16658,22 +17537,20 @@ function logCapturedError(capturedError) { // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; - } - // The error is fatal. Since the silencing might have + } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. - console.error(error); - // For a more detailed description of this block, see: + + console.error(error); // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:"; + var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. - var errorBoundaryMessage = void 0; - // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. if (errorBoundaryFound && errorBoundaryName) { if (willRetry) { errorBoundaryMessage = @@ -16691,31 +17568,32 @@ function logCapturedError(capturedError) { "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."; } + var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + - ("" + errorBoundaryMessage); - - // In development, we provide our own message with just the component stack. + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. + console.error(combinedMessage); } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } -var PossiblyWeakSet$1 = typeof WeakSet === "function" ? WeakSet : Set; - +var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source; var stack = errorInfo.stack; + if (stack === null && source !== null) { stack = getStackByFiberInDevAndProd(source); } @@ -16756,9 +17634,8 @@ var callComponentWillUnmountWithTimer = function(current$$1, instance) { instance.state = current$$1.memoizedState; instance.componentWillUnmount(); stopPhaseTimer(); -}; +}; // Capture errors so they don't interrupt unmounting. -// Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback( @@ -16768,6 +17645,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { current$$1, instance ); + if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); @@ -16777,10 +17655,12 @@ function safelyCallComponentWillUnmount(current$$1, instance) { function safelyDetachRef(current$$1) { var ref = current$$1.ref; + if (ref !== null) { if (typeof ref === "function") { { invokeGuardedCallback(null, ref, null, null); + if (hasCaughtError()) { var refError = clearCaughtError(); captureCommitPhaseError(current$$1, refError); @@ -16795,6 +17675,7 @@ function safelyDetachRef(current$$1) { function safelyCallDestroy(current$$1, destroy) { { invokeGuardedCallback(null, destroy, null); + if (hasCaughtError()) { var error = clearCaughtError(); captureCommitPhaseError(current$$1, error); @@ -16810,16 +17691,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); return; } + case ClassComponent: { if (finishedWork.effectTag & Snapshot) { if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, "getSnapshotBeforeUpdate"); - var instance = finishedWork.stateNode; - // We could update instance props and state here, + var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -16849,14 +17731,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { : void 0; } } + var snapshot = instance.getSnapshotBeforeUpdate( finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState ); + { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; + if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); warningWithoutStack$1( @@ -16867,12 +17752,15 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { ); } } + instance.__reactInternalSnapshotBeforeUpdate = snapshot; stopPhaseTimer(); } } + return; } + case HostRoot: case HostComponent: case HostText: @@ -16880,16 +17768,13 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case IncompleteClassComponent: // Nothing to do for these component types return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -16897,18 +17782,22 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { function commitHookEffectList(unmountTag, mountTag, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; + if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; + do { if ((effect.tag & unmountTag) !== NoEffect$1) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; + if (destroy !== undefined) { destroy(); } } + if ((effect.tag & mountTag) !== NoEffect$1) { // Mount var create = effect.create; @@ -16916,8 +17805,10 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { { var _destroy = effect.destroy; + if (_destroy !== undefined && typeof _destroy !== "function") { var addendum = void 0; + if (_destroy === null) { addendum = " You returned null. If your effect does not require clean " + @@ -16939,6 +17830,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else { addendum = " You returned: " + _destroy; } + warningWithoutStack$1( false, "An effect function must not return anything besides a function, " + @@ -16949,6 +17841,7 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } } } + effect = effect.next; } while (effect !== firstEffect); } @@ -16964,6 +17857,7 @@ function commitPassiveHookEffects(finishedWork) { commitHookEffectList(NoEffect$1, MountPassive, finishedWork); break; } + default: break; } @@ -16983,14 +17877,16 @@ function commitLifeCycles( commitHookEffectList(UnmountLayout, MountLayout, finishedWork); break; } + case ClassComponent: { var instance = finishedWork.stateNode; + if (finishedWork.effectTag & Update) { if (current$$1 === null) { - startPhaseTimer(finishedWork, "componentDidMount"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidMount"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17020,6 +17916,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidMount(); stopPhaseTimer(); } else { @@ -17031,10 +17928,10 @@ function commitLifeCycles( current$$1.memoizedProps ); var prevState = current$$1.memoizedState; - startPhaseTimer(finishedWork, "componentDidUpdate"); - // We could update instance props and state here, + startPhaseTimer(finishedWork, "componentDidUpdate"); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + { if ( finishedWork.type === finishedWork.elementType && @@ -17064,6 +17961,7 @@ function commitLifeCycles( : void 0; } } + instance.componentDidUpdate( prevProps, prevState, @@ -17072,7 +17970,9 @@ function commitLifeCycles( stopPhaseTimer(); } } + var updateQueue = finishedWork.updateQueue; + if (updateQueue !== null) { { if ( @@ -17102,10 +18002,10 @@ function commitLifeCycles( ) : void 0; } - } - // We could update instance props and state here, + } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. + commitUpdateQueue( finishedWork, updateQueue, @@ -17113,22 +18013,28 @@ function commitLifeCycles( committedExpirationTime ); } + return; } + case HostRoot: { var _updateQueue = finishedWork.updateQueue; + if (_updateQueue !== null) { var _instance = null; + if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; + case ClassComponent: _instance = finishedWork.child.stateNode; break; } } + commitUpdateQueue( finishedWork, _updateQueue, @@ -17136,15 +18042,16 @@ function commitLifeCycles( committedExpirationTime ); } + return; } - case HostComponent: { - var _instance2 = finishedWork.stateNode; - // Renderers may schedule work to be done after host components are mounted + case HostComponent: { + var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. + if (current$$1 === null && finishedWork.effectTag & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; @@ -17152,14 +18059,17 @@ function commitLifeCycles( return; } + case HostText: { // We have no life-cycles associated with text. return; } + case HostPortal: { // We have no life-cycles associated with portals. return; } + case Profiler: { if (enableProfilerTimer) { var onRender = finishedWork.memoizedProps.onRender; @@ -17187,23 +18097,27 @@ function commitLifeCycles( } } } + return; } - case SuspenseComponent: + + case SuspenseComponent: { + commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); + return; + } + case SuspenseListComponent: case IncompleteClassComponent: case FundamentalComponent: + case ScopeComponent: return; + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } @@ -17211,10 +18125,13 @@ function commitLifeCycles( function hideOrUnhideAllChildren(finishedWork, isHidden) { if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its + // children to find all the terminal nodes. var node = finishedWork; + while (true) { if (node.tag === HostComponent) { var instance = node.stateNode; + if (isHidden) { hideInstance(instance); } else { @@ -17222,6 +18139,7 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if (node.tag === HostText) { var _instance3 = node.stateNode; + if (isHidden) { hideTextInstance(_instance3); } else { @@ -17229,9 +18147,11 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { } } else if ( node.tag === SuspenseComponent && - node.memoizedState !== null + node.memoizedState !== null && + node.memoizedState.dehydrated === null ) { // Found a nested Suspense component that timed out. Skip over the + // primary child fragment, which should remain hidden. var fallbackChildFragment = node.child.sibling; fallbackChildFragment.return = node; node = fallbackChildFragment; @@ -17241,15 +18161,19 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } @@ -17258,16 +18182,24 @@ function hideOrUnhideAllChildren(finishedWork, isHidden) { function commitAttachRef(finishedWork) { var ref = finishedWork.ref; + if (ref !== null) { var instance = finishedWork.stateNode; - var instanceToUse = void 0; + var instanceToUse; + switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; + default: instanceToUse = instance; + } // Moved outside to ensure DCE works with this flag + + if (enableScopeAPI && finishedWork.tag === ScopeComponent) { + instanceToUse = instance.methods; } + if (typeof ref === "function") { ref(instanceToUse); } else { @@ -17290,6 +18222,7 @@ function commitAttachRef(finishedWork) { function commitDetachRef(current$$1) { var currentRef = current$$1.ref; + if (currentRef !== null) { if (typeof currentRef === "function") { currentRef(null); @@ -17297,12 +18230,11 @@ function commitDetachRef(current$$1) { currentRef.current = null; } } -} - -// User-originating errors (lifecycles and refs) should not interrupt +} // User-originating errors (lifecycles and refs) should not interrupt // deletion, so don't let them throw. Host-originating errors should // interrupt deletion, so it's okay -function commitUnmount(current$$1, renderPriorityLevel) { + +function commitUnmount(finishedRoot, current$$1, renderPriorityLevel) { onCommitUnmount(current$$1); switch (current$$1.tag) { @@ -17311,12 +18243,12 @@ function commitUnmount(current$$1, renderPriorityLevel) { case MemoComponent: case SimpleMemoComponent: { var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; - if (lastEffect !== null) { - var firstEffect = lastEffect.next; - // When the owner fiber is deleted, the destroy function of a passive + if (lastEffect !== null) { + var firstEffect = lastEffect.next; // When the owner fiber is deleted, the destroy function of a passive // effect hook is called during the synchronous commit phase. This is // a concession to implementation complexity. Calling it in the // passive effect phase (like they usually are, when dependencies @@ -17328,40 +18260,51 @@ function commitUnmount(current$$1, renderPriorityLevel) { // the priority. // // TODO: Reconsider this implementation trade off. + var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; runWithPriority(priorityLevel, function() { var effect = firstEffect; + do { var destroy = effect.destroy; + if (destroy !== undefined) { safelyCallDestroy(current$$1, destroy); } + effect = effect.next; } while (effect !== firstEffect); }); } } + break; } + case ClassComponent: { safelyDetachRef(current$$1); var instance = current$$1.stateNode; + if (typeof instance.componentWillUnmount === "function") { safelyCallComponentWillUnmount(current$$1, instance); } + return; } + case HostComponent: { if (enableFlareAPI) { var dependencies = current$$1.dependencies; if (dependencies !== null) { var respondersMap = dependencies.responders; + if (respondersMap !== null) { var responderInstances = Array.from(respondersMap.values()); + for ( var i = 0, length = responderInstances.length; i < length; @@ -17370,49 +18313,80 @@ function commitUnmount(current$$1, renderPriorityLevel) { var responderInstance = responderInstances[i]; unmountResponderInstance(responderInstance); } + dependencies.responders = null; } } } + safelyDetachRef(current$$1); return; } + case HostPortal: { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if (supportsMutation) { - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else if (supportsPersistence) { emptyPortalContainer(current$$1); } + return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = current$$1.stateNode; + if (fundamentalInstance !== null) { unmountFundamentalComponent(fundamentalInstance); current$$1.stateNode = null; } } + + return; } - } -} -function commitNestedUnmounts(root, renderPriorityLevel) { - // While we're inside a removed host node we don't want to call - // removeChild on the inner nodes because they're removed by the top + case DehydratedFragment: { + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(current$$1.stateNode); + } + } + } + + return; + } + + case ScopeComponent: { + if (enableScopeAPI) { + safelyDetachRef(current$$1); + } + } + } +} + +function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) { + // While we're inside a removed host node we don't want to call + // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore + // we do an inner loop while we're still inside the host node. var node = root; + while (true) { - commitUnmount(node, renderPriorityLevel); - // Visit children because they may contain more composite or host nodes. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes. // Skip portals because commitUnmount() currently visits them recursively. + if ( - node.child !== null && - // If we use mutation we drill down into portals using commitUnmount above. + node.child !== null && // If we use mutation we drill down into portals using commitUnmount above. // If we don't use mutation we drill down into portals here instead. (!supportsMutation || node.tag !== HostPortal) ) { @@ -17420,27 +18394,31 @@ function commitNestedUnmounts(root, renderPriorityLevel) { node = node.child; continue; } + if (node === root) { return; } + while (node.sibling === null) { if (node.return === null || node.return === root) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } function detachFiber(current$$1) { - var alternate = current$$1.alternate; - // Cut off the return pointers to disconnect it from the tree. Ideally, we + var alternate = current$$1.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. This child // itself will be GC:ed when the parent updates the next time. + current$$1.return = null; current$$1.child = null; current$$1.memoizedState = null; @@ -17451,6 +18429,7 @@ function detachFiber(current$$1) { current$$1.lastEffect = null; current$$1.pendingProps = null; current$$1.memoizedProps = null; + if (alternate !== null) { detachFiber(alternate); } @@ -17463,7 +18442,6 @@ function emptyPortalContainer(current$$1) { var portal = current$$1.stateNode; var containerInfo = portal.containerInfo; - var emptyChildSet = createContainerChildSet(containerInfo); replaceContainerChildren(containerInfo, emptyChildSet); } @@ -17480,46 +18458,42 @@ function commitContainer(finishedWork) { case FundamentalComponent: { return; } + case HostRoot: case HostPortal: { var portalOrRoot = finishedWork.stateNode; var containerInfo = portalOrRoot.containerInfo, - _pendingChildren = portalOrRoot.pendingChildren; - - replaceContainerChildren(containerInfo, _pendingChildren); + pendingChildren = portalOrRoot.pendingChildren; + replaceContainerChildren(containerInfo, pendingChildren); return; } + default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + { + 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." + ); + } } } } function getHostParentFiber(fiber) { var parent = fiber.return; + while (parent !== null) { if (isHostParent(parent)) { return parent; } + parent = parent.return; } - (function() { - { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } } function isHostParent(fiber) { @@ -17534,7 +18508,9 @@ function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. + // TODO: Find a more efficient way to do this. var node = fiber; + siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { @@ -17543,31 +18519,34 @@ function getHostSibling(fiber) { // last sibling. return null; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; + while ( node.tag !== HostComponent && node.tag !== HostText && - node.tag !== DehydratedSuspenseComponent + node.tag !== DehydratedFragment ) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.effectTag & Placement) { // If we don't have a child, try the siblings instead. continue siblings; - } - // If we don't have a child, try the siblings instead. + } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. + if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } - } - // Check if this host node is stable or about to be placed. + } // Check if this host node is stable or about to be placed. + if (!(node.effectTag & Placement)) { // Found it! return node.stateNode; @@ -17578,58 +18557,61 @@ function getHostSibling(fiber) { function commitPlacement(finishedWork) { if (!supportsMutation) { return; - } + } // Recursively insert all host nodes into the parent. - // Recursively insert all host nodes into the parent. - var parentFiber = getHostParentFiber(finishedWork); + var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. - // Note: these two variables *must* always be updated together. - var parent = void 0; - var isContainer = void 0; + var parent; + var isContainer; var parentStateNode = parentFiber.stateNode; + switch (parentFiber.tag) { case HostComponent: parent = parentStateNode; isContainer = false; break; + case HostRoot: parent = parentStateNode.containerInfo; isContainer = true; break; + case HostPortal: parent = parentStateNode.containerInfo; isContainer = true; break; + case FundamentalComponent: if (enableFundamentalAPI) { parent = parentStateNode.instance; isContainer = false; } + // eslint-disable-next-line-no-fallthrough - default: - (function() { - { - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + + default: { + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." + ); + } } + if (parentFiber.effectTag & ContentReset) { // Reset the text content of the parent before doing any insertions parentFiber.effectTag &= ~ContentReset; } - var before = getHostSibling(finishedWork); - // We only have the top Fiber that was inserted but we need to recurse down its + var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. + var node = finishedWork; + while (true) { var isHost = node.tag === HostComponent || node.tag === HostText; + if (isHost || (enableFundamentalAPI && node.tag === FundamentalComponent)) { var stateNode = isHost ? node.stateNode : node.stateNode.instance; + if (before) { if (isContainer) { insertInContainerBefore(parent, stateNode, before); @@ -17652,85 +18634,91 @@ function commitPlacement(finishedWork) { node = node.child; continue; } + if (node === finishedWork) { return; } + while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } + node = node.return; } + node.sibling.return = node.return; node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel) { +function unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel) { // We only have the top Fiber that was deleted but we need to recurse down its - var node = current$$1; - - // Each iteration, currentParent is populated with node's host parent if not + // children to find all the terminal nodes. + var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not // currentParentIsValid. - var currentParentIsValid = false; - // Note: these two variables *must* always be updated together. - var currentParent = void 0; - var currentParentIsContainer = void 0; + var currentParentIsValid = false; // Note: these two variables *must* always be updated together. + + var currentParent; + var currentParentIsContainer; while (true) { if (!currentParentIsValid) { var parent = node.return; + findParent: while (true) { - (function() { - if (!(parent !== null)) { - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(parent !== null)) { + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + var parentStateNode = parent.stateNode; + switch (parent.tag) { case HostComponent: currentParent = parentStateNode; currentParentIsContainer = false; break findParent; + case HostRoot: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case HostPortal: currentParent = parentStateNode.containerInfo; currentParentIsContainer = true; break findParent; + case FundamentalComponent: if (enableFundamentalAPI) { currentParent = parentStateNode.instance; currentParentIsContainer = false; } } + parent = parent.return; } + currentParentIsValid = true; } if (node.tag === HostComponent || node.tag === HostText) { - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, node.stateNode); } else { removeChild(currentParent, node.stateNode); - } - // Don't visit children because we already visited them. + } // Don't visit children because we already visited them. } else if (enableFundamentalAPI && node.tag === FundamentalComponent) { var fundamentalNode = node.stateNode.instance; - commitNestedUnmounts(node, renderPriorityLevel); - // After all the children have unmounted, it is now safe to remove the + commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the // node from the tree. + if (currentParentIsContainer) { removeChildFromContainer(currentParent, fundamentalNode); } else { @@ -17738,9 +18726,20 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { } } else if ( enableSuspenseServerRenderer && - node.tag === DehydratedSuspenseComponent + node.tag === DehydratedFragment ) { - // Delete the dehydrated suspense boundary and all of its content. + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onDeleted = hydrationCallbacks.onDeleted; + + if (onDeleted) { + onDeleted(node.stateNode); + } + } + } // Delete the dehydrated suspense boundary and all of its content. + if (currentParentIsContainer) { clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); } else { @@ -17751,49 +18750,55 @@ function unmountHostComponents(current$$1, renderPriorityLevel) { // When we go into a portal, it becomes the parent to remove from. // We will reassign it back when we pop the portal on the way up. currentParent = node.stateNode.containerInfo; - currentParentIsContainer = true; - // Visit children because portals might contain host components. + currentParentIsContainer = true; // Visit children because portals might contain host components. + node.child.return = node; node = node.child; continue; } } else { - commitUnmount(node, renderPriorityLevel); - // Visit children because we may find more host components below. + commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below. + if (node.child !== null) { node.child.return = node; node = node.child; continue; } } + if (node === current$$1) { return; } + while (node.sibling === null) { if (node.return === null || node.return === current$$1) { return; } + node = node.return; + if (node.tag === HostPortal) { // When we go out of the portal, we need to restore the parent. // Since we don't keep a stack of them, we will search for it. currentParentIsValid = false; } } + node.sibling.return = node.return; node = node.sibling; } } -function commitDeletion(current$$1, renderPriorityLevel) { +function commitDeletion(finishedRoot, current$$1, renderPriorityLevel) { if (supportsMutation) { // Recursively delete all host nodes from the parent. // Detach refs and call componentWillUnmount() on the whole subtree. - unmountHostComponents(current$$1, renderPriorityLevel); + unmountHostComponents(finishedRoot, current$$1, renderPriorityLevel); } else { // Detach refs and call componentWillUnmount() on the whole subtree. - commitNestedUnmounts(current$$1, renderPriorityLevel); + commitNestedUnmounts(finishedRoot, current$$1, renderPriorityLevel); } + detachFiber(current$$1); } @@ -17809,18 +18814,35 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + + case HostRoot: { + if (supportsHydration) { + var root = finishedWork.stateNode; + + if (root.hydrate) { + // We've just hydrated. No need to hydrate again. + root.hydrate = false; + commitHydratedContainer(root.containerInfo); + } + } + + break; + } } commitContainer(finishedWork); @@ -17837,23 +18859,27 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case ClassComponent: { return; } + case HostComponent: { var instance = finishedWork.stateNode; + if (instance != null) { // Commit the work prepared earlier. - var newProps = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps; - var type = finishedWork.type; - // TODO: Type the updateQueue to be specific to host components. + var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; + if (updatePayload !== null) { commitUpdate( instance, @@ -17864,72 +18890,117 @@ function commitWork(current$$1, finishedWork) { finishedWork ); } + + if (enableFlareAPI) { + var prevListeners = oldProps.listeners; + var nextListeners = newProps.listeners; + + if (prevListeners !== nextListeners) { + updateEventListeners(nextListeners, finishedWork, null); + } + } } + return; } + case HostText: { - (function() { - if (!(finishedWork.stateNode !== null)) { - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); + if (!(finishedWork.stateNode !== null)) { + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + var textInstance = finishedWork.stateNode; - var newText = finishedWork.memoizedProps; - // For hydration we reuse the update path but we treat the oldProps + var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. + var oldText = current$$1 !== null ? current$$1.memoizedProps : newText; commitTextUpdate(textInstance, oldText, newText); return; } + case HostRoot: { + if (supportsHydration) { + var _root = finishedWork.stateNode; + + if (_root.hydrate) { + // We've just hydrated. No need to hydrate again. + _root.hydrate = false; + commitHydratedContainer(_root.containerInfo); + } + } + return; } + case Profiler: { return; } + case SuspenseComponent: { commitSuspenseComponent(finishedWork); attachSuspenseRetryListeners(finishedWork); return; } + case SuspenseListComponent: { attachSuspenseRetryListeners(finishedWork); return; } + case IncompleteClassComponent: { return; } + case FundamentalComponent: { if (enableFundamentalAPI) { var fundamentalInstance = finishedWork.stateNode; updateFundamentalComponent(fundamentalInstance); } + return; } - default: { - (function() { - { - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); + + case ScopeComponent: { + if (enableScopeAPI) { + var scopeInstance = finishedWork.stateNode; + scopeInstance.fiber = finishedWork; + + if (enableFlareAPI) { + var _newProps = finishedWork.memoizedProps; + + var _oldProps = + current$$1 !== null ? current$$1.memoizedProps : _newProps; + + var _prevListeners = _oldProps.listeners; + var _nextListeners = _newProps.listeners; + + if (_prevListeners !== _nextListeners) { + updateEventListeners(_nextListeners, finishedWork, null); + } } - })(); + } + + return; + } + + default: { + { + 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." + ); + } } } } function commitSuspenseComponent(finishedWork) { var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; + var newDidTimeout; var primaryChildParent = finishedWork; + if (newState === null) { newDidTimeout = false; } else { @@ -17944,8 +19015,10 @@ function commitSuspenseComponent(finishedWork) { if (enableSuspenseCallback && newState !== null) { var suspenseCallback = finishedWork.memoizedProps.suspenseCallback; + if (typeof suspenseCallback === "function") { var thenables = finishedWork.updateQueue; + if (thenables !== null) { suspenseCallback(new Set(thenables)); } @@ -17957,23 +19030,67 @@ function commitSuspenseComponent(finishedWork) { } } +function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + if (!supportsHydration) { + return; + } + + var newState = finishedWork.memoizedState; + + if (newState === null) { + var current$$1 = finishedWork.alternate; + + if (current$$1 !== null) { + var prevState = current$$1.memoizedState; + + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + + if (enableSuspenseCallback) { + var hydrationCallbacks = finishedRoot.hydrationCallbacks; + + if (hydrationCallbacks !== null) { + var onHydrated = hydrationCallbacks.onHydrated; + + if (onHydrated) { + onHydrated(suspenseInstance); + } + } + } + } + } + } + } +} + function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of thenables. // For each thenable, attach a listener so that when it resolves, React + // attempts to re-render the boundary in the primary (pre-timeout) state. var thenables = finishedWork.updateQueue; + if (thenables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; + if (retryCache === null) { - retryCache = finishedWork.stateNode = new PossiblyWeakSet$1(); + retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } + thenables.forEach(function(thenable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryThenable.bind(null, finishedWork, thenable); + if (!retryCache.has(thenable)) { if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); + if (thenable.__reactDoNotTraceInteractions !== true) { + retry = tracing.unstable_wrap(retry); + } } + retryCache.add(thenable); thenable.then(retry, retry); } @@ -17985,24 +19102,28 @@ function commitResetTextContent(current$$1) { if (!supportsMutation) { return; } + resetTextContent(current$$1.stateNode); } -var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { - var update = createUpdate(expirationTime, null); - // Unmount the root by rendering null. - update.tag = CaptureUpdate; - // Caution: React DevTools currently depends on this property + var update = createUpdate(expirationTime, null); // Unmount the root by rendering null. + + update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". - update.payload = { element: null }; + + update.payload = { + element: null + }; var error = errorInfo.value; + update.callback = function() { onUncaughtError(error); logError(fiber, errorInfo); }; + return update; } @@ -18010,8 +19131,10 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime, null); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; + if (typeof getDerivedStateFromError === "function") { var error = errorInfo.value; + update.payload = function() { logError(fiber, errorInfo); return getDerivedStateFromError(error); @@ -18019,27 +19142,30 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { } var inst = fiber.stateNode; + if (inst !== null && typeof inst.componentDidCatch === "function") { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } + if (typeof getDerivedStateFromError !== "function") { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined - // Only log here if componentDidCatch is the only error boundary method defined logError(fiber, errorInfo); } + var error = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error, { componentStack: stack !== null ? stack : "" }); + { if (typeof getDerivedStateFromError !== "function") { // If componentDidCatch is the only error boundary method defined, @@ -18061,6 +19187,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { markFailedErrorBoundaryForHotReloading(fiber); }; } + return update; } @@ -18069,18 +19196,21 @@ function attachPingListener(root, renderExpirationTime, thenable) { // only if one does not already exist for the current render expiration // time (which acts like a "thread ID" here). var pingCache = root.pingCache; - var threadIDs = void 0; + var threadIDs; + if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); threadIDs = new Set(); pingCache.set(thenable, threadIDs); } else { threadIDs = pingCache.get(thenable); + if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(thenable, threadIDs); } } + if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); @@ -18090,9 +19220,6 @@ function attachPingListener(root, renderExpirationTime, thenable) { thenable, renderExpirationTime ); - if (enableSchedulerTracing) { - ping = tracing.unstable_wrap(ping); - } thenable.then(ping, ping); } } @@ -18105,8 +19232,8 @@ function throwException( renderExpirationTime ) { // The source fiber did not complete. - sourceFiber.effectTag |= Incomplete; - // Its effect list is no longer valid. + sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid. + sourceFiber.firstEffect = sourceFiber.lastEffect = null; if ( @@ -18116,34 +19243,31 @@ function throwException( ) { // This is a thenable. var thenable = value; - checkForWrongSuspensePriorityInDEV(sourceFiber); - var hasInvisibleParentBoundary = hasSuspenseContext( suspenseStackCursor.current, InvisibleParentSuspenseContext - ); + ); // Schedule the nearest Suspense to re-render the timed out view. - // Schedule the nearest Suspense to re-render the timed out view. var _workInProgress = returnFiber; + do { if ( _workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary) ) { // Found the nearest boundary. - // Stash the promise on the boundary fiber. If the boundary times out, we'll + // attach another listener to flip the boundary back to its normal state. var thenables = _workInProgress.updateQueue; + if (thenables === null) { var updateQueue = new Set(); updateQueue.add(thenable); _workInProgress.updateQueue = updateQueue; } else { thenables.add(thenable); - } - - // If the boundary is outside of batched mode, we should *not* + } // If the boundary is outside of batched mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. In the commit phase, we'll schedule a // subsequent synchronous update to re-render the Suspense. @@ -18151,16 +19275,17 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a batched mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & BatchedMode) === NoMode) { - _workInProgress.effectTag |= DidCapture; - // We're going to commit this fiber even though it didn't complete. + if ((_workInProgress.mode & BatchedMode) === NoMode) { + _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. + sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call @@ -18174,17 +19299,13 @@ function throwException( update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update); } - } - - // The source fiber did not complete. Mark it with Sync priority to + } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. - sourceFiber.expirationTime = Sync; - // Exit without suspending. - return; - } + sourceFiber.expirationTime = Sync; // Exit without suspending. - // Confirmed that the boundary is in a concurrent mode tree. Continue + return; + } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this @@ -18199,7 +19320,6 @@ function throwException( // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. - // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, @@ -18227,56 +19347,16 @@ function throwException( // ensure that new initial loading states can commit as soon as possible. attachPingListener(root, renderExpirationTime, thenable); - _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; - return; - } else if ( - enableSuspenseServerRenderer && - _workInProgress.tag === DehydratedSuspenseComponent - ) { - attachPingListener(root, renderExpirationTime, thenable); - - // Since we already have a current fiber, we can eagerly add a retry listener. - var retryCache = _workInProgress.memoizedState; - if (retryCache === null) { - retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var current$$1 = _workInProgress.alternate; - (function() { - if (!current$$1) { - throw ReactError( - Error( - "A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React." - ) - ); - } - })(); - current$$1.memoizedState = retryCache; - } - // Memoize using the boundary fiber to prevent redundant listeners. - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - var retry = resolveRetryThenable.bind( - null, - _workInProgress, - thenable - ); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - thenable.then(retry, retry); - } - _workInProgress.effectTag |= ShouldCapture; - _workInProgress.expirationTime = renderExpirationTime; - return; - } - // This boundary already captured during this render. Continue to the next + } // This boundary already captured during this render. Continue to the next // boundary. + _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // No boundary was found. Fallthrough to error mode. + } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode. // TODO: Use invariant so the message is stripped in prod? + value = new Error( (getComponentName(sourceFiber.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n" + @@ -18285,33 +19365,37 @@ function throwException( "provide a loading indicator or placeholder to display." + getStackByFiberInDevAndProd(sourceFiber) ); - } - - // We didn't find a boundary that could handle this type of exception. Start + } // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. + renderDidError(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; + do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; + var _update = createRootErrorUpdate( workInProgress, _errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update); return; } + case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; + if ( (workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === "function" || @@ -18320,142 +19404,153 @@ function throwException( !isAlreadyFailedLegacyErrorBoundary(instance))) ) { workInProgress.effectTag |= ShouldCapture; - workInProgress.expirationTime = renderExpirationTime; - // Schedule the error boundary to re-render using updated state + workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state + var _update2 = createClassErrorUpdate( workInProgress, errorInfo, renderExpirationTime ); + enqueueCapturedUpdate(workInProgress, _update2); return; } + break; + default: break; } + workInProgress = workInProgress.return; } while (workInProgress !== null); } -// The scheduler is imported here *only* to detect whether it's been mocked -// DEV stuff var ceil = Math.ceil; - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; +var NoContext = + /* */ + 0; +var BatchedContext = + /* */ + 1; +var EventContext = + /* */ + 2; +var DiscreteEventContext = + /* */ + 4; +var LegacyUnbatchedContext = + /* */ + 8; +var RenderContext = + /* */ + 16; +var CommitContext = + /* */ + 32; +var RootIncomplete = 0; +var RootFatalErrored = 1; +var RootErrored = 2; +var RootSuspended = 3; +var RootSuspendedWithDelay = 4; +var RootCompleted = 5; +// Describes where we are in the React execution stack +var executionContext = NoContext; // The root we're working on -var NoContext = /* */ 0; -var BatchedContext = /* */ 1; -var EventContext = /* */ 2; -var DiscreteEventContext = /* */ 4; -var LegacyUnbatchedContext = /* */ 8; -var RenderContext = /* */ 16; -var CommitContext = /* */ 32; +var workInProgressRoot = null; // The fiber we're working on -var RootIncomplete = 0; -var RootErrored = 1; -var RootSuspended = 2; -var RootSuspendedWithDelay = 3; -var RootCompleted = 4; +var workInProgress = null; // The expiration time we're rendering -// Describes where we are in the React execution stack -var executionContext = NoContext; -// The root we're working on -var workInProgressRoot = null; -// The fiber we're working on -var workInProgress = null; -// The expiration time we're rendering -var renderExpirationTime = NoWork; -// Whether to root completed, errored, suspended, etc. -var workInProgressRootExitStatus = RootIncomplete; -// Most recent event time among processed updates during this render. +var renderExpirationTime = NoWork; // Whether to root completed, errored, suspended, etc. + +var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown + +var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render. // This is conceptually a time stamp but expressed in terms of an ExpirationTime // because we deal mostly with expiration times in the hot path, so this avoids // the conversion happening in the hot path. + var workInProgressRootLatestProcessedExpirationTime = Sync; var workInProgressRootLatestSuspenseTimeout = Sync; -var workInProgressRootCanSuspendUsingConfig = null; -// If we're pinged while rendering we don't always restart immediately. +var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only +// includes unprocessed updates, not work in bailed out children. + +var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately. // This flag determines if it might be worthwhile to restart if an opportunity // happens latere. -var workInProgressRootHasPendingPing = false; -// The most recent time we committed a fallback. This lets us ensure a train + +var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. + var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; - var nextEffect = null; var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; - var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsRenderPriority = NoPriority; var pendingPassiveEffectsExpirationTime = NoWork; +var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates -var rootsWithPendingDiscreteUpdates = null; - -// Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; - var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; - -var interruptedBy = null; - -// Marks the need to reschedule pending interactions at these expiration times +var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times // during the commit phase. This enables them to be traced across components // that spawn new work during render. E.g. hidden boundaries, suspended SSR // hydration or SuspenseList. -var spawnedWorkDuringRender = null; -// Expiration times are computed by adding to the current time (the start +var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start // time). However, if two updates are scheduled within the same event, we // should treat their start times as simultaneous, even if the actual clock // time has advanced between the first and second call. - // In other words, because expiration times determine how updates are batched, // we want all updates of like priority that occur within the same event to // receive the same expiration time. Otherwise we get tearing. -var currentEventTime = NoWork; +var currentEventTime = NoWork; function requestCurrentTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return msToExpirationTime(now()); - } - // We're not inside React, so we may be in the middle of a browser event. + } // We're not inside React, so we may be in the middle of a browser event. + if (currentEventTime !== NoWork) { // Use the same start time for all updates until we enter React again. return currentEventTime; - } - // This is the first update since React yielded. Compute a new start time. + } // This is the first update since React yielded. Compute a new start time. + currentEventTime = msToExpirationTime(now()); return currentEventTime; } - function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { var mode = fiber.mode; + if ((mode & BatchedMode) === NoMode) { return Sync; } var priorityLevel = getCurrentPriorityLevel(); + if ((mode & ConcurrentMode) === NoMode) { return priorityLevel === ImmediatePriority ? Sync : Batched; } if ((executionContext & RenderContext) !== NoContext) { // Use whatever time we're already rendering + // TODO: Should there be a way to opt out, like with `runWithPriority`? return renderExpirationTime; } - var expirationTime = void 0; + var expirationTime; + if (suspenseConfig !== null) { // Compute an expiration time based on the Suspense timeout. expirationTime = computeSuspenseExpiration( @@ -18468,33 +19563,33 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { case ImmediatePriority: expirationTime = Sync; break; + case UserBlockingPriority: // TODO: Rename this to computeUserBlockingExpiration expirationTime = computeInteractiveExpiration(currentTime); break; + case NormalPriority: case LowPriority: // TODO: Handle LowPriority // TODO: Rename this to... something better. expirationTime = computeAsyncExpiration(currentTime); break; + case IdlePriority: - expirationTime = Never; + expirationTime = Idle; break; - default: - (function() { - { - throw ReactError(Error("Expected a valid priority level")); - } - })(); - } - } - // If we're in the middle of rendering a tree, do not update at the same + default: { + throw Error("Expected a valid priority level"); + } + } + } // If we're in the middle of rendering a tree, do not update at the same // expiration time that is already rendering. // TODO: We shouldn't have to do this if the update is on a different root. // Refactor computeExpirationForFiber + scheduleUpdate so we have access to // the root when we check for this condition. + if (workInProgressRoot !== null && expirationTime === renderExpirationTime) { // This is a trick to move this update into a separate batch expirationTime -= 1; @@ -18502,47 +19597,40 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { return expirationTime; } - function scheduleUpdateOnFiber(fiber, expirationTime) { checkForNestedUpdates(); warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber); - var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime); + if (root === null) { warnAboutUpdateOnUnmountedFiberInDEV(fiber); return; } - root.pingTime = NoWork; - checkForInterruption(fiber, expirationTime); - recordScheduleUpdate(); - - // TODO: computeExpirationForFiber also reads the priority. Pass the + recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); if (expirationTime === Sync) { if ( // Check if we're inside unbatchedUpdates - (executionContext & LegacyUnbatchedContext) !== NoContext && - // Check if we're not already rendering + (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering (executionContext & (RenderContext | CommitContext)) === NoContext ) { // Register pending interactions on the root to avoid losing traced interaction data. - schedulePendingInteractions(root, expirationTime); - - // This is a legacy edge case. The initial mount of a ReactDOM.render-ed + schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed // root inside of batchedUpdates should be synchronous, but layout updates // should be deferred until the end of the batch. - var callback = renderRoot(root, Sync, true); - while (callback !== null) { - callback = callback(true); - } + + performSyncWorkOnRoot(root); } else { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); + if (executionContext === NoContext) { - // Flush the synchronous work now, wnless we're already working or inside + // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated @@ -18551,12 +19639,12 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { } } } else { - scheduleCallbackForRoot(root, priorityLevel, expirationTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, expirationTime); } if ( - (executionContext & DiscreteEventContext) !== NoContext && - // Only updates at user-blocking priority or greater are considered + (executionContext & DiscreteEventContext) !== NoContext && // Only updates at user-blocking priority or greater are considered // discrete, even inside a discrete event. (priorityLevel === UserBlockingPriority || priorityLevel === ImmediatePriority) @@ -18567,37 +19655,42 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); } else { var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) { rootsWithPendingDiscreteUpdates.set(root, expirationTime); } } } } -var scheduleWork = scheduleUpdateOnFiber; - -// This is split into a separate function so we can mark a fiber with pending +var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending // work without treating it as a typical update that originates from an event; // e.g. retrying a Suspense boundary isn't an update, but it does schedule work // on a fiber. + function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { // Update the source fiber's expiration time if (fiber.expirationTime < expirationTime) { fiber.expirationTime = expirationTime; } + var alternate = fiber.alternate; + if (alternate !== null && alternate.expirationTime < expirationTime) { alternate.expirationTime = expirationTime; - } - // Walk the parent path to the root and update the child expiration time. + } // Walk the parent path to the root and update the child expiration time. + var node = fiber.return; var root = null; + if (node === null && fiber.tag === HostRoot) { root = fiber.stateNode; } else { while (node !== null) { alternate = node.alternate; + if (node.childExpirationTime < expirationTime) { node.childExpirationTime = expirationTime; + if ( alternate !== null && alternate.childExpirationTime < expirationTime @@ -18610,580 +19703,430 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { ) { alternate.childExpirationTime = expirationTime; } + if (node.return === null && node.tag === HostRoot) { root = node.stateNode; break; } + node = node.return; } } if (root !== null) { - // Update the first and last pending expiration times in this root - var firstPendingTime = root.firstPendingTime; - if (expirationTime > firstPendingTime) { - root.firstPendingTime = expirationTime; - } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime === NoWork || expirationTime < lastPendingTime) { - root.lastPendingTime = expirationTime; - } + if (workInProgressRoot === root) { + // Received an update to a tree that's in the middle of rendering. Mark + // that's unprocessed work on this root. + markUnprocessedUpdateTime(expirationTime); + + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + // The root already suspended with a delay, which means this render + // definitely won't finish. Since we have a new update, let's mark it as + // suspended now, right before marking the incoming update. This has the + // effect of interrupting the current render and switching to the update. + // TODO: This happens to work when receiving an update during the render + // phase, because of the trick inside computeExpirationForFiber to + // subtract 1 from `renderExpirationTime` to move it into a + // separate bucket. But we should probably model it with an exception, + // using the same mechanism we use to force hydration of a subtree. + // TODO: This does not account for low pri updates that were already + // scheduled before the root started rendering. Need to track the next + // pending expiration time (perhaps by backtracking the return path) and + // then trigger a restart in the `renderDidSuspendDelayIfPossible` path. + markRootSuspendedAtTime(root, renderExpirationTime); + } + } // Mark that the root has a pending update. + + markRootUpdatedAtTime(root, expirationTime); } return root; } -// Use this function, along with runRootCallback, to ensure that only a single -// callback per root is scheduled. It's still possible to call renderRoot -// directly, but scheduling via this function helps avoid excessive callbacks. -// It works by storing the callback node and expiration time on the root. When a -// new callback comes in, it compares the expiration time to determine if it -// should cancel the previous one. It also relies on commitRoot scheduling a -// callback to render the next level, because that means we don't need a -// separate callback per expiration time. -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - var existingCallbackExpirationTime = root.callbackExpirationTime; - if (existingCallbackExpirationTime < expirationTime) { - // New callback has higher priority than the existing one. - var existingCallbackNode = root.callbackNode; - if (existingCallbackNode !== null) { - cancelCallback(existingCallbackNode); - } - root.callbackExpirationTime = expirationTime; - - if (expirationTime === Sync) { - // Sync React callbacks are scheduled on a special internal queue - root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - ); - } else { - var options = null; - if ( - !disableSchedulerTimeoutBasedOnReactExpirationTime && - expirationTime !== Never - ) { - var timeout = expirationTimeToMs(expirationTime) - now(); - options = { timeout: timeout }; - } - - root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - options - ); - if ( - enableUserTimingAPI && - expirationTime !== Sync && - (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - // Scheduled an async callback, and we're not already working. Add an - // entry to the flamegraph that shows we're waiting for a callback - // to fire. - startRequestCallbackTimer(); - } - } +function getNextRootExpirationTimeToWorkOn(root) { + // Determines the next expiration time that the root should render, taking + // into account levels that may be suspended, or levels that may have + // received a ping. + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + return lastExpiredTime; + } // "Pending" refers to any update that hasn't committed yet, including if it + // suspended. The "suspended" range is therefore a subset. + + var firstPendingTime = root.firstPendingTime; + + if (!isRootSuspendedAtTime(root, firstPendingTime)) { + // The highest priority pending time is not suspended. Let's work on that. + return firstPendingTime; + } // If the first pending time is suspended, check if there's a lower priority + // pending level that we know about. Or check if we received a ping. Work + // on whichever is higher priority. + + var lastPingedTime = root.lastPingedTime; + var nextKnownPendingLevel = root.nextKnownPendingLevel; + return lastPingedTime > nextKnownPendingLevel + ? lastPingedTime + : nextKnownPendingLevel; +} // Use this function to schedule a task for a root. There's only one task per +// root; if a task was already scheduled, we'll check to make sure the +// expiration time of the existing task is the same as the expiration time of +// the next level that the root has work on. This function is called on every +// update, and right before exiting a task. + +function ensureRootIsScheduled(root) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime !== NoWork) { + // Special case: Expired work should flush synchronously. + root.callbackExpirationTime = Sync; + root.callbackPriority = ImmediatePriority; + root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + ); + return; } - // Associate the current interactions with this new root+priority. - schedulePendingInteractions(root, expirationTime); -} + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + var existingCallbackNode = root.callbackNode; -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode; - var continuation = null; - try { - continuation = callback(isSync); - if (continuation !== null) { - return runRootCallback.bind(null, root, continuation); - } else { - return null; - } - } finally { - // If the callback exits without returning a continuation, remove the - // corresponding callback node from the root. Unless the callback node - // has changed, which implies that it was already cancelled by a high - // priority update. - if (continuation === null && prevCallbackNode === root.callbackNode) { + if (expirationTime === NoWork) { + // There's nothing to work on. + if (existingCallbackNode !== null) { root.callbackNode = null; root.callbackExpirationTime = NoWork; + root.callbackPriority = NoPriority; } - } -} -function flushDiscreteUpdates() { - // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. - // However, `act` uses `batchedUpdates`, so there's no way to distinguish - // those two cases. Need to fix this before exposing flushDiscreteUpdates - // as a public API. - if ( - (executionContext & (BatchedContext | RenderContext | CommitContext)) !== - NoContext - ) { - if (true && (executionContext & RenderContext) !== NoContext) { - warning$1( - false, - "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + - "already rendering." - ); - } - // We're already rendering, so we can't synchronously flush pending work. - // This is probably a nested event dispatch triggered by a lifecycle/effect, - // like `el.focus()`. Exit. return; - } - flushPendingDiscreteUpdates(); - if (!revertPassiveEffectsChange) { - // If the discrete updates scheduled passive effects, flush them now so that - // they fire before the next serial event. - flushPassiveEffects(); - } -} + } // TODO: If this is an update, we already read the current time. Pass the + // time as an argument. -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - if ( - firstBatch !== null && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ) { - scheduleCallback(NormalPriority, function() { - firstBatch._onComplete(); - return null; - }); - return true; - } else { - return false; - } -} + var currentTime = requestCurrentTime(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); // If there's an existing render task, confirm it has the correct priority and + // expiration time. Otherwise, we'll cancel it and schedule a new one. -function flushPendingDiscreteUpdates() { - if (rootsWithPendingDiscreteUpdates !== null) { - // For each root with pending discrete updates, schedule a callback to - // immediately flush them. - var roots = rootsWithPendingDiscreteUpdates; - rootsWithPendingDiscreteUpdates = null; - roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - }); - // Now flush the immediate queue. - flushSyncCallbackQueue(); - } -} + if (existingCallbackNode !== null) { + var existingCallbackPriority = root.callbackPriority; + var existingCallbackExpirationTime = root.callbackExpirationTime; -function batchedUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + if ( + // Callback must have the exact same expiration time. + existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority. + existingCallbackPriority >= priorityLevel + ) { + // Existing callback is sufficient. + return; + } // Need to schedule a new task. + // TODO: Instead of scheduling a new task, we should be able to change the + // priority of the existing one. -function batchedEventUpdates$1(fn, a) { - var prevExecutionContext = executionContext; - executionContext |= EventContext; - try { - return fn(a); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } + cancelCallback(existingCallbackNode); } -} -function discreteUpdates$1(fn, a, b, c) { - var prevExecutionContext = executionContext; - executionContext |= DiscreteEventContext; - try { - // Should this - return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); - } finally { - executionContext = prevExecutionContext; - if (executionContext === NoContext) { - // Flush the immediate callbacks that were scheduled during this batch - flushSyncCallbackQueue(); - } - } -} + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + var callbackNode; -function flushSync(fn, a) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { - (function() { + if (expirationTime === Sync) { + // Sync React callbacks are scheduled on a special internal queue + callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); + } else if (disableSchedulerTimeoutBasedOnReactExpirationTime) { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root) + ); + } else { + callbackNode = scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects + // ordering because tasks are processed in timeout order. { - throw ReactError( - Error( - "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." - ) - ); + timeout: expirationTimeToMs(expirationTime) - now() } - })(); - } - var prevExecutionContext = executionContext; - executionContext |= BatchedContext; - try { - return runWithPriority(ImmediatePriority, fn.bind(null, a)); - } finally { - executionContext = prevExecutionContext; - // Flush the immediate callbacks that were scheduled during this batch. - // Note that this will happen even if batchedUpdates is higher up - // the stack. - flushSyncCallbackQueue(); + ); } -} -function prepareFreshStack(root, expirationTime) { - root.finishedWork = null; - root.finishedExpirationTime = NoWork; + root.callbackNode = callbackNode; +} // This is the entry point for every concurrent task, i.e. anything that +// goes through Scheduler. - var timeoutHandle = root.timeoutHandle; - if (timeoutHandle !== noTimeout) { - // The root previous suspended and scheduled a timeout to commit a fallback - // state. Now that we have additional work, cancel the timeout. - root.timeoutHandle = noTimeout; - // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above - cancelTimeout(timeoutHandle); - } +function performConcurrentWorkOnRoot(root, didTimeout) { + // Since we know we're in a React event, we can clear the current + // event time. The next update will compute a new event time. + currentEventTime = NoWork; - if (workInProgress !== null) { - var interruptedWork = workInProgress.return; - while (interruptedWork !== null) { - unwindInterruptedWork(interruptedWork); - interruptedWork = interruptedWork.return; + if (didTimeout) { + // The render task took too long to complete. Mark the current time as + // expired to synchronously render all expired work in a single batch. + var currentTime = requestCurrentTime(); + markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback. + + ensureRootIsScheduled(root); + return null; + } // Determine the next expiration time to work on, using the fields stored + // on the root. + + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + + if (expirationTime !== NoWork) { + var originalCallbackNode = root.callbackNode; + + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); } - } - workInProgressRoot = root; - workInProgress = createWorkInProgress(root.current, null, expirationTime); - renderExpirationTime = expirationTime; - workInProgressRootExitStatus = RootIncomplete; - workInProgressRootLatestProcessedExpirationTime = Sync; - workInProgressRootLatestSuspenseTimeout = Sync; - workInProgressRootCanSuspendUsingConfig = null; - workInProgressRootHasPendingPing = false; - - if (enableSchedulerTracing) { - spawnedWorkDuringRender = null; - } - - { - ReactStrictModeWarnings.discardPendingWarnings(); - componentsThatTriggeredHighPriSuspend = null; - } -} -function renderRoot(root, expirationTime, isSync) { - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. - if (enableUserTimingAPI && expirationTime !== Sync) { - var didExpire = isSync; - stopRequestCallbackTimer(didExpire); - } + if ( + root !== workInProgressRoot || + expirationTime !== renderExpirationTime + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. - if (root.firstPendingTime < expirationTime) { - // If there's no work left at this expiration time, exit immediately. This - // happens when multiple callbacks are scheduled for a single root, but an - // earlier callback flushes the work of a later one. - return null; - } + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); - if (isSync && root.finishedExpirationTime === expirationTime) { - // There's already a pending commit at this expiration time. - // TODO: This is poorly factored. This case only exists for the - // batch.commit() API. - return commitRoot.bind(null, root); - } + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); - flushPassiveEffects(); + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); - // If the root or expiration time have changed, throw out the existing stack - // and prepare a fresh one. Otherwise we'll continue where we left off. - if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) { - prepareFreshStack(root, expirationTime); - startWorkOnPendingInteractions(root, expirationTime); - } else if (workInProgressRootExitStatus === RootSuspendedWithDelay) { - // We could've received an update at a lower priority while we yielded. - // We're suspended in a delayed state. Once we complete this render we're - // just going to try to recover at the last pending time anyway so we might - // as well start doing that eagerly. - // Ideally we should be able to do this even for retries but we don't yet - // know if we're going to process an update which wants to commit earlier, - // and this path happens very early so it would happen too often. Instead, - // for that case, we'll wait until we complete. - if (workInProgressRootHasPendingPing) { - // We have a ping at this expiration. Let's restart to see if we get unblocked. - prepareFreshStack(root, expirationTime); - } else { - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately, while preserving the position in the queue. - return renderRoot.bind(null, root, lastPendingTime); + if (enableSchedulerTracing) { + popInteractions(prevInteractions); } - } - } - // If we have a work-in-progress fiber, it means there's still work to do - // in this root. - if (workInProgress !== null) { - var prevExecutionContext = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - if (prevDispatcher === null) { - // The React isomorphic package does not include a default dispatcher. - // Instead the first renderer will lazily attach one, in order to give - // nicer error messages. - prevDispatcher = ContextOnlyDispatcher; - } - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - startWorkLoopTimer(workInProgress); - - // TODO: Fork renderRoot into renderRootSync and renderRootAsync - if (isSync) { - if (expirationTime !== Sync) { - // An async update expired. There may be other expired updates on - // this root. We should render all the expired work in a - // single batch. - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) { - // Restart at the current time. - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } - return renderRoot.bind(null, root, currentTime); - } + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; } - } else { - // Since we know we're in a React event, we can clear the current - // event time. The next update will compute a new event time. - currentEventTime = NoWork; - } - - do { - try { - if (isSync) { - workLoopSync(); - } else { - workLoop(); - } - break; - } catch (thrownValue) { - // Reset module-level state that was set during the render phase. - resetContextDependencies(); - resetHooks(); - - var sourceFiber = workInProgress; - if (sourceFiber === null || sourceFiber.return === null) { - // Expected to be working on a non-root fiber. This is a fatal error - // because there's no ancestor that can handle it; the root is - // supposed to capture all errors that weren't caught by an error - // boundary. - prepareFreshStack(root, expirationTime); - executionContext = prevExecutionContext; - throw thrownValue; - } - - if (enableProfilerTimer && sourceFiber.mode & ProfileMode) { - // Record the time spent rendering before an error was thrown. This - // avoids inaccurate Profiler durations in the case of a - // suspended render. - stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true); - } - var returnFiber = sourceFiber.return; - throwException( + if (workInProgress !== null) { + // There's still work left over. Exit without committing. + stopInterruptedWorkLoopTimer(); + } else { + // We now have a consistent tree. The next step is either to commit it, + // or, if something suspended, wait to commit it after a timeout. + stopFinishedWorkLoopTimer(); + var finishedWork = (root.finishedWork = root.current.alternate); + root.finishedExpirationTime = expirationTime; + finishConcurrentRender( root, - returnFiber, - sourceFiber, - thrownValue, - renderExpirationTime + finishedWork, + workInProgressRootExitStatus, + expirationTime ); - workInProgress = completeUnitOfWork(sourceFiber); } - } while (true); - executionContext = prevExecutionContext; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; - } + ensureRootIsScheduled(root); - if (workInProgress !== null) { - // There's still work left over. Return a continuation. - stopInterruptedWorkLoopTimer(); - if (expirationTime !== Sync) { - startRequestCallbackTimer(); + if (root.callbackNode === originalCallbackNode) { + // The task node scheduled for this root is the same one that's + // currently executed. Need to return a continuation. + return performConcurrentWorkOnRoot.bind(null, root); } - return renderRoot.bind(null, root, expirationTime); } } - // We now have a consistent tree. The next step is either to commit it, or, if - // something suspended, wait to commit it after a timeout. - stopFinishedWorkLoopTimer(); - - root.finishedWork = root.current.alternate; - root.finishedExpirationTime = expirationTime; - - var isLocked = resolveLocksOnRoot(root, expirationTime); - if (isLocked) { - // This root has a lock that prevents it from committing. Exit. If we begin - // work on the root again, without any intervening updates, it will finish - // without doing additional work. - return null; - } + return null; +} +function finishConcurrentRender( + root, + finishedWork, + exitStatus, + expirationTime +) { // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: { - (function() { - { - throw ReactError(Error("Should have a work-in-progress.")); - } - })(); + switch (exitStatus) { + case RootIncomplete: + case RootFatalErrored: { + { + throw Error("Root did not complete. This is a bug in React."); + } } - // Flow knows about invariant, so it complains if I add a break statement, - // but eslint doesn't know about invariant, so it complains if I do. - // eslint-disable-next-line no-fallthrough + // Flow knows about invariant, so it complains if I add a break + // statement, but eslint doesn't know about invariant, so it complains + // if I do. eslint-disable-next-line no-fallthrough + case RootErrored: { - // An error was thrown. First check if there is lower priority work - // scheduled on this root. - var _lastPendingTime = root.lastPendingTime; - if (_lastPendingTime < expirationTime) { - // There's lower priority work. Before raising the error, try rendering - // at the lower priority to see if it fixes it. Use a continuation to - // maintain the existing priority and position in the queue. - return renderRoot.bind(null, root, _lastPendingTime); - } - if (!isSync) { - // If we're rendering asynchronously, it's possible the error was - // caused by tearing due to a mutation during an event. Try rendering - // one more time without yiedling to events. - prepareFreshStack(root, expirationTime); - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); - return null; - } - // If we're already rendering synchronously, commit the root in its - // errored state. - return commitRoot.bind(null, root); + // If this was an async render, the error may have happened due to + // a mutation in a concurrent event. Try rendering one more time, + // synchronously, to see if the error goes away. If there are + // lower priority updates, let's include those, too, in case they + // fix the inconsistency. Render at Idle to include all updates. + // If it was Idle or Never or some not-yet-invented time, render + // at that time. + markRootExpiredAtTime( + root, + expirationTime > Idle ? Idle : expirationTime + ); // We assume that this second render pass will be synchronous + // and therefore not hit this path again. + + break; } + case RootSuspended: { - flushSuspensePriorityWarningInDEV(); + markRootSuspendedAtTime(root, expirationTime); + var lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } - // We have an acceptable loading state. We need to figure out if we should - // immediately commit it or wait a bit. + flushSuspensePriorityWarningInDEV(); // We have an acceptable loading state. We need to figure out if we + // should immediately commit it or wait a bit. + // If we have processed new updates during this render, we may now + // have a new loading state ready. We want to ensure that we commit + // that as soon as possible. - // If we have processed new updates during this render, we may now have a - // new loading state ready. We want to ensure that we commit that as soon as - // possible. var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync; + if ( - hasNotProcessedNewUpdates && - !isSync && - // do not delay if we're inside an act() scope + hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // If we have not processed any new updates during this pass, then this is - // either a retry of an existing fallback state or a hidden tree. - // Hidden trees shouldn't be batched with other work and after that's - // fixed it can only be a retry. - // We're going to throttle committing retries so that we don't show too - // many loading states too quickly. + // If we have not processed any new updates during this pass, then + // this is either a retry of an existing fallback state or a + // hidden tree. Hidden trees shouldn't be batched with other work + // and after that's fixed it can only be a retry. We're going to + // throttle committing retries so that we don't show too many + // loading states too quickly. var msUntilTimeout = - globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); - // Don't bother with a very short suspense time. + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. + if (msUntilTimeout > 10) { if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart + // earlier so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } } - var _lastPendingTime2 = root.lastPendingTime; - if (_lastPendingTime2 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level. - return renderRoot.bind(null, root, _lastPendingTime2); + + var nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (nextTime !== NoWork && nextTime !== expirationTime) { + // There's additional work on this root. + break; } - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + + if ( + lastSuspendedTime !== NoWork && + lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = lastSuspendedTime; + break; + } // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. + root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootSuspendedWithDelay: { + markRootSuspendedAtTime(root, expirationTime); + var _lastSuspendedTime = root.lastSuspendedTime; + + if (expirationTime === _lastSuspendedTime) { + root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork); + } + flushSuspensePriorityWarningInDEV(); if ( - !isSync && // do not delay if we're inside an act() scope !(true && flushSuspenseFallbacksInTests && IsThisRendererActing.current) ) { - // We're suspended in a state that should be avoided. We'll try to avoid committing - // it for as long as the timeouts let us. + // We're suspended in a state that should be avoided. We'll try to + // avoid committing it for as long as the timeouts let us. if (workInProgressRootHasPendingPing) { - // This render was pinged but we didn't get to restart earlier so try - // restarting now instead. - prepareFreshStack(root, expirationTime); - return renderRoot.bind(null, root, expirationTime); + var _lastPingedTime = root.lastPingedTime; + + if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) { + // This render was pinged but we didn't get to restart earlier + // so try restarting now instead. + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + + var _nextTime = getNextRootExpirationTimeToWorkOn(root); + + if (_nextTime !== NoWork && _nextTime !== expirationTime) { + // There's additional work on this root. + break; } - var _lastPendingTime3 = root.lastPendingTime; - if (_lastPendingTime3 < expirationTime) { - // There's lower priority work. It might be unsuspended. Try rendering - // at that level immediately. - return renderRoot.bind(null, root, _lastPendingTime3); + + if ( + _lastSuspendedTime !== NoWork && + _lastSuspendedTime !== expirationTime + ) { + // We should prefer to render the fallback of at the last + // suspended level. Ping the last suspended level to try + // rendering it again. + root.lastPingedTime = _lastSuspendedTime; + break; } - var _msUntilTimeout = void 0; + var _msUntilTimeout; + if (workInProgressRootLatestSuspenseTimeout !== Sync) { - // We have processed a suspense config whose expiration time we can use as - // the timeout. + // We have processed a suspense config whose expiration time we + // can use as the timeout. _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now(); } else if (workInProgressRootLatestProcessedExpirationTime === Sync) { - // This should never normally happen because only new updates cause - // delayed states, so we should have processed something. However, - // this could also happen in an offscreen tree. + // This should never normally happen because only new updates + // cause delayed states, so we should have processed something. + // However, this could also happen in an offscreen tree. _msUntilTimeout = 0; } else { - // If we don't have a suspense config, we're going to use a heuristic to + // If we don't have a suspense config, we're going to use a + // heuristic to determine how long we can suspend. var eventTimeMs = inferTimeFromExpirationTime( workInProgressRootLatestProcessedExpirationTime ); @@ -19191,40 +20134,40 @@ function renderRoot(root, expirationTime, isSync) { var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs; var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed < 0) { // We get this wrong some time since we estimate the time. timeElapsed = 0; } - _msUntilTimeout = jnd(timeElapsed) - timeElapsed; - - // Clamp the timeout to the expiration time. - // TODO: Once the event time is exact instead of inferred from expiration time + _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the + // event time is exact instead of inferred from expiration time // we don't need this. + if (timeUntilExpirationMs < _msUntilTimeout) { _msUntilTimeout = timeUntilExpirationMs; } - } + } // Don't bother with a very short suspense time. - // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { - // The render is suspended, it hasn't timed out, and there's no lower - // priority work to do. Instead of committing the fallback + // The render is suspended, it hasn't timed out, and there's no + // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout ); - return null; + break; } - } - // The work expired. Commit immediately. - return commitRoot.bind(null, root); + } // The work expired. Commit immediately. + + commitRoot(root); + break; } + case RootCompleted: { // The work completed. Ready to commit. if ( - !isSync && // do not delay if we're inside an act() scope !( true && @@ -19236,113 +20179,471 @@ function renderRoot(root, expirationTime, isSync) { ) { // If we have exceeded the minimum loading delay, which probably // means we have shown a spinner already, we might have to suspend - // a bit longer to ensure that the spinner is shown for enough time. + // a bit longer to ensure that the spinner is shown for + // enough time. var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay( workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig ); + if (_msUntilTimeout2 > 10) { + markRootSuspendedAtTime(root, expirationTime); root.timeoutHandle = scheduleTimeout( commitRoot.bind(null, root), _msUntilTimeout2 ); - return null; + break; } } - return commitRoot.bind(null, root); + + commitRoot(root); + break; } + default: { - (function() { - { - throw ReactError(Error("Unknown root exit status.")); - } - })(); + { + throw Error("Unknown root exit status."); + } } } -} +} // This is the entry point for synchronous tasks that don't go +// through Scheduler -function markCommitTimeOfFallback() { - globalMostRecentFallbackTime = now(); -} +function performSyncWorkOnRoot(root) { + // Check if there's expired work on this root. Otherwise, render at Sync. + var lastExpiredTime = root.lastExpiredTime; + var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync; + + if (root.finishedExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + // TODO: This is poorly factored. This case only exists for the + // batch.commit() API. + commitRoot(root); + } else { + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } + + flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack + // and prepare a fresh one. Otherwise we'll continue where we left off. -function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { - if ( - expirationTime < workInProgressRootLatestProcessedExpirationTime && - expirationTime > Never - ) { - workInProgressRootLatestProcessedExpirationTime = expirationTime; - } - if (suspenseConfig !== null) { if ( - expirationTime < workInProgressRootLatestSuspenseTimeout && - expirationTime > Never + root !== workInProgressRoot || + expirationTime !== renderExpirationTime ) { - workInProgressRootLatestSuspenseTimeout = expirationTime; - // Most of the time we only have one config and getting wrong is not bad. - workInProgressRootCanSuspendUsingConfig = suspenseConfig; + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteractions(root, expirationTime); + } // If we have a work-in-progress fiber, it means there's still work to do + // in this root. + + if (workInProgress !== null) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + var prevInteractions = pushInteractions(root); + startWorkLoopTimer(workInProgress); + + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + } while (true); + + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + + if (enableSchedulerTracing) { + popInteractions(prevInteractions); + } + + if (workInProgressRootExitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + stopInterruptedWorkLoopTimer(); + prepareFreshStack(root, expirationTime); + markRootSuspendedAtTime(root, expirationTime); + ensureRootIsScheduled(root); + throw fatalError; + } + + if (workInProgress !== null) { + // This is a sync render, so we should have finished the whole tree. + { + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + } else { + // We now have a consistent tree. Because this is a sync render, we + // will commit it even if something suspended. + stopFinishedWorkLoopTimer(); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = expirationTime; + finishSyncRender(root, workInProgressRootExitStatus, expirationTime); + } // Before exiting, make sure there's a callback scheduled for the next + // pending level. + + ensureRootIsScheduled(root); } } + + return null; } -function renderDidSuspend() { - if (workInProgressRootExitStatus === RootIncomplete) { - workInProgressRootExitStatus = RootSuspended; +function finishSyncRender(root, exitStatus, expirationTime) { + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + { + if (exitStatus === RootSuspended || exitStatus === RootSuspendedWithDelay) { + flushSuspensePriorityWarningInDEV(); + } } + + commitRoot(root); } -function renderDidSuspendDelayIfPossible() { +function flushDiscreteUpdates() { + // TODO: Should be able to flush inside batchedUpdates, but not inside `act`. + // However, `act` uses `batchedUpdates`, so there's no way to distinguish + // those two cases. Need to fix this before exposing flushDiscreteUpdates + // as a public API. if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended + (executionContext & (BatchedContext | RenderContext | CommitContext)) !== + NoContext ) { - workInProgressRootExitStatus = RootSuspendedWithDelay; - } -} + if (true && (executionContext & RenderContext) !== NoContext) { + warning$1( + false, + "unstable_flushDiscreteUpdates: Cannot flush updates when React is " + + "already rendering." + ); + } // We're already rendering, so we can't synchronously flush pending work. + // This is probably a nested event dispatch triggered by a lifecycle/effect, + // like `el.focus()`. Exit. -function renderDidError() { - if (workInProgressRootExitStatus !== RootCompleted) { - workInProgressRootExitStatus = RootErrored; + return; } -} -// Called during render to determine if anything has suspended. -// Returns false if we're not sure. -function renderHasNotSuspendedYet() { - // If something errored or completed, we can't really be sure, - // so those are false. - return workInProgressRootExitStatus === RootIncomplete; -} + flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that + // they fire before the next serial event. -function inferTimeFromExpirationTime(expirationTime) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; + flushPassiveEffects(); } -function inferTimeFromExpirationTimeWithSuspenseConfig( - expirationTime, - suspenseConfig -) { - // We don't know exactly when the update was scheduled, but we can infer an - // approximate start time from the expiration time by subtracting the timeout - // that was added to the event time. - var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); - return ( - earliestExpirationTimeMs - - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) - ); +function syncUpdates(fn, a, b, c) { + return runWithPriority(ImmediatePriority, fn.bind(null, a, b, c)); } -function workLoopSync() { - // Already timed out, so perform work without checking if we need to yield. +function flushPendingDiscreteUpdates() { + if (rootsWithPendingDiscreteUpdates !== null) { + // For each root with pending discrete updates, schedule a callback to + // immediately flush them. + var roots = rootsWithPendingDiscreteUpdates; + rootsWithPendingDiscreteUpdates = null; + roots.forEach(function(expirationTime, root) { + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); + }); // Now flush the immediate queue. + + flushSyncCallbackQueue(); + } +} + +function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function batchedEventUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= EventContext; + + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} +function discreteUpdates$1(fn, a, b, c) { + var prevExecutionContext = executionContext; + executionContext |= DiscreteEventContext; + + try { + // Should this + return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); + } finally { + executionContext = prevExecutionContext; + + if (executionContext === NoContext) { + // Flush the immediate callbacks that were scheduled during this batch + flushSyncCallbackQueue(); + } + } +} + +function flushSync(fn, a) { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + { + throw Error( + "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." + ); + } + } + + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + + try { + return runWithPriority(ImmediatePriority, fn.bind(null, a)); + } finally { + executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. + // Note that this will happen even if batchedUpdates is higher up + // the stack. + + flushSyncCallbackQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.finishedWork = null; + root.finishedExpirationTime = NoWork; + var timeoutHandle = root.timeoutHandle; + + if (timeoutHandle !== noTimeout) { + // The root previous suspended and scheduled a timeout to commit a fallback + // state. Now that we have additional work, cancel the timeout. + root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above + + cancelTimeout(timeoutHandle); + } + + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + + while (interruptedWork !== null) { + unwindInterruptedWork(interruptedWork); + interruptedWork = interruptedWork.return; + } + } + + workInProgressRoot = root; + workInProgress = createWorkInProgress(root.current, null, expirationTime); + renderExpirationTime = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; + workInProgressRootLatestProcessedExpirationTime = Sync; + workInProgressRootLatestSuspenseTimeout = Sync; + workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = NoWork; + workInProgressRootHasPendingPing = false; + + if (enableSchedulerTracing) { + spawnedWorkDuringRender = null; + } + + { + ReactStrictModeWarnings.discardPendingWarnings(); + componentsThatTriggeredHighPriSuspend = null; + } +} + +function handleError(root, thrownValue) { + do { + try { + // Reset module-level state that was set during the render phase. + resetContextDependencies(); + resetHooks(); + resetCurrentFiber(); + + if (workInProgress === null || workInProgress.return === null) { + // Expected to be working on a non-root fiber. This is a fatal error + // because there's no ancestor that can handle it; the root is + // supposed to capture all errors that weren't caught by an error + // boundary. + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + return null; + } + + if (enableProfilerTimer && workInProgress.mode & ProfileMode) { + // Record the time spent rendering before an error was thrown. This + // avoids inaccurate Profiler durations in the case of a + // suspended render. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true); + } + + throwException( + root, + workInProgress.return, + workInProgress, + thrownValue, + renderExpirationTime + ); + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + // Something in the return path also threw. + thrownValue = yetAnotherThrownValue; + continue; + } // Return to the normal work loop. + + return; + } while (true); +} + +function pushDispatcher(root) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + + if (prevDispatcher === null) { + // The React isomorphic package does not include a default dispatcher. + // Instead the first renderer will lazily attach one, in order to give + // nicer error messages. + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } +} + +function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher.current = prevDispatcher; +} + +function pushInteractions(root) { + if (enableSchedulerTracing) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; + } + + return null; +} + +function popInteractions(prevInteractions) { + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } +} + +function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); +} +function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { + if ( + expirationTime < workInProgressRootLatestProcessedExpirationTime && + expirationTime > Idle + ) { + workInProgressRootLatestProcessedExpirationTime = expirationTime; + } + + if (suspenseConfig !== null) { + if ( + expirationTime < workInProgressRootLatestSuspenseTimeout && + expirationTime > Idle + ) { + workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad. + + workInProgressRootCanSuspendUsingConfig = suspenseConfig; + } + } +} +function markUnprocessedUpdateTime(expirationTime) { + if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) { + workInProgressRootNextUnprocessedUpdateTime = expirationTime; + } +} +function renderDidSuspend() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} +function renderDidSuspendDelayIfPossible() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootSuspendedWithDelay; + } // Check if there's a lower priority update somewhere else in the tree. + + if ( + workInProgressRootNextUnprocessedUpdateTime !== NoWork && + workInProgressRoot !== null + ) { + // Mark the current render as suspended, and then mark that there's a + // pending update. + // TODO: This should immediately interrupt the current render, instead + // of waiting until the next time we yield. + markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime); + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + ); + } +} +function renderDidError() { + if (workInProgressRootExitStatus !== RootCompleted) { + workInProgressRootExitStatus = RootErrored; + } +} // Called during render to determine if anything has suspended. +// Returns false if we're not sure. + +function renderHasNotSuspendedYet() { + // If something errored or completed, we can't really be sure, + // so those are false. + return workInProgressRootExitStatus === RootIncomplete; +} + +function inferTimeFromExpirationTime(expirationTime) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; +} + +function inferTimeFromExpirationTimeWithSuspenseConfig( + expirationTime, + suspenseConfig +) { + // We don't know exactly when the update was scheduled, but we can infer an + // approximate start time from the expiration time by subtracting the timeout + // that was added to the event time. + var earliestExpirationTimeMs = expirationTimeToMs(expirationTime); + return ( + earliestExpirationTimeMs - + (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION) + ); +} // The work loop is an extremely hot path. Tell Closure not to inline it. + +/** @noinline */ + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. while (workInProgress !== null) { workInProgress = performUnitOfWork(workInProgress); } } +/** @noinline */ -function workLoop() { +function workLoopConcurrent() { // Perform work until Scheduler asks us to yield while (workInProgress !== null && !shouldYield()) { workInProgress = performUnitOfWork(workInProgress); @@ -19354,11 +20655,10 @@ function performUnitOfWork(unitOfWork) { // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = unitOfWork.alternate; - startWorkTimer(unitOfWork); setCurrentFiber(unitOfWork); + var next; - var next = void 0; if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) { startProfilerTimer(unitOfWork); next = beginWork$$1(current$$1, unitOfWork, renderExpirationTime); @@ -19369,6 +20669,7 @@ function performUnitOfWork(unitOfWork) { resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { // If this doesn't spawn new work, complete the current work. next = completeUnitOfWork(unitOfWork); @@ -19382,17 +20683,18 @@ function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. workInProgress = unitOfWork; + do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current$$1 = workInProgress.alternate; - var returnFiber = workInProgress.return; + var returnFiber = workInProgress.return; // Check if the work completed or if something threw. - // Check if the work completed or if something threw. if ((workInProgress.effectTag & Incomplete) === NoEffect) { setCurrentFiber(workInProgress); var next = void 0; + if ( !enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoMode @@ -19400,10 +20702,11 @@ function completeUnitOfWork(unitOfWork) { next = completeWork(current$$1, workInProgress, renderExpirationTime); } else { startProfilerTimer(workInProgress); - next = completeWork(current$$1, workInProgress, renderExpirationTime); - // Update render duration assuming we didn't error. + next = completeWork(current$$1, workInProgress, renderExpirationTime); // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); } + stopWorkTimer(workInProgress); resetCurrentFiber(); resetChildExpirationTime(workInProgress); @@ -19414,8 +20717,7 @@ function completeUnitOfWork(unitOfWork) { } if ( - returnFiber !== null && - // Do not append effects to parents if a sibling failed to complete + returnFiber !== null && // Do not append effects to parents if a sibling failed to complete (returnFiber.effectTag & Incomplete) === NoEffect ) { // Append all the effects of the subtree and this fiber onto the effect @@ -19424,30 +20726,31 @@ function completeUnitOfWork(unitOfWork) { if (returnFiber.firstEffect === null) { returnFiber.firstEffect = workInProgress.firstEffect; } + if (workInProgress.lastEffect !== null) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; } - returnFiber.lastEffect = workInProgress.lastEffect; - } - // If this fiber had side-effects, we append it AFTER the children's + returnFiber.lastEffect = workInProgress.lastEffect; + } // If this fiber had side-effects, we append it AFTER the children's // side-effects. We can perform certain side-effects earlier if needed, // by doing multiple passes over the effect list. We don't want to // schedule our own side-effect on our own list because if end up // reusing children we'll schedule this effect onto itself since we're // at the end. - var effectTag = workInProgress.effectTag; - // Skip both NoWork and PerformedWork tags when creating the effect + var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect // list. PerformedWork effect is read by React DevTools but shouldn't be // committed. + if (effectTag > PerformedWork) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress; } else { returnFiber.firstEffect = workInProgress; } + returnFiber.lastEffect = workInProgress; } } @@ -19455,24 +20758,23 @@ function completeUnitOfWork(unitOfWork) { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. - var _next = unwindWork(workInProgress, renderExpirationTime); - - // Because this fiber did not complete, don't reset its expiration time. + var _next = unwindWork(workInProgress, renderExpirationTime); // Because this fiber did not complete, don't reset its expiration time. if ( enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoMode ) { // Record the render duration for the fiber that errored. - stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing. - // Include the time spent working on failed children before continuing. var actualDuration = workInProgress.actualDuration; var child = workInProgress.child; + while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } + workInProgress.actualDuration = actualDuration; } @@ -19487,6 +20789,7 @@ function completeUnitOfWork(unitOfWork) { _next.effectTag &= HostEffectMask; return _next; } + stopWorkTimer(workInProgress); if (returnFiber !== null) { @@ -19497,21 +20800,30 @@ function completeUnitOfWork(unitOfWork) { } var siblingFiber = workInProgress.sibling; + if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; - } - // Otherwise, return to the parent + } // Otherwise, return to the parent + workInProgress = returnFiber; - } while (workInProgress !== null); + } while (workInProgress !== null); // We've reached the root. - // We've reached the root. if (workInProgressRootExitStatus === RootIncomplete) { workInProgressRootExitStatus = RootCompleted; } + return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + var childExpirationTime = fiber.childExpirationTime; + return updateExpirationTime > childExpirationTime + ? updateExpirationTime + : childExpirationTime; +} + function resetChildExpirationTime(completedWork) { if ( renderExpirationTime !== Never && @@ -19522,55 +20834,62 @@ function resetChildExpirationTime(completedWork) { return; } - var newChildExpirationTime = NoWork; + var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time. - // Bubble up the earliest expiration time. if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; - var treeBaseDuration = completedWork.selfBaseDuration; - - // When a fiber is cloned, its actualDuration is reset to 0. This value will + var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. + var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child; - var child = completedWork.child; + while (child !== null) { var childUpdateExpirationTime = child.expirationTime; var childChildExpirationTime = child.childExpirationTime; + if (childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = childUpdateExpirationTime; } + if (childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = childChildExpirationTime; } + if (shouldBubbleActualDurations) { actualDuration += child.actualDuration; } + treeBaseDuration += child.treeBaseDuration; child = child.sibling; } + completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; + while (_child !== null) { var _childUpdateExpirationTime = _child.expirationTime; var _childChildExpirationTime = _child.childExpirationTime; + if (_childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childUpdateExpirationTime; } + if (_childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childChildExpirationTime; } + _child = _child.sibling; } } @@ -19584,14 +20903,6 @@ function commitRoot(root) { ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel) ); - // If there are passive effects, schedule a callback to flush them. This goes - // outside commitRootImpl so that it inherits the priority of the render. - if (rootWithPendingPassiveEffects !== null) { - scheduleCallback(NormalPriority, function() { - flushPassiveEffects(); - return null; - }); - } return null; } @@ -19599,51 +20910,42 @@ function commitRootImpl(root, renderPriorityLevel) { flushPassiveEffects(); flushRenderPhaseStrictModeWarningsInDEV(); - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError(Error("Should not already be working.")); - } - })(); + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Should not already be working."); + } var finishedWork = root.finishedWork; var expirationTime = root.finishedExpirationTime; + if (finishedWork === null) { return null; } + root.finishedWork = null; root.finishedExpirationTime = NoWork; - (function() { - if (!(finishedWork !== root.current)) { - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - })(); - - // commitRoot never returns a continuation; it always finishes synchronously. + if (!(finishedWork !== root.current)) { + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." + ); + } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. + root.callbackNode = null; root.callbackExpirationTime = NoWork; - - startCommitTimer(); - - // Update the first and last pending times on this root. The new first + root.callbackPriority = NoPriority; + root.nextKnownPendingLevel = NoWork; + startCommitTimer(); // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime; - var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - var firstPendingTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = firstPendingTimeBeforeCommit; - if (firstPendingTimeBeforeCommit < root.lastPendingTime) { - // This usually means we've finished all the work, but it can also happen - // when something gets downprioritized during render, like a hidden tree. - root.lastPendingTime = firstPendingTimeBeforeCommit; - } + + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + markRootFinishedAtTime( + root, + expirationTime, + remainingExpirationTimeBeforeCommit + ); if (root === workInProgressRoot) { // We can reset these now that they are finished. @@ -19651,13 +20953,13 @@ function commitRootImpl(root, renderPriorityLevel) { workInProgress = null; renderExpirationTime = NoWork; } else { - } - // This indicates that the last root we worked on is not the same one that + } // This indicates that the last root we worked on is not the same one that // we're committing now. This most commonly happens when a suspended root // times out. - // Get the list of effects. - var firstEffect = void 0; + + var firstEffect; + if (finishedWork.effectTag > PerformedWork) { // A fiber's effect list consists only of its children, not itself. So if // the root has an effect, we need to add it to the end of the list. The @@ -19677,85 +20979,82 @@ function commitRootImpl(root, renderPriorityLevel) { if (firstEffect !== null) { var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; - } - - // Reset this to null before calling lifecycles - ReactCurrentOwner$2.current = null; + var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles - // The commit phase is broken into several sub-phases. We do a separate pass + ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. - // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. + startCommitSnapshotEffectsTimer(); prepareForCommit(root.containerInfo); nextEffect = firstEffect; + do { { invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); + stopCommitSnapshotEffectsTimer(); if (enableProfilerTimer) { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); - } + } // The next phase is the mutation phase, where we mutate the host tree. - // The next phase is the mutation phase, where we mutate the host tree. startCommitHostEffectsTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( null, commitMutationEffects, null, + root, renderPriorityLevel ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitHostEffectsTimer(); - resetAfterCommit(root.containerInfo); - // The work-in-progress tree is now the current tree. This must come after + stopCommitHostEffectsTimer(); + resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. - root.current = finishedWork; - // The next phase is the layout phase, where we call effects that read + root.current = finishedWork; // The next phase is the layout phase, where we call effects that read // the host tree after it's been mutated. The idiomatic use case for this is // layout, but class component lifecycles also fire here for legacy reasons. + startCommitLifeCyclesTimer(); nextEffect = firstEffect; + do { { invokeGuardedCallback( @@ -19765,41 +21064,44 @@ function commitRootImpl(root, renderPriorityLevel) { root, expirationTime ); + if (hasCaughtError()) { - (function() { - if (!(nextEffect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(nextEffect !== null)) { + throw Error("Should be working on an effect."); + } + var _error2 = clearCaughtError(); + captureCommitPhaseError(nextEffect, _error2); nextEffect = nextEffect.nextEffect; } } } while (nextEffect !== null); - stopCommitLifeCyclesTimer(); - nextEffect = null; - - // Tell Scheduler to yield at the end of the frame, so the browser has an + stopCommitLifeCyclesTimer(); + nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an // opportunity to paint. + requestPaint(); if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); } + executionContext = prevExecutionContext; } else { // No effects. - root.current = finishedWork; - // Measure these anyway so the flamegraph explicitly shows that there were + root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. + startCommitSnapshotEffectsTimer(); stopCommitSnapshotEffectsTimer(); + if (enableProfilerTimer) { recordCommitTime(); } + startCommitHostEffectsTimer(); stopCommitHostEffectsTimer(); startCommitLifeCyclesTimer(); @@ -19807,7 +21109,6 @@ function commitRootImpl(root, renderPriorityLevel) { } stopCommitTimer(); - var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { @@ -19822,26 +21123,22 @@ function commitRootImpl(root, renderPriorityLevel) { // nextEffect pointers to assist with GC. If we have passive effects, we'll // clear this in flushPassiveEffects. nextEffect = firstEffect; + while (nextEffect !== null) { var nextNextEffect = nextEffect.nextEffect; nextEffect.nextEffect = null; nextEffect = nextNextEffect; } - } + } // Check if there's remaining work on this root - // Check if there's remaining work on this root var remainingExpirationTime = root.firstPendingTime; - if (remainingExpirationTime !== NoWork) { - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - remainingExpirationTime - ); + if (remainingExpirationTime !== NoWork) { if (enableSchedulerTracing) { if (spawnedWorkDuringRender !== null) { var expirationTimes = spawnedWorkDuringRender; spawnedWorkDuringRender = null; + for (var i = 0; i < expirationTimes.length; i++) { scheduleInteractions( root, @@ -19850,9 +21147,9 @@ function commitRootImpl(root, renderPriorityLevel) { ); } } - } - scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + schedulePendingInteractions(root, remainingExpirationTime); + } } else { // If there's no remaining work, we can clear the set of already failed // error boundaries. @@ -19869,8 +21166,6 @@ function commitRootImpl(root, renderPriorityLevel) { } } - onCommitRoot(finishedWork.stateNode, expirationTime); - if (remainingExpirationTime === Sync) { // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. @@ -19884,6 +21179,11 @@ function commitRootImpl(root, renderPriorityLevel) { nestedUpdateCount = 0; } + onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any + // additional work on this root is scheduled. + + ensureRootIsScheduled(root); + if (hasUncaughtError) { hasUncaughtError = false; var _error3 = firstUncaughtError; @@ -19897,33 +21197,44 @@ function commitRootImpl(root, renderPriorityLevel) { // synchronously, but layout updates should be deferred until the end // of the batch. return null; - } + } // If layout work was scheduled, flush it now. - // If layout work was scheduled, flush it now. flushSyncCallbackQueue(); return null; } function commitBeforeMutationEffects() { while (nextEffect !== null) { - if ((nextEffect.effectTag & Snapshot) !== NoEffect) { + var effectTag = nextEffect.effectTag; + + if ((effectTag & Snapshot) !== NoEffect) { setCurrentFiber(nextEffect); recordEffect(); - var current$$1 = nextEffect.alternate; commitBeforeMutationLifeCycles(current$$1, nextEffect); - resetCurrentFiber(); } + + if ((effectTag & Passive) !== NoEffect) { + // If there are passive effects, schedule a callback to flush at + // the earliest opportunity. + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + scheduleCallback(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + nextEffect = nextEffect.nextEffect; } } -function commitMutationEffects(renderPriorityLevel) { +function commitMutationEffects(root, renderPriorityLevel) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & ContentReset) { @@ -19932,52 +21243,67 @@ function commitMutationEffects(renderPriorityLevel) { if (effectTag & Ref) { var current$$1 = nextEffect.alternate; + if (current$$1 !== null) { commitDetachRef(current$$1); } - } - - // The following switch statement is only concerned about placement, + } // The following switch statement is only concerned about placement, // updates, and deletions. To avoid needing to add a case for every possible // bitmap value, we remove the secondary effects from the effect tag and // switch on that value. - var primaryEffectTag = effectTag & (Placement | Update | Deletion); + + var primaryEffectTag = + effectTag & (Placement | Update | Deletion | Hydrating); + switch (primaryEffectTag) { case Placement: { - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. + nextEffect.effectTag &= ~Placement; break; } + case PlacementAndUpdate: { // Placement - commitPlacement(nextEffect); - // Clear the "placement" from effect tag so that we know that this is + commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. - nextEffect.effectTag &= ~Placement; - // Update + nextEffect.effectTag &= ~Placement; // Update + var _current = nextEffect.alternate; commitWork(_current, nextEffect); break; } - case Update: { + + case Hydrating: { + nextEffect.effectTag &= ~Hydrating; + break; + } + + case HydratingAndUpdate: { + nextEffect.effectTag &= ~Hydrating; // Update + var _current2 = nextEffect.alternate; commitWork(_current2, nextEffect); break; } + + case Update: { + var _current3 = nextEffect.alternate; + commitWork(_current3, nextEffect); + break; + } + case Deletion: { - commitDeletion(nextEffect, renderPriorityLevel); + commitDeletion(root, nextEffect, renderPriorityLevel); break; } - } + } // TODO: Only record a mutation effect if primaryEffectTag is non-zero. - // TODO: Only record a mutation effect if primaryEffectTag is non-zero. recordEffect(); - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } @@ -19987,7 +21313,6 @@ function commitLayoutEffects(root, committedExpirationTime) { // TODO: Should probably move the bulk of this function to commitWork. while (nextEffect !== null) { setCurrentFiber(nextEffect); - var effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) { @@ -20001,88 +21326,78 @@ function commitLayoutEffects(root, committedExpirationTime) { commitAttachRef(nextEffect); } - if (effectTag & Passive) { - rootDoesHavePassiveEffects = true; - } - resetCurrentFiber(); nextEffect = nextEffect.nextEffect; } } function flushPassiveEffects() { + if (pendingPassiveEffectsRenderPriority !== NoPriority) { + var priorityLevel = + pendingPassiveEffectsRenderPriority > NormalPriority + ? NormalPriority + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = NoPriority; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} + +function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } + var root = rootWithPendingPassiveEffects; var expirationTime = pendingPassiveEffectsExpirationTime; - var renderPriorityLevel = pendingPassiveEffectsRenderPriority; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = NoWork; - pendingPassiveEffectsRenderPriority = NoPriority; - var priorityLevel = - renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel; - return runWithPriority( - priorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = null; - if (enableSchedulerTracing) { - prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { + throw Error("Cannot flush passive effects while already rendering."); } - (function() { - if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) { - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); - } - })(); var prevExecutionContext = executionContext; executionContext |= CommitContext; - - // Note: This currently assumes there are no passive effects on the root + var prevInteractions = pushInteractions(root); // Note: This currently assumes there are no passive effects on the root // fiber, because the root is not part of its own effect list. This could // change in the future. + var effect = root.current.firstEffect; + while (effect !== null) { { setCurrentFiber(effect); invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + if (hasCaughtError()) { - (function() { - if (!(effect !== null)) { - throw ReactError(Error("Should be working on an effect.")); - } - })(); + if (!(effect !== null)) { + throw Error("Should be working on an effect."); + } + var error = clearCaughtError(); captureCommitPhaseError(effect, error); } + resetCurrentFiber(); } - var nextNextEffect = effect.nextEffect; - // Remove nextEffect pointer to assist GC + + var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC + effect.nextEffect = null; effect = nextNextEffect; } if (enableSchedulerTracing) { - tracing.__interactionsRef.current = prevInteractions; + popInteractions(prevInteractions); finishPendingInteractions(root, expirationTime); } executionContext = prevExecutionContext; - flushSyncCallbackQueue(); - - // If additional passive effects were scheduled, increment a counter. If this + flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; - return true; } @@ -20092,7 +21407,6 @@ function isAlreadyFailedLegacyErrorBoundary(instance) { legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } - function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); @@ -20107,6 +21421,7 @@ function prepareToThrowUncaughtError(error) { firstUncaughtError = error; } } + var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { @@ -20114,8 +21429,10 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); enqueueUpdate(rootFiber, update); var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } } @@ -20128,6 +21445,7 @@ function captureCommitPhaseError(sourceFiber, error) { } var fiber = sourceFiber.return; + while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); @@ -20135,6 +21453,7 @@ function captureCommitPhaseError(sourceFiber, error) { } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; + if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && @@ -20143,24 +21462,27 @@ function captureCommitPhaseError(sourceFiber, error) { var errorInfo = createCapturedValue(error, sourceFiber); var update = createClassErrorUpdate( fiber, - errorInfo, - // TODO: This is always sync + errorInfo, // TODO: This is always sync Sync ); enqueueUpdate(fiber, update); var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { - scheduleCallbackForRoot(root, ImmediatePriority, Sync); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, Sync); } + return; } } + fiber = fiber.return; } } - function pingSuspendedRoot(root, thenable, suspendedTime) { var pingCache = root.pingCache; + if (pingCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. @@ -20171,10 +21493,8 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. - // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. - // If we're suspended with delay, we'll always suspend so we can always // restart. If we're suspended without any updates, it might be a retry. // If it's early in the retry we can restart. We can't know for sure @@ -20195,23 +21515,23 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { // opportunity later. So we mark this render as having a ping. workInProgressRootHasPendingPing = true; } + return; } - var lastPendingTime = root.lastPendingTime; - if (lastPendingTime < suspendedTime) { + if (!isRootSuspendedAtTime(root, suspendedTime)) { // The root is no longer suspended at this time. return; } - var pingTime = root.pingTime; - if (pingTime !== NoWork && pingTime < suspendedTime) { + var lastPingedTime = root.lastPingedTime; + + if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) { // There's already a lower priority ping scheduled. return; - } + } // Mark the time at which this ping was scheduled. - // Mark the time at which this ping was scheduled. - root.pingTime = suspendedTime; + root.lastPingedTime = suspendedTime; if (root.finishedExpirationTime === suspendedTime) { // If there's a pending fallback waiting to commit, throw it away. @@ -20219,54 +21539,70 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { root.finishedWork = null; } - var currentTime = requestCurrentTime(); - var priorityLevel = inferPriorityFromExpirationTime( - currentTime, - suspendedTime - ); - scheduleCallbackForRoot(root, priorityLevel, suspendedTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, suspendedTime); } -function retryTimedOutBoundary(boundaryFiber) { +function retryTimedOutBoundary(boundaryFiber, retryTime) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new expiration time. - var currentTime = requestCurrentTime(); - var suspenseConfig = null; // Retries don't carry over the already committed update. - var retryTime = computeExpirationForFiber( - currentTime, - boundaryFiber, - suspenseConfig - ); - // TODO: Special case idle priority? - var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + if (retryTime === NoWork) { + var suspenseConfig = null; // Retries don't carry over the already committed update. + + var currentTime = requestCurrentTime(); + retryTime = computeExpirationForFiber( + currentTime, + boundaryFiber, + suspenseConfig + ); + } // TODO: Special case idle priority? + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { - scheduleCallbackForRoot(root, priorityLevel, retryTime); + ensureRootIsScheduled(root); + schedulePendingInteractions(root, retryTime); } } +function retryDehydratedSuspenseBoundary(boundaryFiber) { + var suspenseState = boundaryFiber.memoizedState; + var retryTime = NoWork; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + + retryTimedOutBoundary(boundaryFiber, retryTime); +} function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = void 0; + var retryTime = NoWork; // Default + + var retryCache; + if (enableSuspenseServerRenderer) { switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; + var suspenseState = boundaryFiber.memoizedState; + + if (suspenseState !== null) { + retryTime = suspenseState.retryTime; + } + break; - case DehydratedSuspenseComponent: - retryCache = boundaryFiber.memoizedState; + + case SuspenseListComponent: + retryCache = boundaryFiber.stateNode; break; - default: - (function() { - { - throw ReactError( - Error( - "Pinged unknown suspense boundary type. This is probably a bug in React." - ) - ); - } - })(); + + default: { + throw Error( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } } } else { retryCache = boundaryFiber.stateNode; @@ -20278,10 +21614,8 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); -} - -// Computes the next Just Noticeable Difference (JND) boundary. + retryTimedOutBoundary(boundaryFiber, retryTime); +} // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid @@ -20290,6 +21624,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. + function jnd(timeElapsed) { return timeElapsed < 120 ? 120 @@ -20312,25 +21647,28 @@ function computeMsUntilSuspenseLoadingDelay( suspenseConfig ) { var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0; + if (busyMinDurationMs <= 0) { return 0; } - var busyDelayMs = suspenseConfig.busyDelayMs | 0; - // Compute the time until this render pass would expire. + var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire. + var currentTimeMs = now(); var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig( mostRecentEventTime, suspenseConfig ); var timeElapsed = currentTimeMs - eventTimeMs; + if (timeElapsed <= busyDelayMs) { // If we haven't yet waited longer than the initial delay, we don't // have to wait any additional time. return 0; } - var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; - // This is the value that is passed to `setTimeout`. + + var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`. + return msUntilTimeout; } @@ -20338,15 +21676,12 @@ function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; - (function() { - { - throw ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) - ); - } - })(); + + { + 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." + ); + } } { @@ -20397,9 +21732,11 @@ function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { } var didWarnStateUpdateForUnmountedComponent = null; + function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { { var tag = fiber.tag; + if ( tag !== HostRoot && tag !== ClassComponent && @@ -20410,18 +21747,21 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { ) { // Only warn for user-defined components, not internal ones like Suspense. return; - } - // We show the whole stack but dedupe on the top component's name because + } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent !== null) { if (didWarnStateUpdateForUnmountedComponent.has(componentName)) { return; } + didWarnStateUpdateForUnmountedComponent.add(componentName); } else { didWarnStateUpdateForUnmountedComponent = new Set([componentName]); } + warningWithoutStack$1( false, "Can't perform a React state update on an unmounted component. This " + @@ -20435,20 +21775,22 @@ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { } } -var beginWork$$1 = void 0; +var beginWork$$1; + if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var dummyFiber = null; + beginWork$$1 = function(current$$1, unitOfWork, expirationTime) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. - // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV( dummyFiber, unitOfWork ); + try { return beginWork$1(current$$1, unitOfWork, expirationTime); } catch (originalError) { @@ -20459,25 +21801,23 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ) { // Don't replay promises. Treat everything else like an error. throw originalError; - } - - // Keep this code in sync with renderRoot; any changes here must have + } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. - resetContextDependencies(); - resetHooks(); + resetContextDependencies(); + resetHooks(); // Don't reset current debug fiber, since we're about to work on the + // same fiber again. // Unwind the failed stack frame - unwindInterruptedWork(unitOfWork); - // Restore the original properties of the fiber. + unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber. + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if (enableProfilerTimer && unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); - } + } // Run beginWork again. - // Run beginWork again. invokeGuardedCallback( null, beginWork$1, @@ -20488,9 +21828,9 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { ); if (hasCaughtError()) { - var replayError = clearCaughtError(); - // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. + var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`. // Rethrow this error instead of the original one. + throw replayError; } else { // This branch is reachable if the render phase is impure. @@ -20504,6 +21844,7 @@ if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInGetChildContext = false; + function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { { if (fiber.tag === ClassComponent) { @@ -20512,16 +21853,19 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { if (didWarnAboutUpdateInGetChildContext) { return; } + warningWithoutStack$1( false, "setState(...): Cannot call setState() inside getChildContext()" ); didWarnAboutUpdateInGetChildContext = true; break; + case "render": if (didWarnAboutUpdateInRender) { return; } + warningWithoutStack$1( false, "Cannot update during an existing state transition (such as " + @@ -20533,11 +21877,11 @@ function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { } } } -} - -// a 'shared' variable that changes when act() opens/closes in tests. -var IsThisRendererActing = { current: false }; +} // a 'shared' variable that changes when act() opens/closes in tests. +var IsThisRendererActing = { + current: false +}; function warnIfNotScopedWithMatchingAct(fiber) { { if ( @@ -20564,7 +21908,6 @@ function warnIfNotScopedWithMatchingAct(fiber) { } } } - function warnIfNotCurrentlyActingEffectsInDEV(fiber) { { if ( @@ -20621,11 +21964,9 @@ function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { } } -var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; +var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler. -// In tests, we want to enforce a mocked scheduler. -var didWarnAboutUnmockedScheduler = false; -// TODO Before we release concurrent mode, revisit this and decide whether a mocked +var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked // scheduler is the actual recommendation. The alternative could be a testing build, // a new lib, or whatever; we dunno just yet. This message is for early adopters // to get their tests right. @@ -20660,20 +22001,22 @@ function warnIfUnmockedScheduler(fiber) { } } } - var componentsThatTriggeredHighPriSuspend = null; function checkForWrongSuspensePriorityInDEV(sourceFiber) { { var currentPriorityLevel = getCurrentPriorityLevel(); + if ( (sourceFiber.mode & ConcurrentMode) !== NoEffect && (currentPriorityLevel === UserBlockingPriority || currentPriorityLevel === ImmediatePriority) ) { var workInProgressNode = sourceFiber; + while (workInProgressNode !== null) { // Add the component that triggered the suspense var current$$1 = workInProgressNode.alternate; + if (current$$1 !== null) { // TODO: warn component that triggers the high priority // suspend is the HostRoot @@ -20682,10 +22025,13 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { // Loop through the component's update queue and see whether the component // has triggered any high priority updates var updateQueue = current$$1.updateQueue; + if (updateQueue !== null) { var update = updateQueue.firstUpdate; + while (update !== null) { var priorityLevel = update.priority; + if ( priorityLevel === UserBlockingPriority || priorityLevel === ImmediatePriority @@ -20699,12 +22045,16 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + update = update.next; } } + break; + case FunctionComponent: case ForwardRef: case SimpleMemoComponent: @@ -20712,11 +22062,12 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { workInProgressNode.memoizedState !== null && workInProgressNode.memoizedState.baseUpdate !== null ) { - var _update = workInProgressNode.memoizedState.baseUpdate; - // Loop through the functional component's memoized state to see whether + var _update = workInProgressNode.memoizedState.baseUpdate; // Loop through the functional component's memoized state to see whether // the component has triggered any high pri updates + while (_update !== null) { var priority = _update.priority; + if ( priority === UserBlockingPriority || priority === ImmediatePriority @@ -20730,21 +22081,27 @@ function checkForWrongSuspensePriorityInDEV(sourceFiber) { getComponentName(workInProgressNode.type) ); } + break; } + if ( _update.next === workInProgressNode.memoizedState.baseUpdate ) { break; } + _update = _update.next; } } + break; + default: break; } } + workInProgressNode = workInProgressNode.return; } } @@ -20770,8 +22127,7 @@ function flushSuspensePriorityWarningInDEV() { "triggers the bulk of the changes." + "\n\n" + "Refer to the documentation for useSuspenseTransition to learn how " + - "to implement this pattern.", - // TODO: Add link to React docs with more information, once it exists + "to implement this pattern.", // TODO: Add link to React docs with more information, once it exists componentNames.sort().join(", ") ); } @@ -20788,6 +22144,7 @@ function markSpawnedWork(expirationTime) { if (!enableSchedulerTracing) { return; } + if (spawnedWorkDuringRender === null) { spawnedWorkDuringRender = [expirationTime]; } else { @@ -20803,6 +22160,7 @@ function scheduleInteractions(root, expirationTime, interactions) { if (interactions.size > 0) { var pendingInteractionMap = root.pendingInteractionMap; var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { interactions.forEach(function(interaction) { if (!pendingInteractions.has(interaction)) { @@ -20813,15 +22171,15 @@ function scheduleInteractions(root, expirationTime, interactions) { pendingInteractions.add(interaction); }); } else { - pendingInteractionMap.set(expirationTime, new Set(interactions)); + pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions. - // Update the pending async work count for the current interactions. interactions.forEach(function(interaction) { interaction.__count++; }); } var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); subscriber.onWorkScheduled(interactions, threadID); @@ -20844,11 +22202,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { // This is called when new work is started on a root. if (!enableSchedulerTracing) { return; - } - - // Determine which interactions this batch of work currently includes, So that + } // Determine which interactions this batch of work currently includes, So that // we can accurately attribute time spent working on it, And so that cascading // work triggered during the render phase will be associated with it. + var interactions = new Set(); root.pendingInteractionMap.forEach(function( scheduledInteractions, @@ -20859,19 +22216,20 @@ function startWorkOnPendingInteractions(root, expirationTime) { return interactions.add(interaction); }); } - }); + }); // Store the current set of interactions on the FiberRoot for a few reasons: + // We can re-use it in hot functions like performConcurrentWorkOnRoot() + // without having to recalculate it. We will also use it in commitWork() to + // pass to any Profiler onRender() hooks. This also provides DevTools with a + // way to access it when the onCommitRoot() hook is called. - // Store the current set of interactions on the FiberRoot for a few reasons: - // We can re-use it in hot functions like renderRoot() without having to - // recalculate it. We will also use it in commitWork() to pass to any Profiler - // onRender() hooks. This also provides DevTools with a way to access it when - // the onCommitRoot() hook is called. root.memoizedInteractions = interactions; if (interactions.size > 0) { var subscriber = tracing.__subscriberRef.current; + if (subscriber !== null) { var threadID = computeThreadID(root, expirationTime); + try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { @@ -20890,11 +22248,11 @@ function finishPendingInteractions(root, committedExpirationTime) { } var earliestRemainingTimeAfterCommit = root.firstPendingTime; - - var subscriber = void 0; + var subscriber; try { subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { var threadID = computeThreadID(root, committedExpirationTime); subscriber.onWorkStopped(root.memoizedInteractions, threadID); @@ -20918,7 +22276,6 @@ function finishPendingInteractions(root, committedExpirationTime) { // That indicates that we are waiting for suspense data. if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { pendingInteractionMap.delete(scheduledExpirationTime); - scheduledInteractions.forEach(function(interaction) { interaction.__count--; @@ -20941,21 +22298,22 @@ function finishPendingInteractions(root, committedExpirationTime) { var onCommitFiberRoot = null; var onCommitFiberUnmount = null; var hasLoggedError = false; - var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined"; - function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") { // No DevTools return false; } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } + if (!hook.supportsFiber) { { warningWithoutStack$1( @@ -20964,16 +22322,18 @@ function injectInternals(internals) { "with the current version of React. Please update React DevTools. " + "https://fb.me/react-devtools" ); - } - // DevTools exists, even though it doesn't support Fiber. + } // DevTools exists, even though it doesn't support Fiber. + return true; } + try { - var rendererID = hook.inject(internals); - // We have successfully injected, so now it is safe to set up hooks. + var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. + onCommitFiberRoot = function(root, expirationTime) { try { var didError = (root.current.effectTag & DidCapture) === DidCapture; + if (enableProfilerTimer) { var currentTime = requestCurrentTime(); var priorityLevel = inferPriorityFromExpirationTime( @@ -20995,6 +22355,7 @@ function injectInternals(internals) { } } }; + onCommitFiberUnmount = function(fiber) { try { hook.onCommitFiberUnmount(rendererID, fiber); @@ -21018,34 +22379,33 @@ function injectInternals(internals) { err ); } - } - // DevTools exists + } // DevTools exists + return true; } - function onCommitRoot(root, expirationTime) { if (typeof onCommitFiberRoot === "function") { onCommitFiberRoot(root, expirationTime); } } - function onCommitUnmount(fiber) { if (typeof onCommitFiberUnmount === "function") { onCommitFiberUnmount(fiber); } } -var hasBadMapPolyfill = void 0; +var hasBadMapPolyfill; { hasBadMapPolyfill = false; + try { var nonExtensibleObject = Object.preventExtensions({}); var testMap = new Map([[nonExtensibleObject, null]]); - var testSet = new Set([nonExtensibleObject]); - // This is necessary for Rollup to not consider these unused. + var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. + testMap.set(0, 0); testSet.add(0); } catch (e) { @@ -21054,14 +22414,7 @@ var hasBadMapPolyfill = void 0; } } -// A Fiber is work on a Component that needs to be done or was done. There can -// be more than one per component. - -var debugCounter = void 0; - -{ - debugCounter = 1; -} +var debugCounter = 1; function FiberNode(tag, pendingProps, key, mode) { // Instance @@ -21069,34 +22422,26 @@ function FiberNode(tag, pendingProps, key, mode) { this.key = key; this.elementType = null; this.type = null; - this.stateNode = null; + this.stateNode = null; // Fiber - // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; - this.ref = null; - this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; + this.mode = mode; // Effects - this.mode = mode; - - // Effects this.effectTag = NoEffect; this.nextEffect = null; - this.firstEffect = null; this.lastEffect = null; - this.expirationTime = NoWork; this.childExpirationTime = NoWork; - this.alternate = null; if (enableProfilerTimer) { @@ -21115,31 +22460,33 @@ function FiberNode(tag, pendingProps, key, mode) { this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; - this.treeBaseDuration = Number.NaN; - - // It's okay to replace the initial doubles with smis after initialization. + this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). + this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; + } // This is normally DEV-only except www when it adds listeners. + // TODO: remove the User Timing integration in favor of Root Events. + + if (enableUserTimingAPI) { + this._debugID = debugCounter++; + this._debugIsCurrentlyTiming = false; } { - this._debugID = debugCounter++; this._debugSource = null; this._debugOwner = null; - this._debugIsCurrentlyTiming = false; this._debugNeedsRemount = false; this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } } -} - -// This is a constructor function, rather than a POJO constructor, still +} // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost @@ -21152,6 +22499,7 @@ function FiberNode(tag, pendingProps, key, mode) { // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. + var createFiber = function(tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); @@ -21169,25 +22517,27 @@ function isSimpleFunctionComponent(type) { type.defaultProps === undefined ); } - function resolveLazyComponentTag(Component) { if (typeof Component === "function") { return shouldConstruct(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; + if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } + if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } + return IndeterminateComponent; -} +} // This is used to create an alternate fiber to do work on. -// This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps, expirationTime) { var workInProgress = current.alternate; + if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused @@ -21215,13 +22565,11 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.alternate = current; current.alternate = workInProgress; } else { - workInProgress.pendingProps = pendingProps; - - // We already have an alternate. + workInProgress.pendingProps = pendingProps; // We already have an alternate. // Reset the effect tag. - workInProgress.effectTag = NoEffect; - // The effect list is no longer valid. + workInProgress.effectTag = NoEffect; // The effect list is no longer valid. + workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; @@ -21238,14 +22586,12 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21254,9 +22600,8 @@ function createWorkInProgress(current, pendingProps, expirationTime) { expirationTime: currentDependencies.expirationTime, firstContext: currentDependencies.firstContext, responders: currentDependencies.responders - }; + }; // These will be overridden during the parent's reconciliation - // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; @@ -21268,56 +22613,54 @@ function createWorkInProgress(current, pendingProps, expirationTime) { { workInProgress._debugNeedsRemount = current._debugNeedsRemount; + switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; + case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; + case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; + default: break; } } return workInProgress; -} +} // Used to reuse a Fiber for a second pass. -// Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderExpirationTime) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. - // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. - // Reset the effect tag but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. - workInProgress.effectTag &= Placement; + workInProgress.effectTag &= Placement; // The effect list is no longer valid. - // The effect list is no longer valid. workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; - var current = workInProgress.alternate; + if (current === null) { // Reset to createFiber's initial values. workInProgress.childExpirationTime = NoWork; workInProgress.expirationTime = renderExpirationTime; - workInProgress.child = null; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; - workInProgress.dependencies = null; if (enableProfilerTimer) { @@ -21330,14 +22673,12 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; - workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; - workInProgress.updateQueue = current.updateQueue; - - // Clone the dependencies object. This is mutated during the render phase, so + workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. + var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null @@ -21358,9 +22699,9 @@ function resetWorkInProgress(workInProgress, renderExpirationTime) { return workInProgress; } - function createHostRootFiber(tag) { - var mode = void 0; + var mode; + if (tag === ConcurrentRoot) { mode = ConcurrentMode | BatchedMode | StrictMode; } else if (tag === BatchedRoot) { @@ -21378,7 +22719,6 @@ function createHostRootFiber(tag) { return createFiber(HostRoot, null, null, mode); } - function createFiberFromTypeAndProps( type, // React$ElementType key, @@ -21387,14 +22727,15 @@ function createFiberFromTypeAndProps( mode, expirationTime ) { - var fiber = void 0; + var fiber; + var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. - var fiberTag = IndeterminateComponent; - // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; + if (typeof type === "function") { if (shouldConstruct(type)) { fiberTag = ClassComponent; + { resolvedType = resolveClassForHotReloading(resolvedType); } @@ -21414,18 +22755,23 @@ function createFiberFromTypeAndProps( expirationTime, key ); + case REACT_CONCURRENT_MODE_TYPE: fiberTag = Mode; mode |= ConcurrentMode | BatchedMode | StrictMode; break; + case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictMode; break; + case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, expirationTime, key); + case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList( pendingProps, @@ -21433,29 +22779,37 @@ function createFiberFromTypeAndProps( expirationTime, key ); + default: { if (typeof type === "object" && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; + case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; + case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; + { resolvedType = resolveForwardRefForHotReloading(resolvedType); } + break getTag; + case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; + case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_FUNDAMENTAL_TYPE: if (enableFundamentalAPI) { return createFiberFromFundamental( @@ -21466,10 +22820,24 @@ function createFiberFromTypeAndProps( key ); } + break; + + case REACT_SCOPE_TYPE: + if (enableScopeAPI) { + return createFiberFromScope( + type, + pendingProps, + mode, + expirationTime, + key + ); + } } } + var info = ""; + { if ( type === undefined || @@ -21482,23 +22850,22 @@ function createFiberFromTypeAndProps( "it's defined in, or you might have mixed up default and " + "named imports."; } + var ownerName = owner ? getComponentName(owner.type) : null; + if (ownerName) { info += "\n\nCheck the render method of `" + ownerName + "`."; } } - (function() { - { - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (type == null ? type : typeof type) + - "." + - info - ) - ); - } - })(); + + { + 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 + ); + } } } } @@ -21507,15 +22874,15 @@ function createFiberFromTypeAndProps( fiber.elementType = type; fiber.type = resolvedType; fiber.expirationTime = expirationTime; - return fiber; } - function createFiberFromElement(element, mode, expirationTime) { var owner = null; + { owner = element._owner; } + var type = element.type; var key = element.key; var pendingProps = element.props; @@ -21527,19 +22894,19 @@ function createFiberFromElement(element, mode, expirationTime) { mode, expirationTime ); + { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } + return fiber; } - function createFiberFromFragment(elements, mode, expirationTime, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromFundamental( fundamentalComponent, pendingProps, @@ -21554,6 +22921,14 @@ function createFiberFromFundamental( return fiber; } +function createFiberFromScope(scope, pendingProps, mode, expirationTime, key) { + var fiber = createFiber(ScopeComponent, pendingProps, key, mode); + fiber.type = scope; + fiber.elementType = scope; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -21567,76 +22942,74 @@ function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { } } - var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); - // TODO: The Profiler fiber shouldn't have a type. It has a tag. + var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag. + fiber.elementType = REACT_PROFILER_TYPE; fiber.type = REACT_PROFILER_TYPE; fiber.expirationTime = expirationTime; - return fiber; } function createFiberFromSuspense(pendingProps, mode, expirationTime, key) { - var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); - - // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. + var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. + fiber.type = REACT_SUSPENSE_TYPE; fiber.elementType = REACT_SUSPENSE_TYPE; - fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); + { // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag. // This needs to be fixed in getComponentName so that it relies on the tag // instead. fiber.type = REACT_SUSPENSE_LIST_TYPE; } + fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromText(content, mode, expirationTime) { var fiber = createFiber(HostText, content, null, mode); fiber.expirationTime = expirationTime; return fiber; } - function createFiberFromHostInstanceForDeletion() { - var fiber = createFiber(HostComponent, null, null, NoMode); - // TODO: These should not need a type. + var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type. + fiber.elementType = "DELETED"; fiber.type = "DELETED"; return fiber; } - +function createFiberFromDehydratedFragment(dehydratedNode) { + var fiber = createFiber(DehydratedFragment, null, null, NoMode); + fiber.stateNode = dehydratedNode; + return fiber; +} function createFiberFromPortal(portal, mode, expirationTime) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.expirationTime = expirationTime; fiber.stateNode = { containerInfo: portal.containerInfo, - pendingChildren: null, // Used by persistent updates + pendingChildren: null, + // Used by persistent updates implementation: portal.implementation }; return fiber; -} +} // Used for stashing WIP properties to replay failed work in DEV. -// Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); - } - - // This is intentionally written as a list of all properties. + } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 @@ -21665,12 +23038,14 @@ function assignFiberPropertiesInDEV(target, source) { target.expirationTime = source.expirationTime; target.childExpirationTime = source.childExpirationTime; target.alternate = source.alternate; + if (enableProfilerTimer) { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } + target._debugID = source._debugID; target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; @@ -21680,19 +23055,6 @@ function assignFiberPropertiesInDEV(target, source) { return target; } -// TODO: This should be lifted into the renderer. - -// The following attributes are only used by interaction tracing builds. -// They enable interactions to be associated with their async work, -// And expose interaction metadata to the React DevTools Profiler plugin. -// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. - -// Exported FiberRoot type includes all properties, -// To avoid requiring potentially error-prone :any casts throughout the project. -// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true). -// The types are defined separately within this file to ensure they stay in sync. -// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.) - function FiberRootNode(containerInfo, tag, hydrate) { this.tag = tag; this.current = null; @@ -21705,31 +23067,129 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.context = null; this.pendingContext = null; this.hydrate = hydrate; - this.firstBatch = null; this.callbackNode = null; - this.callbackExpirationTime = NoWork; + this.callbackPriority = NoPriority; this.firstPendingTime = NoWork; - this.lastPendingTime = NoWork; - this.pingTime = NoWork; + this.firstSuspendedTime = NoWork; + this.lastSuspendedTime = NoWork; + this.nextKnownPendingLevel = NoWork; + this.lastPingedTime = NoWork; + this.lastExpiredTime = NoWork; if (enableSchedulerTracing) { this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } + + if (enableSuspenseCallback) { + this.hydrationCallbacks = null; + } } -function createFiberRoot(containerInfo, tag, hydrate) { +function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate); - // Cyclic construction. This cheats the type system right now because + if (enableSuspenseCallback) { + root.hydrationCallbacks = hydrationCallbacks; + } // Cyclic construction. This cheats the type system right now because // stateNode is any. + var uninitializedFiber = createHostRootFiber(tag); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - return root; } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + return ( + firstSuspendedTime !== NoWork && + firstSuspendedTime >= expirationTime && + lastSuspendedTime <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + var lastSuspendedTime = root.lastSuspendedTime; + + if (firstSuspendedTime < expirationTime) { + root.firstSuspendedTime = expirationTime; + } + + if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) { + root.lastSuspendedTime = expirationTime; + } + + if (expirationTime <= root.lastPingedTime) { + root.lastPingedTime = NoWork; + } + + if (expirationTime <= root.lastExpiredTime) { + root.lastExpiredTime = NoWork; + } +} +function markRootUpdatedAtTime(root, expirationTime) { + // Update the range of pending times + var firstPendingTime = root.firstPendingTime; + + if (expirationTime > firstPendingTime) { + root.firstPendingTime = expirationTime; + } // Update the range of suspended times. Treat everything lower priority or + // equal to this update as unsuspended. + + var firstSuspendedTime = root.firstSuspendedTime; + + if (firstSuspendedTime !== NoWork) { + if (expirationTime >= firstSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (expirationTime >= root.lastSuspendedTime) { + root.lastSuspendedTime = expirationTime + 1; + } // This is a pending level. Check if it's higher priority than the next + // known pending level. + + if (expirationTime > root.nextKnownPendingLevel) { + root.nextKnownPendingLevel = expirationTime; + } + } +} +function markRootFinishedAtTime( + root, + finishedExpirationTime, + remainingExpirationTime +) { + // Update the range of pending times + root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or + // equal to this update as unsuspended. + + if (finishedExpirationTime <= root.lastSuspendedTime) { + // The entire suspended range is now unsuspended. + root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork; + } else if (finishedExpirationTime <= root.firstSuspendedTime) { + // Part of the suspended range is now unsuspended. Narrow the range to + // include everything between the unsuspended time (non-inclusive) and the + // last suspended time. + root.firstSuspendedTime = finishedExpirationTime - 1; + } + + if (finishedExpirationTime <= root.lastPingedTime) { + // Clear the pinged time + root.lastPingedTime = NoWork; + } + + if (finishedExpirationTime <= root.lastExpiredTime) { + // Clear the expired time + root.lastExpiredTime = NoWork; + } +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + + if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) { + root.lastExpiredTime = expirationTime; + } +} // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. @@ -21738,14 +23198,10 @@ function createFiberRoot(containerInfo, tag, hydrate) { var ReactFiberInstrumentation = { debugTool: null }; - var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; -// 0 is PROD, 1 is DEV. -// Might add PROFILE later. - -var didWarnAboutNestedUpdates = void 0; -var didWarnAboutFindNodeInStrictMode = void 0; +var didWarnAboutNestedUpdates; +var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; @@ -21762,6 +23218,7 @@ function getContextForSubtree(parentComponent) { if (fiber.tag === ClassComponent) { var Component = fiber.type; + if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } @@ -21770,166 +23227,72 @@ function getContextForSubtree(parentComponent) { return parentContext; } -function scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback -) { - { - if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { - didWarnAboutNestedUpdates = true; - 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" - ); +function findHostInstance(component) { + var fiber = get(component); + + if (fiber === undefined) { + if (typeof component.render === "function") { + { + throw Error("Unable to find node on an unmounted component."); + } + } else { + { + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } } } - var update = createUpdate(expirationTime, suspenseConfig); - // Caution: React DevTools currently depends on this property - // being called "element". - update.payload = { element: element }; - - callback = callback === undefined ? null : callback; - if (callback !== null) { - !(typeof callback === "function") - ? warningWithoutStack$1( - false, - "render(...): Expected the last optional `callback` argument to be a " + - "function. Instead received: %s.", - callback - ) - : void 0; - update.callback = callback; - } + var hostFiber = findCurrentHostFiber(fiber); - if (revertPassiveEffectsChange) { - flushPassiveEffects(); + if (hostFiber === null) { + return null; } - enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); - return expirationTime; + return hostFiber.stateNode; } -function updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback -) { - // TODO: If this is a nested container, this won't be the root. - var current$$1 = container.current; - +function findHostInstanceWithWarning(component, methodName) { { - if (ReactFiberInstrumentation_1.debugTool) { - if (current$$1.alternate === null) { - ReactFiberInstrumentation_1.debugTool.onMountContainer(container); - } else if (element === null) { - ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); - } else { - ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); - } - } - } - - var context = getContextForSubtree(parentComponent); - if (container.context === null) { - container.context = context; - } else { - container.pendingContext = context; - } - - return scheduleRootUpdate( - current$$1, - element, - expirationTime, - suspenseConfig, - callback - ); -} + var fiber = get(component); -function findHostInstance(component) { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { + if (fiber === undefined) { + if (typeof component.render === "function") { { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); + throw Error("Unable to find node on an unmounted component."); } - })(); - } else { - (function() { + } else { { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } - })(); - } - } - var hostFiber = findCurrentHostFiber(fiber); - if (hostFiber === null) { - return null; - } - return hostFiber.stateNode; -} - -function findHostInstanceWithWarning(component, methodName) { - { - var fiber = get(component); - if (fiber === undefined) { - if (typeof component.render === "function") { - (function() { - { - throw ReactError( - Error("Unable to find node on an unmounted component.") - ); - } - })(); - } else { - (function() { - { - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) - ); - } - })(); } } + var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + if (hostFiber.mode & StrictMode) { var componentName = getComponentName(fiber.type) || "Component"; + if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; + if (fiber.mode & StrictMode) { warningWithoutStack$1( false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which is inside StrictMode. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -21940,10 +23303,9 @@ function findHostInstanceWithWarning(component, methodName) { false, "%s is deprecated in StrictMode. " + "%s was passed an instance of %s which renders StrictMode children. " + - "Instead, add a ref directly to the element you want to reference." + - "\n%s" + - "\n\nLearn more about using refs safely here:" + - "\nhttps://fb.me/react-strict-mode-find-node", + "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, @@ -21952,18 +23314,20 @@ function findHostInstanceWithWarning(component, methodName) { } } } + return hostFiber.stateNode; } + return findHostInstance(component); } -function createContainer(containerInfo, tag, hydrate) { - return createFiberRoot(containerInfo, tag, hydrate); +function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) { + return createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks); } - function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; var currentTime = requestCurrentTime(); + { // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests if ("undefined" !== typeof jest) { @@ -21971,30 +23335,83 @@ function updateContainer(element, container, parentComponent, callback) { warnIfNotScopedWithMatchingAct(current$$1); } } + var suspenseConfig = requestCurrentSuspenseConfig(); var expirationTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - return updateContainerAtExpirationTime( - element, - container, - parentComponent, - expirationTime, - suspenseConfig, - callback - ); -} + { + if (ReactFiberInstrumentation_1.debugTool) { + if (current$$1.alternate === null) { + ReactFiberInstrumentation_1.debugTool.onMountContainer(container); + } else if (element === null) { + ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); + } else { + ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); + } + } + } + + var context = getContextForSubtree(parentComponent); + + if (container.context === null) { + container.context = context; + } else { + container.pendingContext = context; + } + + { + if (phase === "render" && current !== null && !didWarnAboutNestedUpdates) { + didWarnAboutNestedUpdates = true; + 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" + ); + } + } + + var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property + // being called "element". + + update.payload = { + element: element + }; + callback = callback === undefined ? null : callback; + + if (callback !== null) { + !(typeof callback === "function") + ? warningWithoutStack$1( + false, + "render(...): Expected the last optional `callback` argument to be a " + + "function. Instead received: %s.", + callback + ) + : void 0; + update.callback = callback; + } + + enqueueUpdate(current$$1, update); + scheduleWork(current$$1, expirationTime); + return expirationTime; +} function getPublicRootInstance(container) { var containerFiber = container.current; + if (!containerFiber.child) { return null; } + switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); + default: return containerFiber.child.stateNode; } @@ -22007,7 +23424,6 @@ var shouldSuspendImpl = function(fiber) { function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } - var overrideHookState = null; var overrideProps = null; var scheduleUpdate = null; @@ -22018,62 +23434,53 @@ var setSuspenseHandler = null; if (idx >= path.length) { return value; } + var key = path[idx]; - var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); - // $FlowFixMe number or string is fine here + var updated = Array.isArray(obj) ? obj.slice() : Object.assign({}, obj); // $FlowFixMe number or string is fine here + updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); return updated; }; var copyWithSet = function(obj, path, value) { return copyWithSetImpl(obj, path, 0, value); - }; + }; // Support DevTools editable values for useState and useReducer. - // Support DevTools editable values for useState and useReducer. overrideHookState = function(fiber, id, path, value) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; + while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } - if (currentHook !== null) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } + if (currentHook !== null) { var newState = copyWithSet(currentHook.memoizedState, path, value); currentHook.memoizedState = newState; - currentHook.baseState = newState; - - // We aren't actually adding an update to the queue, + currentHook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. - fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); + fiber.memoizedProps = Object.assign({}, fiber.memoizedProps); scheduleWork(fiber, Sync); } - }; + }; // Support DevTools props for function components, forwardRef, memo, host components, etc. - // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } + scheduleWork(fiber, Sync); }; scheduleUpdate = function(fiber) { - if (revertPassiveEffectsChange) { - flushPassiveEffects(); - } scheduleWork(fiber, Sync); }; @@ -22085,7 +23492,6 @@ var setSuspenseHandler = null; function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - return injectInternals( Object.assign({}, devToolsConfig, { overrideHookState: overrideHookState, @@ -22095,9 +23501,11 @@ function injectIntoDevTools(devToolsConfig) { currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); + if (hostFiber === null) { return null; } + return hostFiber.stateNode; }, findFiberByHostInstance: function(instance) { @@ -22105,9 +23513,9 @@ function injectIntoDevTools(devToolsConfig) { // Might not be implemented by the renderer. return null; } + return findFiberByHostInstance(instance); }, - // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh, scheduleRefresh: scheduleRefresh, @@ -22126,13 +23534,11 @@ function injectIntoDevTools(devToolsConfig) { function createPortal( children, - containerInfo, - // TODO: figure out the API for cross-renderer implementation. + containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation ) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, @@ -22143,404 +23549,31 @@ function createPortal( }; } -// TODO: this is special because it gets imported during build. - -var ReactVersion = "16.8.6"; - -// Modules provided by RN: -var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { - /** - * `NativeMethodsMixin` provides methods to access the underlying native - * component directly. This can be useful in cases when you want to focus - * a view or measure its on-screen dimensions, for example. - * - * The methods described here are available on most of the default components - * provided by React Native. Note, however, that they are *not* available on - * composite components that aren't directly backed by a native view. This will - * generally include most components that you define in your own app. For more - * information, see [Direct - * Manipulation](docs/direct-manipulation.html). - * - * Note the Flow $Exact<> syntax is required to support mixins. - * React createClass mixins can only be used with exact types. - */ - var NativeMethodsMixin = { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measure( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow: function(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - // We can't call FabricUIManager here because it won't be loaded in paper - // at initialization time. See https://github.com/facebook/react/pull/15490 - // for more info. - nativeFabricUIManager.measureInWindow( - maybeInstance.node, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } else { - ReactNativePrivateInterface.UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - } - }, - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeNode`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * - * As always, to obtain a native node handle for a component, you can use - * `findNodeHandle(component)`. - */ - measureLayout: function( - relativeToNativeNode, - onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: measureLayout on components using NativeMethodsMixin " + - "or ReactNative.NativeComponent is not currently supported in Fabric. " + - "measureLayout must be called on a native ref. Consider using forwardRef." - ); - return; - } else { - var relativeNode = void 0; - - if (typeof relativeToNativeNode === "number") { - // Already a node handle - relativeNode = relativeToNativeNode; - } else if (relativeToNativeNode._nativeTag) { - relativeNode = relativeToNativeNode._nativeTag; - } - - if (relativeNode == null) { - warningWithoutStack$1( - false, - "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." - ); - - return; - } - - ReactNativePrivateInterface.UIManager.measureLayout( - findNodeHandle(this), - relativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - } - }, - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](docs/direct-manipulation.html)). - */ - setNativeProps: function(nativeProps) { - // Class components don't have viewConfig -> validateAttributes. - // Nor does it make sense to set native props on a non-native component. - // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than findNodeHandle() because - // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. - // Tests using ReactTestRenderer will trigger this case indirectly. - // Mimicking stack behavior, we should silently ignore this case. - // TODO Fix ReactTestRenderer so we can remove this try/catch. - try { - maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. - // This is not an error; it could mean a class component rendered null. - if (maybeInstance == null) { - return; - } - - if (maybeInstance.canonical) { - warningWithoutStack$1( - false, - "Warning: setNativeProps is not currently supported in Fabric" - ); - return; - } - - var nativeTag = - maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; - var viewConfig = - maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - - { - warnForStyleProps(nativeProps, viewConfig.validAttributes); - } - - var updatePayload = create(nativeProps, viewConfig.validAttributes); - - // Avoid the overhead of bridge calls if there's no update. - // This is an expensive no-op for Android, and causes an unnecessary - // view invalidation for certain components (eg RCTTextInput) on iOS. - if (updatePayload != null) { - ReactNativePrivateInterface.UIManager.updateView( - nativeTag, - viewConfig.uiViewClassName, - updatePayload - ); - } - }, - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus: function() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }, - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur: function() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - } - }; - - { - // hide this from Flow since we can't define these properties outside of - // true without actually implementing them (setting them to undefined - // isn't allowed by ReactClass) - var NativeMethodsMixin_DEV = NativeMethodsMixin; - (function() { - if ( - !( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps - ) - ) { - throw ReactError(Error("Do not override existing functions.")); - } - })(); - // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, - // Once these lifecycles have been remove from the reconciler. - NativeMethodsMixin_DEV.componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { - throwOnStylesProp(this, newProps); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { - throwOnStylesProp(this, this.props); - }; - NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( - newProps - ) { - throwOnStylesProp(this, newProps); - }; - - // React may warn about cWM/cWRP/cWU methods being deprecated. - // Add a flag to suppress these warnings for this special case. - // TODO (bvaughn) Remove this flag once the above methods have been removed. - NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; - NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; - } - - return NativeMethodsMixin; -}; - -function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _possibleConstructorReturn(self, call) { - if (!self) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return call && (typeof call === "object" || typeof call === "function") - ? call - : self; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) - Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass); -} - -// Modules provided by RN: -var ReactNativeComponent = function(findNodeHandle, findHostInstance) { - /** - * Superclass that provides methods to access the underlying native component. - * This can be useful when you want to focus a view or measure its dimensions. - * - * Methods implemented by this class are available on most default components - * provided by React Native. However, they are *not* available on composite - * components that are not directly backed by a native view. For more - * information, see [Direct Manipulation](docs/direct-manipulation.html). - * - * @abstract - */ - var ReactNativeComponent = (function(_React$Component) { - _inherits(ReactNativeComponent, _React$Component); - - function ReactNativeComponent() { - _classCallCheck$1(this, ReactNativeComponent); - - return _possibleConstructorReturn( - this, - _React$Component.apply(this, arguments) - ); - } - - /** - * Removes focus. This is the opposite of `focus()`. - */ - - /** - * Due to bugs in Flow's handling of React.createClass, some fields already - * declared in the base class need to be redeclared below. - */ - ReactNativeComponent.prototype.blur = function blur() { - ReactNativePrivateInterface.TextInputState.blurTextInput( - findNodeHandle(this) - ); - }; - - /** - * Requests focus. The exact behavior depends on the platform and view. - */ - - ReactNativeComponent.prototype.focus = function focus() { - ReactNativePrivateInterface.TextInputState.focusTextInput( - findNodeHandle(this) - ); - }; - +// TODO: this is special because it gets imported during build. + +var ReactVersion = "16.10.2"; + +var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { + /** + * `NativeMethodsMixin` provides methods to access the underlying native + * component directly. This can be useful in cases when you want to focus + * a view or measure its on-screen dimensions, for example. + * + * The methods described here are available on most of the default components + * provided by React Native. Note, however, that they are *not* available on + * composite components that aren't directly backed by a native view. This will + * generally include most components that you define in your own app. For more + * information, see [Direct + * Manipulation](docs/direct-manipulation.html). + * + * Note the Flow $Exact<> syntax is required to support mixins. + * React createClass mixins can only be used with exact types. + */ + var NativeMethodsMixin = { /** - * Measures the on-screen location and dimensions. If successful, the callback - * will be called asynchronously with the following arguments: + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: * * - x * - y @@ -22549,24 +23582,22 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * - pageX * - pageY * - * These values are not available until after natives rendering completes. If - * you need the measurements as soon as possible, consider using the - * [`onLayout` prop](docs/view.html#onlayout) instead. + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. */ - - ReactNativeComponent.prototype.measure = function measure(callback) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measure: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22585,37 +23616,34 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Measures the on-screen location and dimensions. Even if the React Native - * root view is embedded within another native view, this method will give you - * the absolute coordinates measured from the window. If successful, the - * callback will be called asynchronously with the following arguments: + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: * * - x * - y * - width * - height * - * These values are not available until after natives rendering completes. + * Note that these measurements are not available until after the rendering + * has been completed in native. */ - - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( - callback - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + measureInWindow: function(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22634,32 +23662,32 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); } - }; + }, /** - * Similar to [`measure()`](#measure), but the resulting location will be - * relative to the supplied ancestor's location. + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeNode`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. * - * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + * As always, to obtain a native node handle for a component, you can use + * `findNodeHandle(component)`. */ - - ReactNativeComponent.prototype.measureLayout = function measureLayout( + measureLayout: function( relativeToNativeNode, onSuccess, - onFail /* currently unused */ - ) { - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + onFail + ) /* currently unused */ + { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22673,7 +23701,7 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { ); return; } else { - var relativeNode = void 0; + var relativeNode; if (typeof relativeToNativeNode === "number") { // Already a node handle @@ -22687,7 +23715,6 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { false, "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." ); - return; } @@ -22698,7 +23725,7 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); } - }; + }, /** * This function sends props straight to native. They will not participate in @@ -22706,27 +23733,22 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ - - ReactNativeComponent.prototype.setNativeProps = function setNativeProps( - nativeProps - ) { + setNativeProps: function(nativeProps) { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. - // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // Use findNodeHandle() rather than findNodeHandle() because // We want the instance/wrapper (not the native tag). - var maybeInstance = void 0; - - // Fiber errors if findNodeHandle is called for an umounted component. + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. + try { maybeInstance = findHostInstance(this); - } catch (error) {} - - // If there is no host component beneath this we should fail silently. + } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. + if (maybeInstance == null) { return; } @@ -22744,11 +23766,14 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { var viewConfig = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; - var updatePayload = create(nativeProps, viewConfig.validAttributes); + { + warnForStyleProps(nativeProps, viewConfig.validAttributes); + } - // Avoid the overhead of bridge calls if there's no update. + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. + if (updatePayload != null) { ReactNativePrivateInterface.UIManager.updateView( nativeTag, @@ -22756,23 +23781,339 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { updatePayload ); } + }, + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus: function() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }, + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur: function() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + } + }; + + { + // hide this from Flow since we can't define these properties outside of + // true without actually implementing them (setting them to undefined + // isn't allowed by ReactClass) + var NativeMethodsMixin_DEV = NativeMethodsMixin; + + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw Error("Do not override existing functions."); + } // TODO (bvaughn) Remove cWM and cWRP in a future version of React Native, + // Once these lifecycles have been remove from the reconciler. + + NativeMethodsMixin_DEV.componentWillMount = function() { + throwOnStylesProp(this, this.props); + }; + + NativeMethodsMixin_DEV.componentWillReceiveProps = function(newProps) { + throwOnStylesProp(this, newProps); + }; + + NativeMethodsMixin_DEV.UNSAFE_componentWillMount = function() { + throwOnStylesProp(this, this.props); }; - return ReactNativeComponent; - })(React.Component); + NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps = function( + newProps + ) { + throwOnStylesProp(this, newProps); + }; // React may warn about cWM/cWRP/cWU methods being deprecated. + // Add a flag to suppress these warnings for this special case. + // TODO (bvaughn) Remove this flag once the above methods have been removed. + + NativeMethodsMixin_DEV.componentWillMount.__suppressDeprecationWarning = true; + NativeMethodsMixin_DEV.componentWillReceiveProps.__suppressDeprecationWarning = true; + } + + return NativeMethodsMixin; +}; + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} + +var ReactNativeComponent = function(findNodeHandle, findHostInstance) { + /** + * Superclass that provides methods to access the underlying native component. + * This can be useful when you want to focus a view or measure its dimensions. + * + * Methods implemented by this class are available on most default components + * provided by React Native. However, they are *not* available on composite + * components that are not directly backed by a native view. For more + * information, see [Direct Manipulation](docs/direct-manipulation.html). + * + * @abstract + */ + var ReactNativeComponent = + /*#__PURE__*/ + (function(_React$Component) { + _inheritsLoose(ReactNativeComponent, _React$Component); + + function ReactNativeComponent() { + return _React$Component.apply(this, arguments) || this; + } + + var _proto = ReactNativeComponent.prototype; + + /** + * Due to bugs in Flow's handling of React.createClass, some fields already + * declared in the base class need to be redeclared below. + */ + + /** + * Removes focus. This is the opposite of `focus()`. + */ + _proto.blur = function blur() { + ReactNativePrivateInterface.TextInputState.blurTextInput( + findNodeHandle(this) + ); + }; + /** + * Requests focus. The exact behavior depends on the platform and view. + */ + + _proto.focus = function focus() { + ReactNativePrivateInterface.TextInputState.focusTextInput( + findNodeHandle(this) + ); + }; + /** + * Measures the on-screen location and dimensions. If successful, the callback + * will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * These values are not available until after natives rendering completes. If + * you need the measurements as soon as possible, consider using the + * [`onLayout` prop](docs/view.html#onlayout) instead. + */ + + _proto.measure = function measure(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Measures the on-screen location and dimensions. Even if the React Native + * root view is embedded within another native view, this method will give you + * the absolute coordinates measured from the window. If successful, the + * callback will be called asynchronously with the following arguments: + * + * - x + * - y + * - width + * - height + * + * These values are not available until after natives rendering completes. + */ + + _proto.measureInWindow = function measureInWindow(callback) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + // We can't call FabricUIManager here because it won't be loaded in paper + // at initialization time. See https://github.com/facebook/react/pull/15490 + // for more info. + nativeFabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + ReactNativePrivateInterface.UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } + }; + /** + * Similar to [`measure()`](#measure), but the resulting location will be + * relative to the supplied ancestor's location. + * + * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. + */ + + _proto.measureLayout = function measureLayout( + relativeToNativeNode, + onSuccess, + onFail + ) { + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: measureLayout on components using NativeMethodsMixin " + + "or ReactNative.NativeComponent is not currently supported in Fabric. " + + "measureLayout must be called on a native ref. Consider using forwardRef." + ); + return; + } else { + var relativeNode; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } + + if (relativeNode == null) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a node handle or a ref to a native component." + ); + return; + } + + ReactNativePrivateInterface.UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } + }; + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](docs/direct-manipulation.html)). + */ + + _proto.setNativeProps = function setNativeProps(nativeProps) { + // Class components don't have viewConfig -> validateAttributes. + // Nor does it make sense to set native props on a non-native component. + // Instead, find the nearest host component and set props on it. + // Use findNodeHandle() rather than ReactNative.findNodeHandle() because + // We want the instance/wrapper (not the native tag). + var maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. + // Tests using ReactTestRenderer will trigger this case indirectly. + // Mimicking stack behavior, we should silently ignore this case. + // TODO Fix ReactTestRenderer so we can remove this try/catch. + + try { + maybeInstance = findHostInstance(this); + } catch (error) {} // If there is no host component beneath this we should fail silently. + // This is not an error; it could mean a class component rendered null. + + if (maybeInstance == null) { + return; + } + + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + var nativeTag = + maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; + var viewConfig = + maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; + var updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. + // This is an expensive no-op for Android, and causes an unnecessary + // view invalidation for certain components (eg RCTTextInput) on iOS. + + if (updatePayload != null) { + ReactNativePrivateInterface.UIManager.updateView( + nativeTag, + viewConfig.uiViewClassName, + updatePayload + ); + } + }; - // eslint-disable-next-line no-unused-expressions + return ReactNativeComponent; + })(React.Component); // eslint-disable-next-line no-unused-expressions return ReactNativeComponent; }; -// Module provided by RN: var emptyObject$2 = {}; + { Object.freeze(emptyObject$2); } -var getInspectorDataForViewTag = void 0; +var getInspectorDataForViewTag; { var traverseOwnerTreeUp = function(hierarchy, instance) { @@ -22796,30 +24137,36 @@ var getInspectorDataForViewTag = void 0; return instance; } } + return hierarchy[0]; }; var getHostProps = function(fiber) { var host = findCurrentHostFiber(fiber); + if (host) { return host.memoizedProps || emptyObject$2; } + return emptyObject$2; }; var getHostNode = function(fiber, findNodeHandle) { - var hostNode = void 0; - // look for children first for the hostNode + var hostNode; // look for children first for the hostNode // as composite fibers do not have a hostNode + while (fiber) { if (fiber.stateNode !== null && fiber.tag === HostComponent) { hostNode = findNodeHandle(fiber.stateNode); } + if (hostNode) { return hostNode; } + fiber = fiber.child; } + return null; }; @@ -22844,9 +24191,8 @@ var getInspectorDataForViewTag = void 0; }; getInspectorDataForViewTag = function(viewTag) { - var closestInstance = getInstanceFromTag(viewTag); + var closestInstance = getInstanceFromTag(viewTag); // Handle case where user clicks outside of ReactNative - // Handle case where user clicks outside of ReactNative if (!closestInstance) { return { hierarchy: [], @@ -22863,7 +24209,6 @@ var getInspectorDataForViewTag = void 0; var props = getHostProps(instance); var source = instance._debugSource; var selection = fiberHierarchy.indexOf(instance); - return { hierarchy: hierarchy, props: props, @@ -22873,13 +24218,12 @@ var getInspectorDataForViewTag = void 0; }; } -// TODO: direct imports like some-package/src/* are bad. Fix me. -// Module provided by RN: var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function findNodeHandle(componentOrHandle) { { var owner = ReactCurrentOwner.current; + if (owner !== null && owner.stateNode !== null) { !owner.stateNode._warnedAboutRefsInRender ? warningWithoutStack$1( @@ -22892,24 +24236,29 @@ function findNodeHandle(componentOrHandle) { getComponentName(owner.type) || "A component" ) : void 0; - owner.stateNode._warnedAboutRefsInRender = true; } } + if (componentOrHandle == null) { return null; } + if (typeof componentOrHandle === "number") { // Already a node handle return componentOrHandle; } + if (componentOrHandle._nativeTag) { return componentOrHandle._nativeTag; } + if (componentOrHandle.canonical && componentOrHandle.canonical._nativeTag) { return componentOrHandle.canonical._nativeTag; } - var hostInstance = void 0; + + var hostInstance; + { hostInstance = findHostInstanceWithWarning( componentOrHandle, @@ -22920,10 +24269,12 @@ function findNodeHandle(componentOrHandle) { if (hostInstance == null) { return hostInstance; } + if (hostInstance.canonical) { // Fabric return hostInstance.canonical._nativeTag; } + return hostInstance._nativeTag; } @@ -22936,19 +24287,18 @@ setBatchingImplementation( function computeComponentStackForErrorReporting(reactTag) { var fiber = getInstanceFromTag(reactTag); + if (!fiber) { return ""; } + return getStackByFiberInDevAndProd(fiber); } var roots = new Map(); - var ReactNativeRenderer = { NativeComponent: ReactNativeComponent(findNodeHandle, findHostInstance), - findNodeHandle: findNodeHandle, - dispatchCommand: function(handle, command, args) { if (handle._nativeTag == null) { !(handle._nativeTag != null) @@ -22973,15 +24323,16 @@ var ReactNativeRenderer = { if (!root) { // TODO (bvaughn): If we decide to keep the wrapper component, // We could create a wrapper for containerTag as well to reduce special casing. - root = createContainer(containerTag, LegacyRoot, false); + root = createContainer(containerTag, LegacyRoot, false, null); roots.set(containerTag, root); } - updateContainer(element, root, null, callback); + updateContainer(element, root, null, callback); return getPublicRootInstance(root); }, unmountComponentAtNode: function(containerTag) { var root = roots.get(containerTag); + if (root) { // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? updateContainer(null, root, null, function() { @@ -22990,27 +24341,22 @@ var ReactNativeRenderer = { } }, unmountComponentAtNodeAndRemoveContainer: function(containerTag) { - ReactNativeRenderer.unmountComponentAtNode(containerTag); + ReactNativeRenderer.unmountComponentAtNode(containerTag); // Call back into native to remove all of the subviews from this container - // Call back into native to remove all of the subviews from this container ReactNativePrivateInterface.UIManager.removeRootView(containerTag); }, createPortal: function(children, containerTag) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - return createPortal(children, containerTag, null, key); }, - unstable_batchedUpdates: batchedUpdates, - __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // Used as a mixin in many createClass-based components NativeMethodsMixin: NativeMethodsMixin(findNodeHandle, findHostInstance), computeComponentStackForErrorReporting: computeComponentStackForErrorReporting } }; - injectIntoDevTools({ findFiberByHostInstance: getInstanceFromTag, getInspectorDataForViewTag: getInspectorDataForViewTag, @@ -23028,6 +24374,7 @@ var ReactNativeRenderer$3 = // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. + var reactNativeRenderer = ReactNativeRenderer$3.default || ReactNativeRenderer$3; diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-prod.fb.js b/Libraries/Renderer/implementations/ReactNativeRenderer-prod.fb.js index 0ad8d7f5ca9b67..afcbae2cadfc84 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-prod.fb.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-prod.fb.js @@ -14,10 +14,6 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} var eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { @@ -26,21 +22,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -50,12 +42,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -80,14 +70,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -95,12 +83,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -148,10 +134,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -169,7 +153,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -181,10 +165,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -220,10 +202,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -239,12 +219,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -285,14 +263,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -455,10 +431,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -494,8 +468,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -609,8 +582,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -710,7 +683,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -723,7 +696,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -732,9 +705,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -743,194 +716,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -938,7 +919,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -952,9 +933,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -987,10 +971,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1016,10 +998,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } require("../shims/ReactFeatureFlags"); @@ -1064,7 +1044,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1075,10 +1056,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1132,7 +1111,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - if (!tag) throw ReactError(Error("All native instances should have a tag.")); + if (!tag) throw Error("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1171,6 +1150,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1179,6 +1159,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1218,27 +1218,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1258,7 +1262,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1294,22 +1298,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1559,43 +1559,35 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { } var ReactNativeFiberHostComponent = (function() { function ReactNativeFiberHostComponent(tag, viewConfig) { - if (!(this instanceof ReactNativeFiberHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this._children = []; this.viewConfig = viewConfig; } - ReactNativeFiberHostComponent.prototype.blur = function() { + var _proto = ReactNativeFiberHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { ReactNativePrivateInterface.UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { ReactNativePrivateInterface.UIManager.measureInWindow( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { - var relativeNode = void 0; - "number" === typeof relativeToNativeNode - ? (relativeNode = relativeToNativeNode) - : relativeToNativeNode._nativeTag - ? (relativeNode = relativeToNativeNode._nativeTag) - : relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag && - (relativeNode = relativeToNativeNode.canonical._nativeTag); + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, @@ -1604,9 +1596,7 @@ var ReactNativeFiberHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { + _proto.setNativeProps = function(nativeProps) { nativeProps = diffProperties( null, emptyObject, @@ -1623,10 +1613,8 @@ var ReactNativeFiberHostComponent = (function() { return ReactNativeFiberHostComponent; })(); function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var getViewConfigForType = @@ -1747,10 +1735,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1762,15 +1748,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1789,10 +1773,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1842,7 +1824,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1858,7 +1840,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority(reactPriorityLevel, fn) { @@ -1880,8 +1862,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1910,25 +1895,13 @@ function flushSyncCallbackQueueImpl() { } } } -function inferPriorityFromExpirationTime(currentTime, expirationTime) { - if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; - currentTime = - 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); - return 0 >= currentTime - ? 99 - : 250 >= currentTime - ? 98 - : 5250 >= currentTime - ? 97 - : 95; -} function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1942,7 +1915,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1957,41 +1930,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2047,10 +1985,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2170,7 +2106,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2265,6 +2201,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2281,18 +2218,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2320,7 +2254,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2485,23 +2419,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2520,32 +2449,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2947,14 +2870,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3046,7 +2967,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3071,10 +2992,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3110,7 +3035,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3130,10 +3055,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3188,11 +3114,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3206,10 +3130,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3247,14 +3169,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3275,15 +3200,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3298,16 +3215,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3350,10 +3265,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3389,9 +3302,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3415,10 +3326,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3432,7 +3341,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3460,7 +3369,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3474,7 +3384,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3514,7 +3424,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3542,10 +3452,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3573,28 +3481,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3602,10 +3506,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3637,19 +3541,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3717,19 +3621,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3784,7 +3688,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3804,7 +3708,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4294,7 +4198,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4303,116 +4207,37 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; - if (0 === (workInProgress.mode & 2)) - for ( - nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); - renderExpirationTime = createFiberFromFragment( - nextProps, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime - ); - else { - if (null !== current$$1.memoizedState) - if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { nextDidTimeout = nextProps.fallback; nextProps = createFiberFromFragment(null, mode, 0, null); nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); if (0 === (workInProgress.mode & 2)) for ( - suspenseContext = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + nextProps.child = current$$1; + null !== current$$1; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( nextDidTimeout, mode, @@ -4421,28 +4246,118 @@ function updateSuspenseComponent( ); renderExpirationTime.return = workInProgress; nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - workInProgress.stateNode = current$$1.stateNode; + renderExpirationTime.return = workInProgress; + if ( + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) + for ( + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; + + ) + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4452,14 +4367,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4476,24 +4393,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4510,7 +4420,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4519,9 +4429,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4535,33 +4445,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4575,9 +4494,11 @@ function bailoutOnAlreadyFinishedWork( ) { null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4602,10 +4523,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function(parent, workInProgress) { for (var node = workInProgress.child; null !== node; ) { if (5 === node.tag || 6 === node.tag) parent._children.push(node.stateNode); @@ -4662,8 +4583,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -4671,12 +4592,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -4684,13 +4603,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -4712,8 +4629,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -4721,7 +4638,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -4771,24 +4688,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -4796,12 +4746,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -4835,7 +4785,11 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { safelyDetachRef(current$$1$jscomp$0); break; case 4: - unmountHostComponents(current$$1$jscomp$0, renderPriorityLevel); + unmountHostComponents( + finishedRoot, + current$$1$jscomp$0, + renderPriorityLevel + ); } } function detachFiber(current$$1) { @@ -4864,10 +4818,8 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); } parent = parentFiber.stateNode; @@ -4884,10 +4836,8 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } parentFiber.effectTag & 16 && (parentFiber.effectTag &= -17); @@ -4923,9 +4873,7 @@ function commitPlacement(finishedWork) { if (parentFiber) if (isContainer) { if ("number" === typeof parent) - throw ReactError( - Error("Container does not support insertBefore operation") - ); + throw Error("Container does not support insertBefore operation"); } else { isHost = parent; var beforeChild = parentFiber, @@ -5002,12 +4950,16 @@ function commitPlacement(finishedWork) { node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { +function unmountHostComponents( + finishedRoot$jscomp$0, + current$$1, + renderPriorityLevel$jscomp$0 +) { for ( var node = current$$1, currentParentIsValid = !1, - currentParent = void 0, - currentParentIsContainer = void 0; + currentParent, + currentParentIsContainer; ; ) { @@ -5015,10 +4967,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { currentParentIsValid = node.return; a: for (;;) { if (null === currentParentIsValid) - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); currentParent = currentParentIsValid.stateNode; switch (currentParentIsValid.tag) { @@ -5040,14 +4990,15 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { } if (5 === node.tag || 6 === node.tag) { a: for ( - var root = node, + var finishedRoot = finishedRoot$jscomp$0, + root = node, renderPriorityLevel = renderPriorityLevel$jscomp$0, node$jscomp$0 = root; ; ) if ( - (commitUnmount(node$jscomp$0, renderPriorityLevel), + (commitUnmount(finishedRoot, node$jscomp$0, renderPriorityLevel), null !== node$jscomp$0.child && 4 !== node$jscomp$0.tag) ) (node$jscomp$0.child.return = node$jscomp$0), @@ -5063,29 +5014,29 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { node$jscomp$0 = node$jscomp$0.sibling; } currentParentIsContainer - ? ((root = currentParent), + ? ((finishedRoot = currentParent), recursivelyUncacheFiberNode(node.stateNode), ReactNativePrivateInterface.UIManager.manageChildren( - root, + finishedRoot, [], [], [], [], [0] )) - : ((root = currentParent), - (node$jscomp$0 = node.stateNode), - recursivelyUncacheFiberNode(node$jscomp$0), - (renderPriorityLevel = root._children), - (node$jscomp$0 = renderPriorityLevel.indexOf(node$jscomp$0)), - renderPriorityLevel.splice(node$jscomp$0, 1), + : ((finishedRoot = currentParent), + (renderPriorityLevel = node.stateNode), + recursivelyUncacheFiberNode(renderPriorityLevel), + (root = finishedRoot._children), + (renderPriorityLevel = root.indexOf(renderPriorityLevel)), + root.splice(renderPriorityLevel, 1), ReactNativePrivateInterface.UIManager.manageChildren( - root._nativeTag, + finishedRoot._nativeTag, [], [], [], [], - [node$jscomp$0] + [renderPriorityLevel] )); } else if (4 === node.tag) { if (null !== node.child) { @@ -5096,7 +5047,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { continue; } } else if ( - (commitUnmount(node, renderPriorityLevel$jscomp$0), null !== node.child) + (commitUnmount(finishedRoot$jscomp$0, node, renderPriorityLevel$jscomp$0), + null !== node.child) ) { node.child.return = node; node = node.child; @@ -5118,7 +5070,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5148,10 +5100,8 @@ function commitWork(current$$1, finishedWork) { break; case 6: if (null === finishedWork.stateNode) - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." ); ReactNativePrivateInterface.UIManager.updateView( finishedWork.stateNode, @@ -5207,7 +5157,11 @@ function commitWork(current$$1, finishedWork) { } else { if (6 === current$$1.tag) throw Error("Not yet implemented."); - if (13 === current$$1.tag && null !== current$$1.memoizedState) { + if ( + 13 === current$$1.tag && + null !== current$$1.memoizedState && + null === current$$1.memoizedState.dehydrated + ) { updatePayload = current$$1.child.sibling; updatePayload.return = current$$1; current$$1 = updatePayload; @@ -5236,11 +5190,11 @@ function commitWork(current$$1, finishedWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5250,7 +5204,7 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || @@ -5305,18 +5259,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5327,7 +5284,6 @@ var ceil = Math.ceil, rootDoesHavePassiveEffects = !1, rootWithPendingPassiveEffects = null, pendingPassiveEffectsRenderPriority = 90, - pendingPassiveEffectsExpirationTime = 0, rootsWithPendingDiscreteUpdates = null, nestedUpdateCount = 0, rootWithNestedUpdates = null, @@ -5371,10 +5327,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5385,30 +5341,19 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? performSyncWorkOnRoot(fiber) + : (ensureRootIsScheduled(fiber), + executionContext === NoContext && flushSyncCallbackQueue()) + : ensureRootIsScheduled(fiber); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5443,78 +5388,334 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); - } -} -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { - return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null - ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); - } -} -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var priorityLevel = requestCurrentTime(); + 1073741823 === expirationTime + ? (priorityLevel = 99) + : 1 === expirationTime || 2 === expirationTime + ? (priorityLevel = 95) + : ((priorityLevel = + 10 * (1073741821 - expirationTime) - + 10 * (1073741821 - priorityLevel)), + (priorityLevel = + 0 >= priorityLevel + ? 99 + : 250 >= priorityLevel + ? 98 + : 5250 >= priorityLevel + ? 97 + : 95)); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= priorityLevel + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } + } +} +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) + return ( + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null + ); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && expirationTime === renderExpirationTime) || + prepareFreshStack(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if (workInProgressRootHasPendingPing) { + var lastPingedTime = root.lastPingedTime; + if (0 === lastPingedTime || lastPingedTime >= expirationTime) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + lastPingedTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== lastPingedTime && lastPingedTime !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + lastPingedTime = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (lastPingedTime = + now() - + (10 * (1073741821 - lastPingedTime) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + lastPingedTime <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + lastPingedTime)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } + } + return null; +} +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && lastExpiredTime === renderExpirationTime) || + prepareFreshStack(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5560,345 +5761,188 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var next = beginWork$$1( unitOfWork.alternate, @@ -5915,7 +5959,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { a: { var current = current$$1; current$$1 = workInProgress; @@ -5935,71 +5979,62 @@ function completeUnitOfWork(unitOfWork) { case 3: popHostContainer(current$$1); popTopLevelContextObject(current$$1); - newProps = current$$1.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - current$$1.effectTag &= -3; + current = current$$1.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(current$$1); break; case 5: popHostContext(current$$1); - renderExpirationTime$jscomp$0 = requiredContext( + var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - var type = current$$1.type; + renderExpirationTime$jscomp$0 = current$$1.type; if (null !== current && null != current$$1.stateNode) updateHostComponent$1( current, current$$1, - type, + renderExpirationTime$jscomp$0, newProps, - renderExpirationTime$jscomp$0 + rootContainerInstance ), current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (newProps) { current = requiredContext(contextStackCursor$1.current); - var type$jscomp$0 = type; - var _instance6 = newProps; - var rootContainerInstance = renderExpirationTime$jscomp$0, - internalInstanceHandle = current$$1, - tag = allocateTag(); - type$jscomp$0 = getViewConfigForType(type$jscomp$0); - var updatePayload = diffProperties( - null, - emptyObject, - _instance6, - type$jscomp$0.validAttributes - ); + var internalInstanceHandle = current$$1, + tag = allocateTag(), + viewConfig = getViewConfigForType( + renderExpirationTime$jscomp$0 + ), + updatePayload = diffProperties( + null, + emptyObject, + newProps, + viewConfig.validAttributes + ); ReactNativePrivateInterface.UIManager.createView( tag, - type$jscomp$0.uiViewClassName, + viewConfig.uiViewClassName, rootContainerInstance, updatePayload ); - rootContainerInstance = new ReactNativeFiberHostComponent( - tag, - type$jscomp$0 - ); + viewConfig = new ReactNativeFiberHostComponent(tag, viewConfig); instanceCache.set(tag, internalInstanceHandle); - instanceProps.set(tag, _instance6); - _instance6 = rootContainerInstance; - appendAllChildren(_instance6, current$$1, !1, !1); + instanceProps.set(tag, newProps); + appendAllChildren(viewConfig, current$$1, !1, !1); + current$$1.stateNode = viewConfig; finalizeInitialChildren( - _instance6, - type, - newProps, + viewConfig, renderExpirationTime$jscomp$0, + newProps, + rootContainerInstance, current ) && (current$$1.effectTag |= 4); - current$$1.stateNode = _instance6; null !== current$$1.ref && (current$$1.effectTag |= 128); } else if (null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6012,31 +6047,29 @@ function completeUnitOfWork(unitOfWork) { ); else { if ("string" !== typeof newProps && null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); - type = requiredContext(rootInstanceStackCursor.current); renderExpirationTime$jscomp$0 = requiredContext( + rootInstanceStackCursor.current + ); + rootContainerInstance = requiredContext( contextStackCursor$1.current ); current = current$$1; - if (!renderExpirationTime$jscomp$0.isInAParentText) - throw ReactError( - Error( - "Text strings must be rendered within a component." - ) + if (!rootContainerInstance.isInAParentText) + throw Error( + "Text strings must be rendered within a component." ); - renderExpirationTime$jscomp$0 = allocateTag(); + rootContainerInstance = allocateTag(); ReactNativePrivateInterface.UIManager.createView( - renderExpirationTime$jscomp$0, + rootContainerInstance, "RCTRawText", - type, + renderExpirationTime$jscomp$0, { text: newProps } ); - instanceCache.set(renderExpirationTime$jscomp$0, current$$1); - current.stateNode = renderExpirationTime$jscomp$0; + instanceCache.set(rootContainerInstance, current$$1); + current.stateNode = rootContainerInstance; } break; case 11: @@ -6049,41 +6082,51 @@ function completeUnitOfWork(unitOfWork) { break a; } newProps = null !== newProps; - renderExpirationTime$jscomp$0 = !1; + rootContainerInstance = !1; null !== current && - ((type = current.memoizedState), - (renderExpirationTime$jscomp$0 = null !== type), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === type || - ((type = current.child.sibling), - null !== type && - ((_instance6 = current$$1.firstEffect), - null !== _instance6 - ? ((current$$1.firstEffect = type), - (type.nextEffect = _instance6)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8)))); + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && + ((internalInstanceHandle = current$$1.firstEffect), + null !== internalInstanceHandle + ? ((current$$1.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = internalInstanceHandle)) + : ((current$$1.firstEffect = current$$1.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if ( newProps && - !renderExpirationTime$jscomp$0 && + !rootContainerInstance && 0 !== (current$$1.mode & 2) ) if ( (null === current && !0 !== current$$1.memoizedProps.unstable_avoidThisFallback) || - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; - if (newProps || renderExpirationTime$jscomp$0) - current$$1.effectTag |= 4; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime( + workInProgressRoot, + renderExpirationTime + ), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } + if (newProps || rootContainerInstance) current$$1.effectTag |= 4; break; case 7: break; @@ -6105,76 +6148,78 @@ function completeUnitOfWork(unitOfWork) { case 17: isContextProvider(current$$1.type) && popContext(current$$1); break; - case 18: - break; case 19: pop(suspenseStackCursor, current$$1); newProps = current$$1.memoizedState; if (null === newProps) break; - type = 0 !== (current$$1.effectTag & 64); - _instance6 = newProps.rendering; - if (null === _instance6) - if (type) cutOffTailIfNeeded(newProps, !1); + rootContainerInstance = 0 !== (current$$1.effectTag & 64); + internalInstanceHandle = newProps.rendering; + if (null === internalInstanceHandle) + if (rootContainerInstance) cutOffTailIfNeeded(newProps, !1); else { if ( workInProgressRootExitStatus !== RootIncomplete || (null !== current && 0 !== (current.effectTag & 64)) ) for (current = current$$1.child; null !== current; ) { - _instance6 = findFirstSuspended(current); - if (null !== _instance6) { + internalInstanceHandle = findFirstSuspended(current); + if (null !== internalInstanceHandle) { current$$1.effectTag |= 64; cutOffTailIfNeeded(newProps, !1); - newProps = _instance6.updateQueue; - null !== newProps && - ((current$$1.updateQueue = newProps), + current = internalInstanceHandle.updateQueue; + null !== current && + ((current$$1.updateQueue = current), (current$$1.effectTag |= 4)); - current$$1.firstEffect = current$$1.lastEffect = null; - newProps = renderExpirationTime$jscomp$0; - for (current = current$$1.child; null !== current; ) - (renderExpirationTime$jscomp$0 = current), - (type = newProps), - (renderExpirationTime$jscomp$0.effectTag &= 2), - (renderExpirationTime$jscomp$0.nextEffect = null), - (renderExpirationTime$jscomp$0.firstEffect = null), - (renderExpirationTime$jscomp$0.lastEffect = null), - (_instance6 = - renderExpirationTime$jscomp$0.alternate), - null === _instance6 - ? ((renderExpirationTime$jscomp$0.childExpirationTime = 0), - (renderExpirationTime$jscomp$0.expirationTime = type), - (renderExpirationTime$jscomp$0.child = null), - (renderExpirationTime$jscomp$0.memoizedProps = null), - (renderExpirationTime$jscomp$0.memoizedState = null), - (renderExpirationTime$jscomp$0.updateQueue = null), - (renderExpirationTime$jscomp$0.dependencies = null)) - : ((renderExpirationTime$jscomp$0.childExpirationTime = - _instance6.childExpirationTime), - (renderExpirationTime$jscomp$0.expirationTime = - _instance6.expirationTime), - (renderExpirationTime$jscomp$0.child = - _instance6.child), - (renderExpirationTime$jscomp$0.memoizedProps = - _instance6.memoizedProps), - (renderExpirationTime$jscomp$0.memoizedState = - _instance6.memoizedState), - (renderExpirationTime$jscomp$0.updateQueue = - _instance6.updateQueue), - (type = _instance6.dependencies), - (renderExpirationTime$jscomp$0.dependencies = - null === type + null === newProps.lastEffect && + (current$$1.firstEffect = null); + current$$1.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; + for (newProps = current$$1.child; null !== newProps; ) + (rootContainerInstance = newProps), + (renderExpirationTime$jscomp$0 = current), + (rootContainerInstance.effectTag &= 2), + (rootContainerInstance.nextEffect = null), + (rootContainerInstance.firstEffect = null), + (rootContainerInstance.lastEffect = null), + (internalInstanceHandle = + rootContainerInstance.alternate), + null === internalInstanceHandle + ? ((rootContainerInstance.childExpirationTime = 0), + (rootContainerInstance.expirationTime = renderExpirationTime$jscomp$0), + (rootContainerInstance.child = null), + (rootContainerInstance.memoizedProps = null), + (rootContainerInstance.memoizedState = null), + (rootContainerInstance.updateQueue = null), + (rootContainerInstance.dependencies = null)) + : ((rootContainerInstance.childExpirationTime = + internalInstanceHandle.childExpirationTime), + (rootContainerInstance.expirationTime = + internalInstanceHandle.expirationTime), + (rootContainerInstance.child = + internalInstanceHandle.child), + (rootContainerInstance.memoizedProps = + internalInstanceHandle.memoizedProps), + (rootContainerInstance.memoizedState = + internalInstanceHandle.memoizedState), + (rootContainerInstance.updateQueue = + internalInstanceHandle.updateQueue), + (renderExpirationTime$jscomp$0 = + internalInstanceHandle.dependencies), + (rootContainerInstance.dependencies = + null === renderExpirationTime$jscomp$0 ? null : { - expirationTime: type.expirationTime, - firstContext: type.firstContext, - responders: type.responders + expirationTime: + renderExpirationTime$jscomp$0.expirationTime, + firstContext: + renderExpirationTime$jscomp$0.firstContext, + responders: + renderExpirationTime$jscomp$0.responders })), - (current = current.sibling); + (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & - SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, current$$1 ); current$$1 = current$$1.child; @@ -6184,20 +6229,21 @@ function completeUnitOfWork(unitOfWork) { } } else { - if (!type) + if (!rootContainerInstance) if ( - ((current = findFirstSuspended(_instance6)), null !== current) + ((current = findFirstSuspended(internalInstanceHandle)), + null !== current) ) { if ( ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((current$$1.updateQueue = current), + (current$$1.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((current$$1.updateQueue = current), - (current$$1.effectTag |= 4)); current$$1 = current$$1.lastEffect = newProps.lastEffect; null !== current$$1 && (current$$1.nextEffect = null); break; @@ -6206,18 +6252,18 @@ function completeUnitOfWork(unitOfWork) { now() > newProps.tailExpiration && 1 < renderExpirationTime$jscomp$0 && ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), (current$$1.expirationTime = current$$1.childExpirationTime = renderExpirationTime$jscomp$0 - 1)); newProps.isBackwards - ? ((_instance6.sibling = current$$1.child), - (current$$1.child = _instance6)) + ? ((internalInstanceHandle.sibling = current$$1.child), + (current$$1.child = internalInstanceHandle)) : ((current = newProps.last), null !== current - ? (current.sibling = _instance6) - : (current$$1.child = _instance6), - (newProps.last = _instance6)); + ? (current.sibling = internalInstanceHandle) + : (current$$1.child = internalInstanceHandle), + (newProps.last = internalInstanceHandle)); } if (null !== newProps.tail) { 0 === newProps.tailExpiration && @@ -6228,10 +6274,9 @@ function completeUnitOfWork(unitOfWork) { newProps.lastEffect = current$$1.lastEffect; current.sibling = null; newProps = suspenseStackCursor.current; - newProps = type - ? (newProps & SubtreeSuspenseContextMask) | - ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask; + newProps = rootContainerInstance + ? (newProps & 1) | 2 + : newProps & 1; push(suspenseStackCursor, newProps, current$$1); current$$1 = current; break a; @@ -6239,34 +6284,39 @@ function completeUnitOfWork(unitOfWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + current$$1.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } current$$1 = null; } - newProps = workInProgress; - if (1 === renderExpirationTime || 1 !== newProps.childExpirationTime) { - current = 0; + current = workInProgress; + if (1 === renderExpirationTime || 1 !== current.childExpirationTime) { + newProps = 0; for ( - renderExpirationTime$jscomp$0 = newProps.child; - null !== renderExpirationTime$jscomp$0; + rootContainerInstance = current.child; + null !== rootContainerInstance; ) - (type = renderExpirationTime$jscomp$0.expirationTime), - (_instance6 = renderExpirationTime$jscomp$0.childExpirationTime), - type > current && (current = type), - _instance6 > current && (current = _instance6), - (renderExpirationTime$jscomp$0 = - renderExpirationTime$jscomp$0.sibling); - newProps.childExpirationTime = current; + (renderExpirationTime$jscomp$0 = + rootContainerInstance.expirationTime), + (internalInstanceHandle = + rootContainerInstance.childExpirationTime), + renderExpirationTime$jscomp$0 > newProps && + (newProps = renderExpirationTime$jscomp$0), + internalInstanceHandle > newProps && + (newProps = internalInstanceHandle), + (rootContainerInstance = rootContainerInstance.sibling); + current.childExpirationTime = newProps; } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6281,10 +6331,10 @@ function completeUnitOfWork(unitOfWork) { } else { current$$1 = unwindWork(workInProgress, renderExpirationTime); if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6294,131 +6344,88 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$0, renderPriorityLevel$jscomp$0) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$0.finishedWork, + expirationTime = root$jscomp$0.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$0.finishedWork = null; + root$jscomp$0.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$0.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$0.callbackNode = null; + root$jscomp$0.callbackExpirationTime = 0; + root$jscomp$0.callbackPriority = 90; + root$jscomp$0.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$0.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$0.lastSuspendedTime + ? (root$jscomp$0.firstSuspendedTime = root$jscomp$0.lastSuspendedTime = root$jscomp$0.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$0.firstSuspendedTime && + (root$jscomp$0.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$0.lastPingedTime && + (root$jscomp$0.lastPingedTime = 0); + expirationTime <= root$jscomp$0.lastExpiredTime && + (root$jscomp$0.lastExpiredTime = 0); + root$jscomp$0 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$0, + renderPriorityLevel = renderPriorityLevel$jscomp$0; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: commitPlacement(nextEffect); nextEffect.effectTag &= -3; @@ -6428,90 +6435,90 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - (prevProps = nextEffect), - unmountHostComponents(prevProps, current$$1), - detachFiber(prevProps); + var current$$1$jscomp$0 = nextEffect; + unmountHostComponents( + root, + current$$1$jscomp$0, + renderPriorityLevel + ); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$0.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for (effectTag = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { var current$$1$jscomp$1 = nextEffect.alternate; - current$$1$jscomp$0 = nextEffect; + current$$1 = nextEffect; currentRef = effectTag; - switch (current$$1$jscomp$0.tag) { + switch (current$$1.tag) { case 0: case 11: case 15: - commitHookEffectList( - UnmountLayout, - MountLayout, - current$$1$jscomp$0 - ); + commitHookEffectList(16, 32, current$$1); break; case 1: - var instance$jscomp$0 = current$$1$jscomp$0.stateNode; - if (current$$1$jscomp$0.effectTag & 4) + var instance = current$$1.stateNode; + if (current$$1.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = - current$$1$jscomp$0.elementType === - current$$1$jscomp$0.type + var prevProps = + current$$1.elementType === current$$1.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( - current$$1$jscomp$0.type, + current$$1.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } - var updateQueue = current$$1$jscomp$0.updateQueue; + var updateQueue = current$$1.updateQueue; null !== updateQueue && commitUpdateQueue( - current$$1$jscomp$0, + current$$1, updateQueue, - instance$jscomp$0, + instance, currentRef ); break; case 3: - var _updateQueue = current$$1$jscomp$0.updateQueue; + var _updateQueue = current$$1.updateQueue; if (null !== _updateQueue) { - current$$1 = null; - if (null !== current$$1$jscomp$0.child) - switch (current$$1$jscomp$0.child.tag) { + root = null; + if (null !== current$$1.child) + switch (current$$1.child.tag) { case 5: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; break; case 1: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; } - commitUpdateQueue( - current$$1$jscomp$0, - _updateQueue, - current$$1, - currentRef - ); + commitUpdateQueue(current$$1, _updateQueue, root, currentRef); } break; case 5: @@ -6523,101 +6530,111 @@ function commitRootImpl(root, renderPriorityLevel) { case 12: break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + current$$1 = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; break; default: - instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(current$$1) + : (ref.current = current$$1); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); nextEffect = null; requestPaint(); - executionContext = childExpirationTimeBeforeCommit; - } else root.current = finishedWork; + executionContext = prevExecutionContext; + } else root$jscomp$0.current = finishedWork; if (rootDoesHavePassiveEffects) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (rootWithPendingPassiveEffects = root$jscomp$0), + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$0); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$0 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - 0 !== renderPriorityLevel - ? ((effectTag$jscomp$0 = requestCurrentTime()), - (effectTag$jscomp$0 = inferPriorityFromExpirationTime( - effectTag$jscomp$0, - renderPriorityLevel - )), - scheduleCallbackForRoot(root, effectTag$jscomp$0, renderPriorityLevel)) - : (legacyErrorBoundariesThatAlreadyFailed = null); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + (nextEffect = renderPriorityLevel$jscomp$0); + renderPriorityLevel$jscomp$0 = root$jscomp$0.firstPendingTime; + 0 === renderPriorityLevel$jscomp$0 && + (legacyErrorBoundariesThatAlreadyFailed = null); + 1073741823 === renderPriorityLevel$jscomp$0 + ? root$jscomp$0 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$0)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$0); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$0 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$0); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; - var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + var root = rootWithPendingPassiveEffects; rootWithPendingPassiveEffects = null; - pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root) { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; for (root = root.current.firstEffect; null !== root; ) { @@ -6628,12 +6645,11 @@ function flushPassiveEffectsImpl(root) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === root) - throw ReactError(Error("Should be working on an effect.")); + if (null === root) throw Error("Should be working on an effect."); captureCommitPhaseError(root, error); } finishedWork = root.nextEffect; @@ -6649,7 +6665,7 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && ensureRootIsScheduled(rootFiber); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6671,7 +6687,7 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && ensureRootIsScheduled(fiber); break; } } @@ -6688,27 +6704,25 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + null !== boundaryFiber && ensureRootIsScheduled(boundaryFiber); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6754,7 +6768,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6766,7 +6780,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6798,6 +6812,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6882,7 +6897,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6925,12 +6942,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6970,10 +6985,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -7011,7 +7024,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7101,7 +7115,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7290,10 +7304,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; var onCommitFiberRoot = null, @@ -7464,12 +7478,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7513,19 +7525,54 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; +} +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; } function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7535,23 +7582,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7569,10 +7613,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7591,14 +7633,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7611,31 +7652,11 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; if ("number" === typeof componentOrHandle) return componentOrHandle; @@ -7668,33 +7689,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7707,10 +7718,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7723,34 +7733,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7828,9 +7836,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7844,9 +7851,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7860,29 +7866,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7949,9 +7953,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromTag, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js b/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js index b11536d066f5c5..83ba009d089450 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js @@ -15,10 +15,6 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} var eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { @@ -27,21 +23,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -51,12 +43,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -81,14 +71,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -96,12 +84,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -149,10 +135,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -170,7 +154,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -182,10 +166,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -221,10 +203,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -240,12 +220,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -286,14 +264,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -456,10 +432,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -495,8 +469,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -610,8 +583,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -711,7 +684,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -724,7 +697,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -733,9 +706,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -744,194 +717,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -939,7 +920,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -953,9 +934,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -988,10 +972,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1017,10 +999,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1064,7 +1044,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1075,10 +1056,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1132,7 +1111,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - if (!tag) throw ReactError(Error("All native instances should have a tag.")); + if (!tag) throw Error("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1171,6 +1150,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1179,6 +1159,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1218,27 +1218,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1258,7 +1262,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1294,22 +1298,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1559,43 +1559,35 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { } var ReactNativeFiberHostComponent = (function() { function ReactNativeFiberHostComponent(tag, viewConfig) { - if (!(this instanceof ReactNativeFiberHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this._children = []; this.viewConfig = viewConfig; } - ReactNativeFiberHostComponent.prototype.blur = function() { + var _proto = ReactNativeFiberHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { ReactNativePrivateInterface.UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { ReactNativePrivateInterface.UIManager.measureInWindow( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { - var relativeNode = void 0; - "number" === typeof relativeToNativeNode - ? (relativeNode = relativeToNativeNode) - : relativeToNativeNode._nativeTag - ? (relativeNode = relativeToNativeNode._nativeTag) - : relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag && - (relativeNode = relativeToNativeNode.canonical._nativeTag); + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, @@ -1604,9 +1596,7 @@ var ReactNativeFiberHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { + _proto.setNativeProps = function(nativeProps) { nativeProps = diffProperties( null, emptyObject, @@ -1623,10 +1613,8 @@ var ReactNativeFiberHostComponent = (function() { return ReactNativeFiberHostComponent; })(); function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var getViewConfigForType = @@ -1747,10 +1735,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1762,15 +1748,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1789,10 +1773,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1842,7 +1824,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1858,7 +1840,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority(reactPriorityLevel, fn) { @@ -1880,8 +1862,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1910,25 +1895,13 @@ function flushSyncCallbackQueueImpl() { } } } -function inferPriorityFromExpirationTime(currentTime, expirationTime) { - if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; - currentTime = - 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); - return 0 >= currentTime - ? 99 - : 250 >= currentTime - ? 98 - : 5250 >= currentTime - ? 97 - : 95; -} function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1942,7 +1915,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1957,41 +1930,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2047,10 +1985,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2170,7 +2106,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2265,6 +2201,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2281,18 +2218,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2320,7 +2254,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2485,23 +2419,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2520,32 +2449,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2947,14 +2870,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3046,7 +2967,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3071,10 +2992,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3110,7 +3035,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3130,10 +3055,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3188,11 +3114,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3206,10 +3130,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3247,14 +3169,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3275,15 +3200,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3298,16 +3215,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3350,10 +3265,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3389,9 +3302,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3415,10 +3326,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3432,7 +3341,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3460,7 +3369,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3474,7 +3384,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3514,7 +3424,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3542,10 +3452,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3573,28 +3481,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3602,10 +3506,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3637,19 +3541,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3717,19 +3621,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3784,7 +3688,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3804,7 +3708,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4294,7 +4198,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4303,116 +4207,37 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; - if (0 === (workInProgress.mode & 2)) - for ( - nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); - renderExpirationTime = createFiberFromFragment( - nextProps, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime - ); - else { - if (null !== current$$1.memoizedState) - if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { nextDidTimeout = nextProps.fallback; nextProps = createFiberFromFragment(null, mode, 0, null); nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); if (0 === (workInProgress.mode & 2)) for ( - suspenseContext = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + nextProps.child = current$$1; + null !== current$$1; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( nextDidTimeout, mode, @@ -4421,28 +4246,118 @@ function updateSuspenseComponent( ); renderExpirationTime.return = workInProgress; nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - workInProgress.stateNode = current$$1.stateNode; + renderExpirationTime.return = workInProgress; + if ( + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) + for ( + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; + + ) + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4452,14 +4367,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4476,24 +4393,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4510,7 +4420,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4519,9 +4429,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4535,33 +4445,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4575,9 +4494,11 @@ function bailoutOnAlreadyFinishedWork( ) { null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4602,10 +4523,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function(parent, workInProgress) { for (var node = workInProgress.child; null !== node; ) { if (5 === node.tag || 6 === node.tag) parent._children.push(node.stateNode); @@ -4662,8 +4583,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -4671,12 +4592,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -4684,13 +4603,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -4712,8 +4629,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -4721,7 +4638,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -4771,24 +4688,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -4796,12 +4746,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -4835,7 +4785,11 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { safelyDetachRef(current$$1$jscomp$0); break; case 4: - unmountHostComponents(current$$1$jscomp$0, renderPriorityLevel); + unmountHostComponents( + finishedRoot, + current$$1$jscomp$0, + renderPriorityLevel + ); } } function detachFiber(current$$1) { @@ -4864,10 +4818,8 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); } parent = parentFiber.stateNode; @@ -4884,10 +4836,8 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } parentFiber.effectTag & 16 && (parentFiber.effectTag &= -17); @@ -4923,9 +4873,7 @@ function commitPlacement(finishedWork) { if (parentFiber) if (isContainer) { if ("number" === typeof parent) - throw ReactError( - Error("Container does not support insertBefore operation") - ); + throw Error("Container does not support insertBefore operation"); } else { isHost = parent; var beforeChild = parentFiber, @@ -5002,12 +4950,16 @@ function commitPlacement(finishedWork) { node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { +function unmountHostComponents( + finishedRoot$jscomp$0, + current$$1, + renderPriorityLevel$jscomp$0 +) { for ( var node = current$$1, currentParentIsValid = !1, - currentParent = void 0, - currentParentIsContainer = void 0; + currentParent, + currentParentIsContainer; ; ) { @@ -5015,10 +4967,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { currentParentIsValid = node.return; a: for (;;) { if (null === currentParentIsValid) - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); currentParent = currentParentIsValid.stateNode; switch (currentParentIsValid.tag) { @@ -5040,14 +4990,15 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { } if (5 === node.tag || 6 === node.tag) { a: for ( - var root = node, + var finishedRoot = finishedRoot$jscomp$0, + root = node, renderPriorityLevel = renderPriorityLevel$jscomp$0, node$jscomp$0 = root; ; ) if ( - (commitUnmount(node$jscomp$0, renderPriorityLevel), + (commitUnmount(finishedRoot, node$jscomp$0, renderPriorityLevel), null !== node$jscomp$0.child && 4 !== node$jscomp$0.tag) ) (node$jscomp$0.child.return = node$jscomp$0), @@ -5063,29 +5014,29 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { node$jscomp$0 = node$jscomp$0.sibling; } currentParentIsContainer - ? ((root = currentParent), + ? ((finishedRoot = currentParent), recursivelyUncacheFiberNode(node.stateNode), ReactNativePrivateInterface.UIManager.manageChildren( - root, + finishedRoot, [], [], [], [], [0] )) - : ((root = currentParent), - (node$jscomp$0 = node.stateNode), - recursivelyUncacheFiberNode(node$jscomp$0), - (renderPriorityLevel = root._children), - (node$jscomp$0 = renderPriorityLevel.indexOf(node$jscomp$0)), - renderPriorityLevel.splice(node$jscomp$0, 1), + : ((finishedRoot = currentParent), + (renderPriorityLevel = node.stateNode), + recursivelyUncacheFiberNode(renderPriorityLevel), + (root = finishedRoot._children), + (renderPriorityLevel = root.indexOf(renderPriorityLevel)), + root.splice(renderPriorityLevel, 1), ReactNativePrivateInterface.UIManager.manageChildren( - root._nativeTag, + finishedRoot._nativeTag, [], [], [], [], - [node$jscomp$0] + [renderPriorityLevel] )); } else if (4 === node.tag) { if (null !== node.child) { @@ -5096,7 +5047,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { continue; } } else if ( - (commitUnmount(node, renderPriorityLevel$jscomp$0), null !== node.child) + (commitUnmount(finishedRoot$jscomp$0, node, renderPriorityLevel$jscomp$0), + null !== node.child) ) { node.child.return = node; node = node.child; @@ -5118,7 +5070,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5148,10 +5100,8 @@ function commitWork(current$$1, finishedWork) { break; case 6: if (null === finishedWork.stateNode) - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." ); ReactNativePrivateInterface.UIManager.updateView( finishedWork.stateNode, @@ -5207,7 +5157,11 @@ function commitWork(current$$1, finishedWork) { } else { if (6 === current$$1.tag) throw Error("Not yet implemented."); - if (13 === current$$1.tag && null !== current$$1.memoizedState) { + if ( + 13 === current$$1.tag && + null !== current$$1.memoizedState && + null === current$$1.memoizedState.dehydrated + ) { updatePayload = current$$1.child.sibling; updatePayload.return = current$$1; current$$1 = updatePayload; @@ -5236,11 +5190,11 @@ function commitWork(current$$1, finishedWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5250,7 +5204,7 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || @@ -5305,18 +5259,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5327,7 +5284,6 @@ var ceil = Math.ceil, rootDoesHavePassiveEffects = !1, rootWithPendingPassiveEffects = null, pendingPassiveEffectsRenderPriority = 90, - pendingPassiveEffectsExpirationTime = 0, rootsWithPendingDiscreteUpdates = null, nestedUpdateCount = 0, rootWithNestedUpdates = null, @@ -5371,10 +5327,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5385,30 +5341,19 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? performSyncWorkOnRoot(fiber) + : (ensureRootIsScheduled(fiber), + executionContext === NoContext && flushSyncCallbackQueue()) + : ensureRootIsScheduled(fiber); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5443,78 +5388,334 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); - } -} -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { - return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null - ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); - } -} -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var priorityLevel = requestCurrentTime(); + 1073741823 === expirationTime + ? (priorityLevel = 99) + : 1 === expirationTime || 2 === expirationTime + ? (priorityLevel = 95) + : ((priorityLevel = + 10 * (1073741821 - expirationTime) - + 10 * (1073741821 - priorityLevel)), + (priorityLevel = + 0 >= priorityLevel + ? 99 + : 250 >= priorityLevel + ? 98 + : 5250 >= priorityLevel + ? 97 + : 95)); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= priorityLevel + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = priorityLevel; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + priorityLevel, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } + } +} +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) + return ( + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null + ); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && expirationTime === renderExpirationTime) || + prepareFreshStack(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if (workInProgressRootHasPendingPing) { + var lastPingedTime = root.lastPingedTime; + if (0 === lastPingedTime || lastPingedTime >= expirationTime) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + } + lastPingedTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== lastPingedTime && lastPingedTime !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + lastPingedTime = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (lastPingedTime = + now() - + (10 * (1073741821 - lastPingedTime) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + lastPingedTime <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + lastPingedTime)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } + } + return null; +} +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + (root === workInProgressRoot && lastExpiredTime === renderExpirationTime) || + prepareFreshStack(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5560,345 +5761,188 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var next = beginWork$$1( unitOfWork.alternate, @@ -5915,7 +5959,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { a: { var current = current$$1; current$$1 = workInProgress; @@ -5935,71 +5979,62 @@ function completeUnitOfWork(unitOfWork) { case 3: popHostContainer(current$$1); popTopLevelContextObject(current$$1); - newProps = current$$1.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - current$$1.effectTag &= -3; + current = current$$1.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(current$$1); break; case 5: popHostContext(current$$1); - renderExpirationTime$jscomp$0 = requiredContext( + var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - var type = current$$1.type; + renderExpirationTime$jscomp$0 = current$$1.type; if (null !== current && null != current$$1.stateNode) updateHostComponent$1( current, current$$1, - type, + renderExpirationTime$jscomp$0, newProps, - renderExpirationTime$jscomp$0 + rootContainerInstance ), current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (newProps) { current = requiredContext(contextStackCursor$1.current); - var type$jscomp$0 = type; - var _instance6 = newProps; - var rootContainerInstance = renderExpirationTime$jscomp$0, - internalInstanceHandle = current$$1, - tag = allocateTag(); - type$jscomp$0 = getViewConfigForType(type$jscomp$0); - var updatePayload = diffProperties( - null, - emptyObject, - _instance6, - type$jscomp$0.validAttributes - ); + var internalInstanceHandle = current$$1, + tag = allocateTag(), + viewConfig = getViewConfigForType( + renderExpirationTime$jscomp$0 + ), + updatePayload = diffProperties( + null, + emptyObject, + newProps, + viewConfig.validAttributes + ); ReactNativePrivateInterface.UIManager.createView( tag, - type$jscomp$0.uiViewClassName, + viewConfig.uiViewClassName, rootContainerInstance, updatePayload ); - rootContainerInstance = new ReactNativeFiberHostComponent( - tag, - type$jscomp$0 - ); + viewConfig = new ReactNativeFiberHostComponent(tag, viewConfig); instanceCache.set(tag, internalInstanceHandle); - instanceProps.set(tag, _instance6); - _instance6 = rootContainerInstance; - appendAllChildren(_instance6, current$$1, !1, !1); + instanceProps.set(tag, newProps); + appendAllChildren(viewConfig, current$$1, !1, !1); + current$$1.stateNode = viewConfig; finalizeInitialChildren( - _instance6, - type, - newProps, + viewConfig, renderExpirationTime$jscomp$0, + newProps, + rootContainerInstance, current ) && (current$$1.effectTag |= 4); - current$$1.stateNode = _instance6; null !== current$$1.ref && (current$$1.effectTag |= 128); } else if (null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -6012,31 +6047,29 @@ function completeUnitOfWork(unitOfWork) { ); else { if ("string" !== typeof newProps && null === current$$1.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); - type = requiredContext(rootInstanceStackCursor.current); renderExpirationTime$jscomp$0 = requiredContext( + rootInstanceStackCursor.current + ); + rootContainerInstance = requiredContext( contextStackCursor$1.current ); current = current$$1; - if (!renderExpirationTime$jscomp$0.isInAParentText) - throw ReactError( - Error( - "Text strings must be rendered within a component." - ) + if (!rootContainerInstance.isInAParentText) + throw Error( + "Text strings must be rendered within a component." ); - renderExpirationTime$jscomp$0 = allocateTag(); + rootContainerInstance = allocateTag(); ReactNativePrivateInterface.UIManager.createView( - renderExpirationTime$jscomp$0, + rootContainerInstance, "RCTRawText", - type, + renderExpirationTime$jscomp$0, { text: newProps } ); - instanceCache.set(renderExpirationTime$jscomp$0, current$$1); - current.stateNode = renderExpirationTime$jscomp$0; + instanceCache.set(rootContainerInstance, current$$1); + current.stateNode = rootContainerInstance; } break; case 11: @@ -6049,41 +6082,51 @@ function completeUnitOfWork(unitOfWork) { break a; } newProps = null !== newProps; - renderExpirationTime$jscomp$0 = !1; + rootContainerInstance = !1; null !== current && - ((type = current.memoizedState), - (renderExpirationTime$jscomp$0 = null !== type), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === type || - ((type = current.child.sibling), - null !== type && - ((_instance6 = current$$1.firstEffect), - null !== _instance6 - ? ((current$$1.firstEffect = type), - (type.nextEffect = _instance6)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8)))); + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && + ((internalInstanceHandle = current$$1.firstEffect), + null !== internalInstanceHandle + ? ((current$$1.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = internalInstanceHandle)) + : ((current$$1.firstEffect = current$$1.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if ( newProps && - !renderExpirationTime$jscomp$0 && + !rootContainerInstance && 0 !== (current$$1.mode & 2) ) if ( (null === current && !0 !== current$$1.memoizedProps.unstable_avoidThisFallback) || - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; - if (newProps || renderExpirationTime$jscomp$0) - current$$1.effectTag |= 4; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime( + workInProgressRoot, + renderExpirationTime + ), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } + if (newProps || rootContainerInstance) current$$1.effectTag |= 4; break; case 7: break; @@ -6105,76 +6148,78 @@ function completeUnitOfWork(unitOfWork) { case 17: isContextProvider(current$$1.type) && popContext(current$$1); break; - case 18: - break; case 19: pop(suspenseStackCursor, current$$1); newProps = current$$1.memoizedState; if (null === newProps) break; - type = 0 !== (current$$1.effectTag & 64); - _instance6 = newProps.rendering; - if (null === _instance6) - if (type) cutOffTailIfNeeded(newProps, !1); + rootContainerInstance = 0 !== (current$$1.effectTag & 64); + internalInstanceHandle = newProps.rendering; + if (null === internalInstanceHandle) + if (rootContainerInstance) cutOffTailIfNeeded(newProps, !1); else { if ( workInProgressRootExitStatus !== RootIncomplete || (null !== current && 0 !== (current.effectTag & 64)) ) for (current = current$$1.child; null !== current; ) { - _instance6 = findFirstSuspended(current); - if (null !== _instance6) { + internalInstanceHandle = findFirstSuspended(current); + if (null !== internalInstanceHandle) { current$$1.effectTag |= 64; cutOffTailIfNeeded(newProps, !1); - newProps = _instance6.updateQueue; - null !== newProps && - ((current$$1.updateQueue = newProps), + current = internalInstanceHandle.updateQueue; + null !== current && + ((current$$1.updateQueue = current), (current$$1.effectTag |= 4)); - current$$1.firstEffect = current$$1.lastEffect = null; - newProps = renderExpirationTime$jscomp$0; - for (current = current$$1.child; null !== current; ) - (renderExpirationTime$jscomp$0 = current), - (type = newProps), - (renderExpirationTime$jscomp$0.effectTag &= 2), - (renderExpirationTime$jscomp$0.nextEffect = null), - (renderExpirationTime$jscomp$0.firstEffect = null), - (renderExpirationTime$jscomp$0.lastEffect = null), - (_instance6 = - renderExpirationTime$jscomp$0.alternate), - null === _instance6 - ? ((renderExpirationTime$jscomp$0.childExpirationTime = 0), - (renderExpirationTime$jscomp$0.expirationTime = type), - (renderExpirationTime$jscomp$0.child = null), - (renderExpirationTime$jscomp$0.memoizedProps = null), - (renderExpirationTime$jscomp$0.memoizedState = null), - (renderExpirationTime$jscomp$0.updateQueue = null), - (renderExpirationTime$jscomp$0.dependencies = null)) - : ((renderExpirationTime$jscomp$0.childExpirationTime = - _instance6.childExpirationTime), - (renderExpirationTime$jscomp$0.expirationTime = - _instance6.expirationTime), - (renderExpirationTime$jscomp$0.child = - _instance6.child), - (renderExpirationTime$jscomp$0.memoizedProps = - _instance6.memoizedProps), - (renderExpirationTime$jscomp$0.memoizedState = - _instance6.memoizedState), - (renderExpirationTime$jscomp$0.updateQueue = - _instance6.updateQueue), - (type = _instance6.dependencies), - (renderExpirationTime$jscomp$0.dependencies = - null === type + null === newProps.lastEffect && + (current$$1.firstEffect = null); + current$$1.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; + for (newProps = current$$1.child; null !== newProps; ) + (rootContainerInstance = newProps), + (renderExpirationTime$jscomp$0 = current), + (rootContainerInstance.effectTag &= 2), + (rootContainerInstance.nextEffect = null), + (rootContainerInstance.firstEffect = null), + (rootContainerInstance.lastEffect = null), + (internalInstanceHandle = + rootContainerInstance.alternate), + null === internalInstanceHandle + ? ((rootContainerInstance.childExpirationTime = 0), + (rootContainerInstance.expirationTime = renderExpirationTime$jscomp$0), + (rootContainerInstance.child = null), + (rootContainerInstance.memoizedProps = null), + (rootContainerInstance.memoizedState = null), + (rootContainerInstance.updateQueue = null), + (rootContainerInstance.dependencies = null)) + : ((rootContainerInstance.childExpirationTime = + internalInstanceHandle.childExpirationTime), + (rootContainerInstance.expirationTime = + internalInstanceHandle.expirationTime), + (rootContainerInstance.child = + internalInstanceHandle.child), + (rootContainerInstance.memoizedProps = + internalInstanceHandle.memoizedProps), + (rootContainerInstance.memoizedState = + internalInstanceHandle.memoizedState), + (rootContainerInstance.updateQueue = + internalInstanceHandle.updateQueue), + (renderExpirationTime$jscomp$0 = + internalInstanceHandle.dependencies), + (rootContainerInstance.dependencies = + null === renderExpirationTime$jscomp$0 ? null : { - expirationTime: type.expirationTime, - firstContext: type.firstContext, - responders: type.responders + expirationTime: + renderExpirationTime$jscomp$0.expirationTime, + firstContext: + renderExpirationTime$jscomp$0.firstContext, + responders: + renderExpirationTime$jscomp$0.responders })), - (current = current.sibling); + (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & - SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, current$$1 ); current$$1 = current$$1.child; @@ -6184,20 +6229,21 @@ function completeUnitOfWork(unitOfWork) { } } else { - if (!type) + if (!rootContainerInstance) if ( - ((current = findFirstSuspended(_instance6)), null !== current) + ((current = findFirstSuspended(internalInstanceHandle)), + null !== current) ) { if ( ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((current$$1.updateQueue = current), + (current$$1.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((current$$1.updateQueue = current), - (current$$1.effectTag |= 4)); current$$1 = current$$1.lastEffect = newProps.lastEffect; null !== current$$1 && (current$$1.nextEffect = null); break; @@ -6206,18 +6252,18 @@ function completeUnitOfWork(unitOfWork) { now() > newProps.tailExpiration && 1 < renderExpirationTime$jscomp$0 && ((current$$1.effectTag |= 64), - (type = !0), + (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), (current$$1.expirationTime = current$$1.childExpirationTime = renderExpirationTime$jscomp$0 - 1)); newProps.isBackwards - ? ((_instance6.sibling = current$$1.child), - (current$$1.child = _instance6)) + ? ((internalInstanceHandle.sibling = current$$1.child), + (current$$1.child = internalInstanceHandle)) : ((current = newProps.last), null !== current - ? (current.sibling = _instance6) - : (current$$1.child = _instance6), - (newProps.last = _instance6)); + ? (current.sibling = internalInstanceHandle) + : (current$$1.child = internalInstanceHandle), + (newProps.last = internalInstanceHandle)); } if (null !== newProps.tail) { 0 === newProps.tailExpiration && @@ -6228,10 +6274,9 @@ function completeUnitOfWork(unitOfWork) { newProps.lastEffect = current$$1.lastEffect; current.sibling = null; newProps = suspenseStackCursor.current; - newProps = type - ? (newProps & SubtreeSuspenseContextMask) | - ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask; + newProps = rootContainerInstance + ? (newProps & 1) | 2 + : newProps & 1; push(suspenseStackCursor, newProps, current$$1); current$$1 = current; break a; @@ -6239,34 +6284,39 @@ function completeUnitOfWork(unitOfWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + current$$1.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } current$$1 = null; } - newProps = workInProgress; - if (1 === renderExpirationTime || 1 !== newProps.childExpirationTime) { - current = 0; + current = workInProgress; + if (1 === renderExpirationTime || 1 !== current.childExpirationTime) { + newProps = 0; for ( - renderExpirationTime$jscomp$0 = newProps.child; - null !== renderExpirationTime$jscomp$0; + rootContainerInstance = current.child; + null !== rootContainerInstance; ) - (type = renderExpirationTime$jscomp$0.expirationTime), - (_instance6 = renderExpirationTime$jscomp$0.childExpirationTime), - type > current && (current = type), - _instance6 > current && (current = _instance6), - (renderExpirationTime$jscomp$0 = - renderExpirationTime$jscomp$0.sibling); - newProps.childExpirationTime = current; + (renderExpirationTime$jscomp$0 = + rootContainerInstance.expirationTime), + (internalInstanceHandle = + rootContainerInstance.childExpirationTime), + renderExpirationTime$jscomp$0 > newProps && + (newProps = renderExpirationTime$jscomp$0), + internalInstanceHandle > newProps && + (newProps = internalInstanceHandle), + (rootContainerInstance = rootContainerInstance.sibling); + current.childExpirationTime = newProps; } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6281,10 +6331,10 @@ function completeUnitOfWork(unitOfWork) { } else { current$$1 = unwindWork(workInProgress, renderExpirationTime); if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6294,131 +6344,88 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$0, renderPriorityLevel$jscomp$0) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$0.finishedWork, + expirationTime = root$jscomp$0.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$0.finishedWork = null; + root$jscomp$0.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$0.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$0.callbackNode = null; + root$jscomp$0.callbackExpirationTime = 0; + root$jscomp$0.callbackPriority = 90; + root$jscomp$0.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$0.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$0.lastSuspendedTime + ? (root$jscomp$0.firstSuspendedTime = root$jscomp$0.lastSuspendedTime = root$jscomp$0.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$0.firstSuspendedTime && + (root$jscomp$0.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$0.lastPingedTime && + (root$jscomp$0.lastPingedTime = 0); + expirationTime <= root$jscomp$0.lastExpiredTime && + (root$jscomp$0.lastExpiredTime = 0); + root$jscomp$0 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$0, + renderPriorityLevel = renderPriorityLevel$jscomp$0; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: commitPlacement(nextEffect); nextEffect.effectTag &= -3; @@ -6428,90 +6435,90 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - (prevProps = nextEffect), - unmountHostComponents(prevProps, current$$1), - detachFiber(prevProps); + var current$$1$jscomp$0 = nextEffect; + unmountHostComponents( + root, + current$$1$jscomp$0, + renderPriorityLevel + ); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$0.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for (effectTag = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { var current$$1$jscomp$1 = nextEffect.alternate; - current$$1$jscomp$0 = nextEffect; + current$$1 = nextEffect; currentRef = effectTag; - switch (current$$1$jscomp$0.tag) { + switch (current$$1.tag) { case 0: case 11: case 15: - commitHookEffectList( - UnmountLayout, - MountLayout, - current$$1$jscomp$0 - ); + commitHookEffectList(16, 32, current$$1); break; case 1: - var instance$jscomp$0 = current$$1$jscomp$0.stateNode; - if (current$$1$jscomp$0.effectTag & 4) + var instance = current$$1.stateNode; + if (current$$1.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = - current$$1$jscomp$0.elementType === - current$$1$jscomp$0.type + var prevProps = + current$$1.elementType === current$$1.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( - current$$1$jscomp$0.type, + current$$1.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } - var updateQueue = current$$1$jscomp$0.updateQueue; + var updateQueue = current$$1.updateQueue; null !== updateQueue && commitUpdateQueue( - current$$1$jscomp$0, + current$$1, updateQueue, - instance$jscomp$0, + instance, currentRef ); break; case 3: - var _updateQueue = current$$1$jscomp$0.updateQueue; + var _updateQueue = current$$1.updateQueue; if (null !== _updateQueue) { - current$$1 = null; - if (null !== current$$1$jscomp$0.child) - switch (current$$1$jscomp$0.child.tag) { + root = null; + if (null !== current$$1.child) + switch (current$$1.child.tag) { case 5: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; break; case 1: - current$$1 = current$$1$jscomp$0.child.stateNode; + root = current$$1.child.stateNode; } - commitUpdateQueue( - current$$1$jscomp$0, - _updateQueue, - current$$1, - currentRef - ); + commitUpdateQueue(current$$1, _updateQueue, root, currentRef); } break; case 5: @@ -6523,101 +6530,111 @@ function commitRootImpl(root, renderPriorityLevel) { case 12: break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + current$$1 = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; break; default: - instanceToUse = instance$jscomp$1; + current$$1 = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(current$$1) + : (ref.current = current$$1); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); nextEffect = null; requestPaint(); - executionContext = childExpirationTimeBeforeCommit; - } else root.current = finishedWork; + executionContext = prevExecutionContext; + } else root$jscomp$0.current = finishedWork; if (rootDoesHavePassiveEffects) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), - (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (rootWithPendingPassiveEffects = root$jscomp$0), + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$0); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$0 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - 0 !== renderPriorityLevel - ? ((effectTag$jscomp$0 = requestCurrentTime()), - (effectTag$jscomp$0 = inferPriorityFromExpirationTime( - effectTag$jscomp$0, - renderPriorityLevel - )), - scheduleCallbackForRoot(root, effectTag$jscomp$0, renderPriorityLevel)) - : (legacyErrorBoundariesThatAlreadyFailed = null); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + (nextEffect = renderPriorityLevel$jscomp$0); + renderPriorityLevel$jscomp$0 = root$jscomp$0.firstPendingTime; + 0 === renderPriorityLevel$jscomp$0 && + (legacyErrorBoundariesThatAlreadyFailed = null); + 1073741823 === renderPriorityLevel$jscomp$0 + ? root$jscomp$0 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$0)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$0); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$0 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$0); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; - var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + var root = rootWithPendingPassiveEffects; rootWithPendingPassiveEffects = null; - pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root) { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; for (root = root.current.firstEffect; null !== root; ) { @@ -6628,12 +6645,11 @@ function flushPassiveEffectsImpl(root) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === root) - throw ReactError(Error("Should be working on an effect.")); + if (null === root) throw Error("Should be working on an effect."); captureCommitPhaseError(root, error); } finishedWork = root.nextEffect; @@ -6649,7 +6665,7 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && ensureRootIsScheduled(rootFiber); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6671,7 +6687,7 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && ensureRootIsScheduled(fiber); break; } } @@ -6688,27 +6704,25 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + null !== boundaryFiber && ensureRootIsScheduled(boundaryFiber); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6754,7 +6768,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6766,7 +6780,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6798,6 +6812,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -6882,7 +6897,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -6925,12 +6942,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -6970,10 +6985,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -7011,7 +7024,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7101,7 +7115,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7290,10 +7304,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; var onCommitFiberRoot = null, @@ -7464,12 +7478,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7513,19 +7525,54 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; +} +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; } function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7535,23 +7582,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7569,10 +7613,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7591,14 +7633,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7611,31 +7652,11 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; if ("number" === typeof componentOrHandle) return componentOrHandle; @@ -7668,33 +7689,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7707,10 +7718,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7723,34 +7733,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7828,9 +7836,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7844,9 +7851,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7860,29 +7866,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -7949,9 +7953,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromTag, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.fb.js b/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.fb.js index dccfb21435145b..3da454cf0f8a6c 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.fb.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.fb.js @@ -14,12 +14,8 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"), - tracing = require("scheduler/tracing"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} -var eventPluginOrder = null, + tracing = require("scheduler/tracing"), + eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { if (eventPluginOrder) @@ -27,21 +23,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -51,12 +43,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -81,14 +71,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -96,12 +84,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -149,10 +135,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -170,7 +154,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -182,10 +166,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -221,10 +203,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -240,12 +220,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -286,14 +264,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -456,10 +432,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -495,8 +469,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -610,8 +583,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -711,7 +684,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -724,7 +697,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -733,9 +706,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -744,194 +717,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -939,7 +920,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -953,9 +934,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -988,10 +972,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1017,10 +999,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } require("../shims/ReactFeatureFlags"); @@ -1065,7 +1045,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1076,10 +1057,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1133,7 +1112,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - if (!tag) throw ReactError(Error("All native instances should have a tag.")); + if (!tag) throw Error("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1172,6 +1151,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1180,6 +1160,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1219,27 +1219,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1259,7 +1263,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1295,22 +1299,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1560,43 +1560,35 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { } var ReactNativeFiberHostComponent = (function() { function ReactNativeFiberHostComponent(tag, viewConfig) { - if (!(this instanceof ReactNativeFiberHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this._children = []; this.viewConfig = viewConfig; } - ReactNativeFiberHostComponent.prototype.blur = function() { + var _proto = ReactNativeFiberHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { ReactNativePrivateInterface.UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { ReactNativePrivateInterface.UIManager.measureInWindow( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { - var relativeNode = void 0; - "number" === typeof relativeToNativeNode - ? (relativeNode = relativeToNativeNode) - : relativeToNativeNode._nativeTag - ? (relativeNode = relativeToNativeNode._nativeTag) - : relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag && - (relativeNode = relativeToNativeNode.canonical._nativeTag); + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, @@ -1605,9 +1597,7 @@ var ReactNativeFiberHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { + _proto.setNativeProps = function(nativeProps) { nativeProps = diffProperties( null, emptyObject, @@ -1624,10 +1614,8 @@ var ReactNativeFiberHostComponent = (function() { return ReactNativeFiberHostComponent; })(); function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var getViewConfigForType = @@ -1748,10 +1736,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1763,15 +1749,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1790,10 +1774,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1821,10 +1803,8 @@ if ( null == tracing.__interactionsRef || null == tracing.__interactionsRef.current ) - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) + 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" ); var fakeCallbackNode = {}, requestPaint = @@ -1852,7 +1832,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1868,7 +1848,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority(reactPriorityLevel, fn) { @@ -1890,8 +1870,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1922,7 +1905,7 @@ function flushSyncCallbackQueueImpl() { } function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; + if (1 === expirationTime || 2 === expirationTime) return 95; currentTime = 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); return 0 >= currentTime @@ -1936,9 +1919,10 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1952,7 +1936,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1967,41 +1951,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2057,10 +2006,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2180,7 +2127,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2275,6 +2222,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2291,18 +2239,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2330,7 +2275,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2495,23 +2440,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2530,32 +2470,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2957,14 +2891,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3056,7 +2988,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3081,10 +3013,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3120,7 +3056,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3140,10 +3076,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3198,11 +3135,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3216,10 +3151,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3257,14 +3190,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3285,15 +3221,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3308,16 +3236,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3360,10 +3286,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3399,9 +3323,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3425,10 +3347,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3442,7 +3362,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3470,7 +3390,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3484,7 +3405,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3524,7 +3445,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3552,10 +3473,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3583,28 +3502,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3612,10 +3527,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3647,19 +3562,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3727,19 +3642,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3805,7 +3720,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3825,7 +3740,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4319,7 +4234,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4328,164 +4243,171 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; if (0 === (workInProgress.mode & 2)) for ( - nextDidTimeout = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; + nextProps.child = current$$1; + null !== current$$1; ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( - nextProps, + nextDidTimeout, mode, renderExpirationTime, null ); renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime + nextProps.sibling = renderExpirationTime; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - else { - if (null !== current$$1.memoizedState) + renderExpirationTime.return = workInProgress; if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - if (workInProgress.mode & 8) { - nextDidTimeout = 0; - for ( - suspenseContext = renderExpirationTime.child; - null !== suspenseContext; - - ) - (nextDidTimeout += suspenseContext.treeBaseDuration), - (suspenseContext = suspenseContext.sibling); - renderExpirationTime.treeBaseDuration = nextDidTimeout; - } - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { - nextDidTimeout = nextProps.fallback; - nextProps = createFiberFromFragment(null, mode, 0, null); - nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); - if (0 === (workInProgress.mode & 2)) + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) for ( - suspenseContext = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); if (workInProgress.mode & 8) { - suspenseContext = 0; - for (JSCompiler_temp = nextProps.child; null !== JSCompiler_temp; ) - (suspenseContext += JSCompiler_temp.treeBaseDuration), - (JSCompiler_temp = JSCompiler_temp.sibling); - nextProps.treeBaseDuration = suspenseContext; + nextDidTimeout = 0; + for (current$$1 = renderExpirationTime.child; null !== current$$1; ) + (nextDidTimeout += current$$1.treeBaseDuration), + (current$$1 = current$$1.sibling); + renderExpirationTime.treeBaseDuration = nextDidTimeout; } - renderExpirationTime = createFiberFromFragment( - nextDidTimeout, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime - ); - workInProgress.stateNode = current$$1.stateNode; + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + if (workInProgress.mode & 8) { + current$$1 = 0; + for (suspenseContext = nextProps.child; null !== suspenseContext; ) + (current$$1 += suspenseContext.treeBaseDuration), + (suspenseContext = suspenseContext.sibling); + nextProps.treeBaseDuration = current$$1; + } + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4495,14 +4417,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4519,24 +4443,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4553,7 +4470,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4562,9 +4479,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4578,33 +4495,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4619,9 +4545,11 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); profilerStartTime = -1; + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4646,10 +4574,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function(parent, workInProgress) { for (var node = workInProgress.child; null !== node; ) { if (5 === node.tag || 6 === node.tag) parent._children.push(node.stateNode); @@ -4701,7 +4629,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { : (_lastTailNode.sibling = null); } } -function completeWork(current, workInProgress, renderExpirationTime) { +function completeWork(current, workInProgress, renderExpirationTime$jscomp$0) { var newProps = workInProgress.pendingProps; switch (workInProgress.tag) { case 2: @@ -4717,12 +4645,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 3: popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); - newProps = workInProgress.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - workInProgress.effectTag &= -3; + current = workInProgress.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(workInProgress); break; case 5: @@ -4730,12 +4656,12 @@ function completeWork(current, workInProgress, renderExpirationTime) { var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - renderExpirationTime = workInProgress.type; + renderExpirationTime$jscomp$0 = workInProgress.type; if (null !== current && null != workInProgress.stateNode) updateHostComponent$1( current, workInProgress, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance ), @@ -4744,7 +4670,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { else if (newProps) { current = requiredContext(contextStackCursor$1.current); var tag = allocateTag(), - viewConfig = getViewConfigForType(renderExpirationTime), + viewConfig = getViewConfigForType(renderExpirationTime$jscomp$0), updatePayload = diffProperties( null, emptyObject, @@ -4761,20 +4687,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { instanceCache.set(tag, workInProgress); instanceProps.set(tag, newProps); appendAllChildren(viewConfig, workInProgress, !1, !1); + workInProgress.stateNode = viewConfig; finalizeInitialChildren( viewConfig, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance, current ) && (workInProgress.effectTag |= 4); - workInProgress.stateNode = viewConfig; null !== workInProgress.ref && (workInProgress.effectTag |= 128); } else if (null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -4787,15 +4711,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); else { if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); current = requiredContext(rootInstanceStackCursor.current); if (!requiredContext(contextStackCursor$1.current).isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") + throw Error( + "Text strings must be rendered within a component." ); rootContainerInstance = allocateTag(); ReactNativePrivateInterface.UIManager.createView( @@ -4815,37 +4737,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { newProps = workInProgress.memoizedState; if (0 !== (workInProgress.effectTag & 64)) return ( - (workInProgress.expirationTime = renderExpirationTime), workInProgress + (workInProgress.expirationTime = renderExpirationTime$jscomp$0), + workInProgress ); newProps = null !== newProps; rootContainerInstance = !1; null !== current && - ((renderExpirationTime = current.memoizedState), - (rootContainerInstance = null !== renderExpirationTime), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === renderExpirationTime || - ((renderExpirationTime = current.child.sibling), - null !== renderExpirationTime && + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && ((tag = workInProgress.firstEffect), null !== tag - ? ((workInProgress.firstEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = tag)) - : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = null)), - (renderExpirationTime.effectTag = 8)))); + ? ((workInProgress.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = tag)) + : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if (newProps && !rootContainerInstance && 0 !== (workInProgress.mode & 2)) if ( (null === current && !0 !== workInProgress.memoizedProps.unstable_avoidThisFallback) || - 0 !== (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } if (newProps || rootContainerInstance) workInProgress.effectTag |= 4; break; case 7: @@ -4868,8 +4800,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 17: isContextProvider(workInProgress.type) && popContext(workInProgress); break; - case 18: - break; case 19: pop(suspenseStackCursor, workInProgress); newProps = workInProgress.memoizedState; @@ -4892,8 +4822,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { null !== current && ((workInProgress.updateQueue = current), (workInProgress.effectTag |= 4)); - workInProgress.firstEffect = workInProgress.lastEffect = null; - current = renderExpirationTime; + null === newProps.lastEffect && + (workInProgress.firstEffect = null); + workInProgress.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; for (newProps = workInProgress.child; null !== newProps; ) (rootContainerInstance = newProps), (tag = current), @@ -4901,8 +4833,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.nextEffect = null), (rootContainerInstance.firstEffect = null), (rootContainerInstance.lastEffect = null), - (renderExpirationTime = rootContainerInstance.alternate), - null === renderExpirationTime + (renderExpirationTime$jscomp$0 = + rootContainerInstance.alternate), + null === renderExpirationTime$jscomp$0 ? ((rootContainerInstance.childExpirationTime = 0), (rootContainerInstance.expirationTime = tag), (rootContainerInstance.child = null), @@ -4913,18 +4846,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.selfBaseDuration = 0), (rootContainerInstance.treeBaseDuration = 0)) : ((rootContainerInstance.childExpirationTime = - renderExpirationTime.childExpirationTime), + renderExpirationTime$jscomp$0.childExpirationTime), (rootContainerInstance.expirationTime = - renderExpirationTime.expirationTime), + renderExpirationTime$jscomp$0.expirationTime), (rootContainerInstance.child = - renderExpirationTime.child), + renderExpirationTime$jscomp$0.child), (rootContainerInstance.memoizedProps = - renderExpirationTime.memoizedProps), + renderExpirationTime$jscomp$0.memoizedProps), (rootContainerInstance.memoizedState = - renderExpirationTime.memoizedState), + renderExpirationTime$jscomp$0.memoizedState), (rootContainerInstance.updateQueue = - renderExpirationTime.updateQueue), - (tag = renderExpirationTime.dependencies), + renderExpirationTime$jscomp$0.updateQueue), + (tag = renderExpirationTime$jscomp$0.dependencies), (rootContainerInstance.dependencies = null === tag ? null @@ -4934,14 +4867,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { responders: tag.responders }), (rootContainerInstance.selfBaseDuration = - renderExpirationTime.selfBaseDuration), + renderExpirationTime$jscomp$0.selfBaseDuration), (rootContainerInstance.treeBaseDuration = - renderExpirationTime.treeBaseDuration)), + renderExpirationTime$jscomp$0.treeBaseDuration)), (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, workInProgress ); return workInProgress.child; @@ -4955,24 +4887,24 @@ function completeWork(current, workInProgress, renderExpirationTime) { if ( ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((workInProgress.updateQueue = current), + (workInProgress.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((workInProgress.updateQueue = current), - (workInProgress.effectTag |= 4)); workInProgress = workInProgress.lastEffect = newProps.lastEffect; null !== workInProgress && (workInProgress.nextEffect = null); break; } } else now() > newProps.tailExpiration && - 1 < renderExpirationTime && + 1 < renderExpirationTime$jscomp$0 && ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), - (current = renderExpirationTime - 1), + (current = renderExpirationTime$jscomp$0 - 1), (workInProgress.expirationTime = workInProgress.childExpirationTime = current), null === spawnedWorkDuringRender ? (spawnedWorkDuringRender = [current]) @@ -4995,20 +4927,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { (newProps.lastEffect = workInProgress.lastEffect), (current.sibling = null), (newProps = suspenseStackCursor.current), - (newProps = rootContainerInstance - ? (newProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask), - push(suspenseStackCursor, newProps, workInProgress), + push( + suspenseStackCursor, + rootContainerInstance ? (newProps & 1) | 2 : newProps & 1, + workInProgress + ), current ); break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } return null; @@ -5018,8 +4953,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -5027,12 +4962,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -5040,13 +4973,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -5068,8 +4999,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -5077,7 +5008,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5127,24 +5058,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -5152,12 +5116,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5191,7 +5155,11 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { safelyDetachRef(current$$1$jscomp$0); break; case 4: - unmountHostComponents(current$$1$jscomp$0, renderPriorityLevel); + unmountHostComponents( + finishedRoot, + current$$1$jscomp$0, + renderPriorityLevel + ); } } function detachFiber(current$$1) { @@ -5220,10 +5188,8 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); } parent = parentFiber.stateNode; @@ -5240,10 +5206,8 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } parentFiber.effectTag & 16 && (parentFiber.effectTag &= -17); @@ -5279,9 +5243,7 @@ function commitPlacement(finishedWork) { if (parentFiber) if (isContainer) { if ("number" === typeof parent) - throw ReactError( - Error("Container does not support insertBefore operation") - ); + throw Error("Container does not support insertBefore operation"); } else { isHost = parent; var beforeChild = parentFiber, @@ -5358,12 +5320,16 @@ function commitPlacement(finishedWork) { node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { +function unmountHostComponents( + finishedRoot$jscomp$0, + current$$1, + renderPriorityLevel$jscomp$0 +) { for ( var node = current$$1, currentParentIsValid = !1, - currentParent = void 0, - currentParentIsContainer = void 0; + currentParent, + currentParentIsContainer; ; ) { @@ -5371,10 +5337,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { currentParentIsValid = node.return; a: for (;;) { if (null === currentParentIsValid) - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); currentParent = currentParentIsValid.stateNode; switch (currentParentIsValid.tag) { @@ -5396,14 +5360,15 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { } if (5 === node.tag || 6 === node.tag) { a: for ( - var root = node, + var finishedRoot = finishedRoot$jscomp$0, + root = node, renderPriorityLevel = renderPriorityLevel$jscomp$0, node$jscomp$0 = root; ; ) if ( - (commitUnmount(node$jscomp$0, renderPriorityLevel), + (commitUnmount(finishedRoot, node$jscomp$0, renderPriorityLevel), null !== node$jscomp$0.child && 4 !== node$jscomp$0.tag) ) (node$jscomp$0.child.return = node$jscomp$0), @@ -5419,29 +5384,29 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { node$jscomp$0 = node$jscomp$0.sibling; } currentParentIsContainer - ? ((root = currentParent), + ? ((finishedRoot = currentParent), recursivelyUncacheFiberNode(node.stateNode), ReactNativePrivateInterface.UIManager.manageChildren( - root, + finishedRoot, [], [], [], [], [0] )) - : ((root = currentParent), - (node$jscomp$0 = node.stateNode), - recursivelyUncacheFiberNode(node$jscomp$0), - (renderPriorityLevel = root._children), - (node$jscomp$0 = renderPriorityLevel.indexOf(node$jscomp$0)), - renderPriorityLevel.splice(node$jscomp$0, 1), + : ((finishedRoot = currentParent), + (renderPriorityLevel = node.stateNode), + recursivelyUncacheFiberNode(renderPriorityLevel), + (root = finishedRoot._children), + (renderPriorityLevel = root.indexOf(renderPriorityLevel)), + root.splice(renderPriorityLevel, 1), ReactNativePrivateInterface.UIManager.manageChildren( - root._nativeTag, + finishedRoot._nativeTag, [], [], [], [], - [node$jscomp$0] + [renderPriorityLevel] )); } else if (4 === node.tag) { if (null !== node.child) { @@ -5452,7 +5417,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { continue; } } else if ( - (commitUnmount(node, renderPriorityLevel$jscomp$0), null !== node.child) + (commitUnmount(finishedRoot$jscomp$0, node, renderPriorityLevel$jscomp$0), + null !== node.child) ) { node.child.return = node; node = node.child; @@ -5474,7 +5440,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5504,10 +5470,8 @@ function commitWork(current$$1, finishedWork) { break; case 6: if (null === finishedWork.stateNode) - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." ); ReactNativePrivateInterface.UIManager.updateView( finishedWork.stateNode, @@ -5563,7 +5527,11 @@ function commitWork(current$$1, finishedWork) { } else { if (6 === current$$1.tag) throw Error("Not yet implemented."); - if (13 === current$$1.tag && null !== current$$1.memoizedState) { + if ( + 13 === current$$1.tag && + null !== current$$1.memoizedState && + null === current$$1.memoizedState.dehydrated + ) { updatePayload = current$$1.child.sibling; updatePayload.return = current$$1; current$$1 = updatePayload; @@ -5592,11 +5560,11 @@ function commitWork(current$$1, finishedWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5606,11 +5574,12 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || - ((retry = tracing.unstable_wrap(retry)), + (!0 !== thenable.__reactDoNotTraceInteractions && + (retry = tracing.unstable_wrap(retry)), retryCache.add(thenable), thenable.then(retry, retry)); }); @@ -5663,18 +5632,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5730,10 +5702,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5744,35 +5716,22 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - scheduleInteractions( - fiber, - expirationTime, - tracing.__interactionsRef.current - ); - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - } else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? (schedulePendingInteractions(fiber, expirationTime), + performSyncWorkOnRoot(fiber)) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime), + executionContext === NoContext && flushSyncCallbackQueue()) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime)); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5807,79 +5766,330 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var currentTime = requestCurrentTime(); + currentTime = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= currentTime + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = currentTime; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + currentTime, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } - scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) + prepareFreshStack(root, expirationTime), + startWorkOnPendingInteractions(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if ( + workInProgressRootHasPendingPing && + ((prevInteractions = root.lastPingedTime), + 0 === prevInteractions || prevInteractions >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevInteractions = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevInteractions && prevInteractions !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + prevInteractions = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (prevInteractions = + now() - + (10 * (1073741821 - prevInteractions) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + prevInteractions <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + prevInteractions)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || lastExpiredTime !== renderExpirationTime) + prepareFreshStack(root, lastExpiredTime), + startWorkOnPendingInteractions(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5925,354 +6135,196 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; spawnedWorkDuringRender = null; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime), - startWorkOnPendingInteractions(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root$jscomp$0.memoizedInteractions; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - (tracing.__interactionsRef.current = prevInteractions), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - currentTime.mode & 8 && - stopProfilerTimerIfRunningAndRecordDelta(currentTime, !0); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + workInProgress.mode & 8 && + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, !0); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - (sourceFiber = tracing.unstable_wrap(sourceFiber)), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - tracing.__interactionsRef.current = prevInteractions; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function pushInteractions(root) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var current$$1 = unitOfWork.alternate; 0 !== (unitOfWork.mode & 8) @@ -6291,7 +6343,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { if (0 === (workInProgress.mode & 8)) current$$1 = completeWork( current$$1, @@ -6350,7 +6402,7 @@ function completeUnitOfWork(unitOfWork) { } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6377,10 +6429,10 @@ function completeUnitOfWork(unitOfWork) { workInProgress.actualDuration = fiber; } if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6390,134 +6442,90 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$0, renderPriorityLevel$jscomp$0) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$0.finishedWork, + expirationTime = root$jscomp$0.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$0.finishedWork = null; + root$jscomp$0.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$0.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$0.callbackNode = null; + root$jscomp$0.callbackExpirationTime = 0; + root$jscomp$0.callbackPriority = 90; + root$jscomp$0.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$0.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$0.lastSuspendedTime + ? (root$jscomp$0.firstSuspendedTime = root$jscomp$0.lastSuspendedTime = root$jscomp$0.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$0.firstSuspendedTime && + (root$jscomp$0.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$0.lastPingedTime && + (root$jscomp$0.lastPingedTime = 0); + expirationTime <= root$jscomp$0.lastExpiredTime && + (root$jscomp$0.lastExpiredTime = 0); + root$jscomp$0 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + var prevInteractions = pushInteractions(root$jscomp$0); ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); commitTime = now$1(); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$0, + renderPriorityLevel = renderPriorityLevel$jscomp$0; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: commitPlacement(nextEffect); nextEffect.effectTag &= -3; @@ -6527,89 +6535,94 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - (prevProps = nextEffect), - unmountHostComponents(prevProps, current$$1), - detachFiber(prevProps); + var current$$1$jscomp$0 = nextEffect; + unmountHostComponents( + root, + current$$1$jscomp$0, + renderPriorityLevel + ); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$0.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for ( - effectTag = root, current$$1$jscomp$0 = expirationTime; + effectTag = root$jscomp$0, current$$1 = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { - prevProps = effectTag; + renderPriorityLevel = effectTag; var current$$1$jscomp$1 = nextEffect.alternate; currentRef = nextEffect; - current$$1 = current$$1$jscomp$0; + root = current$$1; switch (currentRef.tag) { case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, currentRef); + commitHookEffectList(16, 32, currentRef); break; case 1: - var instance$jscomp$0 = currentRef.stateNode; + var instance = currentRef.stateNode; if (currentRef.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = + var prevProps = currentRef.elementType === currentRef.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( currentRef.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } var updateQueue = currentRef.updateQueue; null !== updateQueue && - commitUpdateQueue( - currentRef, - updateQueue, - instance$jscomp$0, - current$$1 - ); + commitUpdateQueue(currentRef, updateQueue, instance, root); break; case 3: var _updateQueue = currentRef.updateQueue; if (null !== _updateQueue) { - prevProps = null; + renderPriorityLevel = null; if (null !== currentRef.child) switch (currentRef.child.tag) { case 5: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; break; case 1: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; } commitUpdateQueue( currentRef, _updateQueue, - prevProps, - current$$1 + renderPriorityLevel, + root ); } break; @@ -6629,44 +6642,43 @@ function commitRootImpl(root, renderPriorityLevel) { currentRef.treeBaseDuration, currentRef.actualStartTime, commitTime, - prevProps.memoizedInteractions + renderPriorityLevel.memoizedInteractions ); break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + currentRef = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; break; default: - instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(currentRef) + : (ref.current = currentRef); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } @@ -6674,80 +6686,99 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect = null; requestPaint(); tracing.__interactionsRef.current = prevInteractions; - executionContext = childExpirationTimeBeforeCommit; - } else (root.current = finishedWork), (commitTime = now$1()); + executionContext = prevExecutionContext; + } else (root$jscomp$0.current = finishedWork), (commitTime = now$1()); if ((effectTag$jscomp$0 = rootDoesHavePassiveEffects)) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), + (rootWithPendingPassiveEffects = root$jscomp$0), (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$0); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$0 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - if (0 !== renderPriorityLevel) { - current$$1$jscomp$1 = requestCurrentTime(); - current$$1$jscomp$1 = inferPriorityFromExpirationTime( - current$$1$jscomp$1, - renderPriorityLevel - ); + (nextEffect = renderPriorityLevel$jscomp$0); + renderPriorityLevel$jscomp$0 = root$jscomp$0.firstPendingTime; + if (0 !== renderPriorityLevel$jscomp$0) { if (null !== spawnedWorkDuringRender) for ( - instance$jscomp$0 = spawnedWorkDuringRender, + remainingExpirationTimeBeforeCommit = spawnedWorkDuringRender, spawnedWorkDuringRender = null, - prevProps$jscomp$0 = 0; - prevProps$jscomp$0 < instance$jscomp$0.length; - prevProps$jscomp$0++ + current$$1$jscomp$1 = 0; + current$$1$jscomp$1 < remainingExpirationTimeBeforeCommit.length; + current$$1$jscomp$1++ ) scheduleInteractions( - root, - instance$jscomp$0[prevProps$jscomp$0], - root.memoizedInteractions + root$jscomp$0, + remainingExpirationTimeBeforeCommit[current$$1$jscomp$1], + root$jscomp$0.memoizedInteractions ); - scheduleCallbackForRoot(root, current$$1$jscomp$1, renderPriorityLevel); + schedulePendingInteractions(root$jscomp$0, renderPriorityLevel$jscomp$0); } else legacyErrorBoundariesThatAlreadyFailed = null; - effectTag$jscomp$0 || finishPendingInteractions(root, expirationTime); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + effectTag$jscomp$0 || + finishPendingInteractions(root$jscomp$0, expirationTime); + 1073741823 === renderPriorityLevel$jscomp$0 + ? root$jscomp$0 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$0)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$0); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$0 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$0); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + expirationTime = pendingPassiveEffectsExpirationTime; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; - for (var effect = root.current.firstEffect; null !== effect; ) { + for ( + var prevInteractions = pushInteractions(root), + effect = root.current.firstEffect; + null !== effect; + + ) { try { var finishedWork = effect; if (0 !== (finishedWork.effectTag & 512)) @@ -6755,12 +6786,11 @@ function flushPassiveEffectsImpl(root, expirationTime) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === effect) - throw ReactError(Error("Should be working on an effect.")); + if (null === effect) throw Error("Should be working on an effect."); captureCommitPhaseError(effect, error); } finishedWork = effect.nextEffect; @@ -6778,7 +6808,9 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && + (ensureRootIsScheduled(rootFiber), + schedulePendingInteractions(rootFiber, 1073741823)); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6800,7 +6832,9 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && + (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, 1073741823)); break; } } @@ -6817,27 +6851,28 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root), + schedulePendingInteractions(root, suspendedTime))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + (ensureRootIsScheduled(boundaryFiber), + schedulePendingInteractions(boundaryFiber, thenable)); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6886,7 +6921,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6898,7 +6933,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6930,6 +6965,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -7014,7 +7050,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -7057,12 +7095,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -7102,10 +7138,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -7143,7 +7177,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7234,7 +7269,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7423,10 +7458,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; function scheduleInteractions(root, expirationTime, interactions) { @@ -7450,6 +7485,9 @@ function scheduleInteractions(root, expirationTime, interactions) { ); } } +function schedulePendingInteractions(root, expirationTime) { + scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); +} function startWorkOnPendingInteractions(root, expirationTime) { var interactions = new Set(); root.pendingInteractionMap.forEach(function( @@ -7477,13 +7515,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { } } function finishPendingInteractions(root, committedExpirationTime) { - var earliestRemainingTimeAfterCommit = root.firstPendingTime, - subscriber = void 0; + var earliestRemainingTimeAfterCommit = root.firstPendingTime; try { - if ( - ((subscriber = tracing.__subscriberRef.current), - null !== subscriber && 0 < root.memoizedInteractions.size) - ) + var subscriber = tracing.__subscriberRef.current; + if (null !== subscriber && 0 < root.memoizedInteractions.size) subscriber.onWorkStopped( root.memoizedInteractions, 1e3 * committedExpirationTime + root.interactionThreadID @@ -7691,12 +7726,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7740,22 +7773,57 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; +} function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7765,23 +7833,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7799,10 +7864,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7821,14 +7884,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7841,31 +7903,11 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; if ("number" === typeof componentOrHandle) return componentOrHandle; @@ -7898,33 +7940,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7937,10 +7969,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7953,34 +7984,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8060,9 +8089,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -8076,9 +8104,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -8092,29 +8119,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8181,9 +8206,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromTag, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js b/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js index 9f45fca0b7182a..0403ddc9924a15 100644 --- a/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js +++ b/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js @@ -15,12 +15,8 @@ require("react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore"); var ReactNativePrivateInterface = require("react-native/Libraries/ReactPrivate/ReactNativePrivateInterface"), React = require("react"), Scheduler = require("scheduler"), - tracing = require("scheduler/tracing"); -function ReactError(error) { - error.name = "Invariant Violation"; - return error; -} -var eventPluginOrder = null, + tracing = require("scheduler/tracing"), + eventPluginOrder = null, namesToPlugins = {}; function recomputePluginOrdering() { if (eventPluginOrder) @@ -28,21 +24,17 @@ function recomputePluginOrdering() { var pluginModule = namesToPlugins[pluginName], pluginIndex = eventPluginOrder.indexOf(pluginName); if (!(-1 < pluginIndex)) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." ); if (!plugins[pluginIndex]) { if (!pluginModule.extractEvents) - throw ReactError( - Error( - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + - pluginName + - "` does not." - ) + throw Error( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." ); plugins[pluginIndex] = pluginModule; pluginIndex = pluginModule.eventTypes; @@ -52,12 +44,10 @@ function recomputePluginOrdering() { pluginModule$jscomp$0 = pluginModule, eventName$jscomp$0 = eventName; if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same event name, `" + - eventName$jscomp$0 + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." ); eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; @@ -82,14 +72,12 @@ function recomputePluginOrdering() { (JSCompiler_inline_result = !0)) : (JSCompiler_inline_result = !1); if (!JSCompiler_inline_result) - throw ReactError( - Error( - "EventPluginRegistry: Failed to publish event `" + - eventName + - "` for plugin `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." ); } } @@ -97,12 +85,10 @@ function recomputePluginOrdering() { } function publishRegistrationName(registrationName, pluginModule) { if (registrationNameModules[registrationName]) - throw ReactError( - Error( - "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + - registrationName + - "`." - ) + throw Error( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." ); registrationNameModules[registrationName] = pluginModule; } @@ -150,10 +136,8 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - throw ReactError( - Error( - "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } @@ -171,7 +155,7 @@ function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; if (Array.isArray(dispatchListener)) - throw ReactError(Error("executeDirectDispatch(...): Invalid `event`.")); + throw Error("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -183,10 +167,8 @@ function executeDirectDispatch(event) { } function accumulateInto(current, next) { if (null == next) - throw ReactError( - Error( - "accumulateInto(...): Accumulated items must not be null or undefined." - ) + throw Error( + "accumulateInto(...): Accumulated items must not be null or undefined." ); if (null == current) return next; if (Array.isArray(current)) { @@ -222,10 +204,8 @@ function executeDispatchesAndReleaseTopLevel(e) { var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { if (eventPluginOrder) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ) + throw Error( + "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); @@ -241,12 +221,10 @@ var injection = { namesToPlugins[pluginName] !== pluginModule ) { if (namesToPlugins[pluginName]) - throw ReactError( - Error( - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + - pluginName + - "`." - ) + throw Error( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = !0; @@ -287,14 +265,12 @@ function getListener(inst, registrationName) { } if (inst) return null; if (listener && "function" !== typeof listener) - throw ReactError( - Error( - "Expected `" + - registrationName + - "` listener to be a function, instead got a value of `" + - typeof listener + - "` type." - ) + throw Error( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." ); return listener; } @@ -457,10 +433,8 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { } function releasePooledEvent(event) { if (!(event instanceof this)) - throw ReactError( - Error( - "Trying to release an event instance into a pool of a different type." - ) + throw Error( + "Trying to release an event instance into a pool of a different type." ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); @@ -496,8 +470,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - if (null == _ref) - throw ReactError(Error("Touch object is missing identifier.")); + if (null == _ref) throw Error("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -611,8 +584,8 @@ var ResponderTouchHistoryStore = { }; function accumulate(current, next) { if (null == next) - throw ReactError( - Error("accumulate(...): Accumulated items must not be null or undefined.") + throw Error( + "accumulate(...): Accumulated items must not be null or undefined." ); return null == current ? next @@ -712,7 +685,7 @@ var eventTypes = { if (0 <= trackedTouchCount) --trackedTouchCount; else return ( - console.error( + console.warn( "Ended a touch event which was not counted in `trackedTouchCount`." ), null @@ -725,7 +698,7 @@ var eventTypes = { isStartish(topLevelType) || isMoveish(topLevelType)) ) { - var JSCompiler_temp = isStartish(topLevelType) + var shouldSetEventType = isStartish(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder @@ -734,9 +707,9 @@ var eventTypes = { : eventTypes.scrollShouldSetResponder; if (responderInst) b: { - var JSCompiler_temp$jscomp$0 = responderInst; + var JSCompiler_temp = responderInst; for ( - var depthA = 0, tempA = JSCompiler_temp$jscomp$0; + var depthA = 0, tempA = JSCompiler_temp; tempA; tempA = getParent(tempA) ) @@ -745,194 +718,202 @@ var eventTypes = { for (var tempB = targetInst; tempB; tempB = getParent(tempB)) tempA++; for (; 0 < depthA - tempA; ) - (JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0)), - depthA--; + (JSCompiler_temp = getParent(JSCompiler_temp)), depthA--; for (; 0 < tempA - depthA; ) (targetInst = getParent(targetInst)), tempA--; for (; depthA--; ) { if ( - JSCompiler_temp$jscomp$0 === targetInst || - JSCompiler_temp$jscomp$0 === targetInst.alternate + JSCompiler_temp === targetInst || + JSCompiler_temp === targetInst.alternate ) break b; - JSCompiler_temp$jscomp$0 = getParent(JSCompiler_temp$jscomp$0); + JSCompiler_temp = getParent(JSCompiler_temp); targetInst = getParent(targetInst); } - JSCompiler_temp$jscomp$0 = null; + JSCompiler_temp = null; } - else JSCompiler_temp$jscomp$0 = targetInst; - targetInst = JSCompiler_temp$jscomp$0 === responderInst; - JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( + else JSCompiler_temp = targetInst; + targetInst = JSCompiler_temp === responderInst; + JSCompiler_temp = ResponderSyntheticEvent.getPooled( + shouldSetEventType, JSCompiler_temp, - JSCompiler_temp$jscomp$0, nativeEvent, nativeEventTarget ); - JSCompiler_temp$jscomp$0.touchHistory = - ResponderTouchHistoryStore.touchHistory; + JSCompiler_temp.touchHistory = ResponderTouchHistoryStore.touchHistory; targetInst ? forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingleSkipTarget ) : forEachAccumulated( - JSCompiler_temp$jscomp$0, + JSCompiler_temp, accumulateTwoPhaseDispatchesSingle ); b: { - JSCompiler_temp = JSCompiler_temp$jscomp$0._dispatchListeners; - targetInst = JSCompiler_temp$jscomp$0._dispatchInstances; - if (Array.isArray(JSCompiler_temp)) + shouldSetEventType = JSCompiler_temp._dispatchListeners; + targetInst = JSCompiler_temp._dispatchInstances; + if (Array.isArray(shouldSetEventType)) for ( depthA = 0; - depthA < JSCompiler_temp.length && - !JSCompiler_temp$jscomp$0.isPropagationStopped(); + depthA < shouldSetEventType.length && + !JSCompiler_temp.isPropagationStopped(); depthA++ ) { if ( - JSCompiler_temp[depthA]( - JSCompiler_temp$jscomp$0, - targetInst[depthA] - ) + shouldSetEventType[depthA](JSCompiler_temp, targetInst[depthA]) ) { - JSCompiler_temp = targetInst[depthA]; + shouldSetEventType = targetInst[depthA]; break b; } } else if ( - JSCompiler_temp && - JSCompiler_temp(JSCompiler_temp$jscomp$0, targetInst) + shouldSetEventType && + shouldSetEventType(JSCompiler_temp, targetInst) ) { - JSCompiler_temp = targetInst; + shouldSetEventType = targetInst; break b; } - JSCompiler_temp = null; + shouldSetEventType = null; } - JSCompiler_temp$jscomp$0._dispatchInstances = null; - JSCompiler_temp$jscomp$0._dispatchListeners = null; - JSCompiler_temp$jscomp$0.isPersistent() || - JSCompiler_temp$jscomp$0.constructor.release( - JSCompiler_temp$jscomp$0 - ); - JSCompiler_temp && JSCompiler_temp !== responderInst - ? ((JSCompiler_temp$jscomp$0 = void 0), - (targetInst = ResponderSyntheticEvent.getPooled( + JSCompiler_temp._dispatchInstances = null; + JSCompiler_temp._dispatchListeners = null; + JSCompiler_temp.isPersistent() || + JSCompiler_temp.constructor.release(JSCompiler_temp); + if (shouldSetEventType && shouldSetEventType !== responderInst) + if ( + ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, - JSCompiler_temp, + shouldSetEventType, nativeEvent, nativeEventTarget )), - (targetInst.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(targetInst, accumulateDirectDispatchesSingle), - (depthA = !0 === executeDirectDispatch(targetInst)), - responderInst - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminationRequest, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (tempB = - !tempA._dispatchListeners || executeDirectDispatch(tempA)), - tempA.isPersistent() || tempA.constructor.release(tempA), - tempB - ? ((tempA = ResponderSyntheticEvent.getPooled( - eventTypes.responderTerminate, - responderInst, - nativeEvent, - nativeEventTarget - )), - (tempA.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated(tempA, accumulateDirectDispatchesSingle), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - [targetInst, tempA] - )), - changeResponder(JSCompiler_temp, depthA)) - : ((JSCompiler_temp = ResponderSyntheticEvent.getPooled( - eventTypes.responderReject, - JSCompiler_temp, - nativeEvent, - nativeEventTarget - )), - (JSCompiler_temp.touchHistory = - ResponderTouchHistoryStore.touchHistory), - forEachAccumulated( - JSCompiler_temp, - accumulateDirectDispatchesSingle - ), - (JSCompiler_temp$jscomp$0 = accumulate( - JSCompiler_temp$jscomp$0, - JSCompiler_temp - )))) - : ((JSCompiler_temp$jscomp$0 = accumulate( + (JSCompiler_temp.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + JSCompiler_temp, + accumulateDirectDispatchesSingle + ), + (targetInst = !0 === executeDirectDispatch(JSCompiler_temp)), + responderInst) + ) + if ( + ((depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminationRequest, + responderInst, + nativeEvent, + nativeEventTarget + )), + (depthA.touchHistory = ResponderTouchHistoryStore.touchHistory), + forEachAccumulated(depthA, accumulateDirectDispatchesSingle), + (tempA = + !depthA._dispatchListeners || executeDirectDispatch(depthA)), + depthA.isPersistent() || depthA.constructor.release(depthA), + tempA) + ) { + depthA = ResponderSyntheticEvent.getPooled( + eventTypes.responderTerminate, + responderInst, + nativeEvent, + nativeEventTarget + ); + depthA.touchHistory = ResponderTouchHistoryStore.touchHistory; + forEachAccumulated(depthA, accumulateDirectDispatchesSingle); + var JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + [JSCompiler_temp, depthA] + ); + changeResponder(shouldSetEventType, targetInst); + } else + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + eventTypes.responderReject, + shouldSetEventType, + nativeEvent, + nativeEventTarget + )), + (shouldSetEventType.touchHistory = + ResponderTouchHistoryStore.touchHistory), + forEachAccumulated( + shouldSetEventType, + accumulateDirectDispatchesSingle + ), + (JSCompiler_temp$jscomp$0 = accumulate( JSCompiler_temp$jscomp$0, - targetInst - )), - changeResponder(JSCompiler_temp, depthA)), - (JSCompiler_temp = JSCompiler_temp$jscomp$0)) - : (JSCompiler_temp = null); - } else JSCompiler_temp = null; - JSCompiler_temp$jscomp$0 = responderInst && isStartish(topLevelType); - targetInst = responderInst && isMoveish(topLevelType); - depthA = + shouldSetEventType + )); + else + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + JSCompiler_temp + )), + changeResponder(shouldSetEventType, targetInst); + else JSCompiler_temp$jscomp$0 = null; + } else JSCompiler_temp$jscomp$0 = null; + shouldSetEventType = responderInst && isStartish(topLevelType); + JSCompiler_temp = responderInst && isMoveish(topLevelType); + targetInst = responderInst && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType); if ( - (JSCompiler_temp$jscomp$0 = JSCompiler_temp$jscomp$0 + (shouldSetEventType = shouldSetEventType ? eventTypes.responderStart - : targetInst + : JSCompiler_temp ? eventTypes.responderMove - : depthA + : targetInst ? eventTypes.responderEnd : null) ) - (JSCompiler_temp$jscomp$0 = ResponderSyntheticEvent.getPooled( - JSCompiler_temp$jscomp$0, + (shouldSetEventType = ResponderSyntheticEvent.getPooled( + shouldSetEventType, responderInst, nativeEvent, nativeEventTarget )), - (JSCompiler_temp$jscomp$0.touchHistory = + (shouldSetEventType.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated( - JSCompiler_temp$jscomp$0, + shouldSetEventType, accumulateDirectDispatchesSingle ), - (JSCompiler_temp = accumulate( - JSCompiler_temp, - JSCompiler_temp$jscomp$0 + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + shouldSetEventType )); - JSCompiler_temp$jscomp$0 = - responderInst && "topTouchCancel" === topLevelType; + shouldSetEventType = responderInst && "topTouchCancel" === topLevelType; if ( (topLevelType = responderInst && - !JSCompiler_temp$jscomp$0 && + !shouldSetEventType && ("topTouchEnd" === topLevelType || "topTouchCancel" === topLevelType)) ) a: { if ((topLevelType = nativeEvent.touches) && 0 !== topLevelType.length) - for (targetInst = 0; targetInst < topLevelType.length; targetInst++) + for ( + JSCompiler_temp = 0; + JSCompiler_temp < topLevelType.length; + JSCompiler_temp++ + ) if ( - ((depthA = topLevelType[targetInst].target), - null !== depthA && void 0 !== depthA && 0 !== depthA) + ((targetInst = topLevelType[JSCompiler_temp].target), + null !== targetInst && + void 0 !== targetInst && + 0 !== targetInst) ) { - tempA = getInstanceFromNode(depthA); + depthA = getInstanceFromNode(targetInst); b: { - for (depthA = responderInst; tempA; ) { - if (depthA === tempA || depthA === tempA.alternate) { - depthA = !0; + for (targetInst = responderInst; depthA; ) { + if ( + targetInst === depthA || + targetInst === depthA.alternate + ) { + targetInst = !0; break b; } - tempA = getParent(tempA); + depthA = getParent(depthA); } - depthA = !1; + targetInst = !1; } - if (depthA) { + if (targetInst) { topLevelType = !1; break a; } @@ -940,7 +921,7 @@ var eventTypes = { topLevelType = !0; } if ( - (topLevelType = JSCompiler_temp$jscomp$0 + (topLevelType = shouldSetEventType ? eventTypes.responderTerminate : topLevelType ? eventTypes.responderRelease @@ -954,9 +935,12 @@ var eventTypes = { )), (nativeEvent.touchHistory = ResponderTouchHistoryStore.touchHistory), forEachAccumulated(nativeEvent, accumulateDirectDispatchesSingle), - (JSCompiler_temp = accumulate(JSCompiler_temp, nativeEvent)), + (JSCompiler_temp$jscomp$0 = accumulate( + JSCompiler_temp$jscomp$0, + nativeEvent + )), changeResponder(null); - return JSCompiler_temp; + return JSCompiler_temp$jscomp$0; }, GlobalResponderHandler: null, injection: { @@ -989,10 +973,8 @@ injection.injectEventPluginsByName({ var bubbleDispatchConfig = customBubblingEventTypes[topLevelType], directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) - throw ReactError( - Error( - 'Unsupported top level event type "' + topLevelType + '" dispatched' - ) + throw Error( + 'Unsupported top level event type "' + topLevelType + '" dispatched' ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, @@ -1018,10 +1000,8 @@ var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { if (getInstanceFromNode(target)) - throw ReactError( - Error( - "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } function batchedUpdatesImpl(fn, bookkeeping) { @@ -1065,7 +1045,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { topLevelType, inst, nativeEvent, - events + events, + 1 )) && (events$jscomp$0 = accumulateInto(events$jscomp$0, possiblePlugin)); } @@ -1076,10 +1057,8 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { if (events) { forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); if (eventQueue) - throw ReactError( - Error( - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ) + throw Error( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); if (hasRethrowError) throw ((events = rethrowError), @@ -1133,7 +1112,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - if (!tag) throw ReactError(Error("All native instances should have a tag.")); + if (!tag) throw Error("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1172,6 +1151,7 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; hasSymbol && Symbol.for("react.fundamental"); hasSymbol && Symbol.for("react.responder"); +hasSymbol && Symbol.for("react.scope"); var MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1180,6 +1160,26 @@ function getIteratorFn(maybeIterable) { maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } +function initializeLazyComponentType(lazyComponent) { + if (-1 === lazyComponent._status) { + lazyComponent._status = 0; + var ctor = lazyComponent._ctor; + ctor = ctor(); + lazyComponent._result = ctor; + ctor.then( + function(moduleObject) { + 0 === lazyComponent._status && + ((moduleObject = moduleObject.default), + (lazyComponent._status = 1), + (lazyComponent._result = moduleObject)); + }, + function(error) { + 0 === lazyComponent._status && + ((lazyComponent._status = 2), (lazyComponent._result = error)); + } + ); + } +} function getComponentName(type) { if (null == type) return null; if ("function" === typeof type) return type.displayName || type.name || null; @@ -1219,27 +1219,31 @@ function getComponentName(type) { } return null; } -function isFiberMountedImpl(fiber) { - var node = fiber; +function getNearestMountedFiber(fiber) { + var node = fiber, + nearestMounted = fiber; if (fiber.alternate) for (; node.return; ) node = node.return; else { - if (0 !== (node.effectTag & 2)) return 1; - for (; node.return; ) - if (((node = node.return), 0 !== (node.effectTag & 2))) return 1; + fiber = node; + do + (node = fiber), + 0 !== (node.effectTag & 1026) && (nearestMounted = node.return), + (fiber = node.return); + while (fiber); } - return 3 === node.tag ? 2 : 3; + return 3 === node.tag ? nearestMounted : null; } function assertIsMounted(fiber) { - if (2 !== isFiberMountedImpl(fiber)) - throw ReactError(Error("Unable to find node on an unmounted component.")); + if (getNearestMountedFiber(fiber) !== fiber) + throw Error("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { - alternate = isFiberMountedImpl(fiber); - if (3 === alternate) - throw ReactError(Error("Unable to find node on an unmounted component.")); - return 1 === alternate ? null : fiber; + alternate = getNearestMountedFiber(fiber); + if (null === alternate) + throw Error("Unable to find node on an unmounted component."); + return alternate !== fiber ? null : fiber; } for (var a = fiber, b = alternate; ; ) { var parentA = a.return; @@ -1259,7 +1263,7 @@ function findCurrentFiberUsingSlowPath(fiber) { if (parentB === b) return assertIsMounted(parentA), alternate; parentB = parentB.sibling; } - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { @@ -1295,22 +1299,18 @@ function findCurrentFiberUsingSlowPath(fiber) { _child = _child.sibling; } if (!didFindChild) - throw ReactError( - Error( - "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." - ) + 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." ); } } if (a.alternate !== b) - throw ReactError( - Error( - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); } if (3 !== a.tag) - throw ReactError(Error("Unable to find node on an unmounted component.")); + throw Error("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1560,43 +1560,35 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) { } var ReactNativeFiberHostComponent = (function() { function ReactNativeFiberHostComponent(tag, viewConfig) { - if (!(this instanceof ReactNativeFiberHostComponent)) - throw new TypeError("Cannot call a class as a function"); this._nativeTag = tag; this._children = []; this.viewConfig = viewConfig; } - ReactNativeFiberHostComponent.prototype.blur = function() { + var _proto = ReactNativeFiberHostComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { + _proto.measure = function(callback) { ReactNativePrivateInterface.UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + _proto.measureInWindow = function(callback) { ReactNativePrivateInterface.UIManager.measureInWindow( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { - var relativeNode = void 0; - "number" === typeof relativeToNativeNode - ? (relativeNode = relativeToNativeNode) - : relativeToNativeNode._nativeTag - ? (relativeNode = relativeToNativeNode._nativeTag) - : relativeToNativeNode.canonical && - relativeToNativeNode.canonical._nativeTag && - (relativeNode = relativeToNativeNode.canonical._nativeTag); + _proto.measureLayout = function(relativeToNativeNode, onSuccess, onFail) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( this._nativeTag, @@ -1605,9 +1597,7 @@ var ReactNativeFiberHostComponent = (function() { mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { + _proto.setNativeProps = function(nativeProps) { nativeProps = diffProperties( null, emptyObject, @@ -1624,10 +1614,8 @@ var ReactNativeFiberHostComponent = (function() { return ReactNativeFiberHostComponent; })(); function shim$1() { - throw ReactError( - Error( - "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } var getViewConfigForType = @@ -1748,10 +1736,8 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { if (contextStackCursor.current !== emptyContextObject) - throw ReactError( - Error( - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." ); push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); @@ -1763,15 +1749,13 @@ function processChildContext(fiber, type, parentContext) { instance = instance.getChildContext(); for (var contextKey in instance) if (!(contextKey in fiber)) - throw ReactError( - Error( - (getComponentName(type) || "Unknown") + - '.getChildContext(): key "' + - contextKey + - '" is not defined in childContextTypes.' - ) + throw Error( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' ); - return Object.assign({}, parentContext, instance); + return Object.assign({}, parentContext, {}, instance); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; @@ -1790,10 +1774,8 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; if (!instance) - throw ReactError( - Error( - "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." ); didChange ? ((type = processChildContext(workInProgress, type, previousContext)), @@ -1821,10 +1803,8 @@ if ( null == tracing.__interactionsRef || null == tracing.__interactionsRef.current ) - throw ReactError( - Error( - "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" - ) + 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" ); var fakeCallbackNode = {}, requestPaint = @@ -1852,7 +1832,7 @@ function getCurrentPriorityLevel() { case Scheduler_IdlePriority: return 95; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function reactPriorityToSchedulerPriority(reactPriorityLevel) { @@ -1868,7 +1848,7 @@ function reactPriorityToSchedulerPriority(reactPriorityLevel) { case 95: return Scheduler_IdlePriority; default: - throw ReactError(Error("Unknown priority level.")); + throw Error("Unknown priority level."); } } function runWithPriority(reactPriorityLevel, fn) { @@ -1890,8 +1870,11 @@ function scheduleSyncCallback(callback) { return fakeCallbackNode; } function flushSyncCallbackQueue() { - null !== immediateQueueCallbackNode && - Scheduler_cancelCallback(immediateQueueCallbackNode); + if (null !== immediateQueueCallbackNode) { + var node = immediateQueueCallbackNode; + immediateQueueCallbackNode = null; + Scheduler_cancelCallback(node); + } flushSyncCallbackQueueImpl(); } function flushSyncCallbackQueueImpl() { @@ -1922,7 +1905,7 @@ function flushSyncCallbackQueueImpl() { } function inferPriorityFromExpirationTime(currentTime, expirationTime) { if (1073741823 === expirationTime) return 99; - if (1 === expirationTime) return 95; + if (1 === expirationTime || 2 === expirationTime) return 95; currentTime = 10 * (1073741821 - expirationTime) - 10 * (1073741821 - currentTime); return 0 >= currentTime @@ -1936,9 +1919,10 @@ function inferPriorityFromExpirationTime(currentTime, expirationTime) { function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } -var hasOwnProperty = Object.prototype.hasOwnProperty; +var is$1 = "function" === typeof Object.is ? Object.is : is, + hasOwnProperty = Object.prototype.hasOwnProperty; function shallowEqual(objA, objB) { - if (is(objA, objB)) return !0; + if (is$1(objA, objB)) return !0; if ( "object" !== typeof objA || null === objA || @@ -1952,7 +1936,7 @@ function shallowEqual(objA, objB) { for (keysB = 0; keysB < keysA.length; keysB++) if ( !hasOwnProperty.call(objB, keysA[keysB]) || - !is(objA[keysA[keysB]], objB[keysA[keysB]]) + !is$1(objA[keysA[keysB]], objB[keysA[keysB]]) ) return !1; return !0; @@ -1967,41 +1951,6 @@ function resolveDefaultProps(Component, baseProps) { } return baseProps; } -function readLazyComponentType(lazyComponent) { - var result = lazyComponent._result; - switch (lazyComponent._status) { - case 1: - return result; - case 2: - throw result; - case 0: - throw result; - default: - lazyComponent._status = 0; - result = lazyComponent._ctor; - result = result(); - result.then( - function(moduleObject) { - 0 === lazyComponent._status && - ((moduleObject = moduleObject.default), - (lazyComponent._status = 1), - (lazyComponent._result = moduleObject)); - }, - function(error) { - 0 === lazyComponent._status && - ((lazyComponent._status = 2), (lazyComponent._result = error)); - } - ); - switch (lazyComponent._status) { - case 1: - return lazyComponent._result; - case 2: - throw lazyComponent._result; - } - lazyComponent._result = result; - throw result; - } -} var valueCursor = { current: null }, currentlyRenderingFiber = null, lastContextDependency = null, @@ -2057,10 +2006,8 @@ function readContext(context, observedBits) { observedBits = { context: context, observedBits: observedBits, next: null }; if (null === lastContextDependency) { if (null === currentlyRenderingFiber) - throw ReactError( - Error( - "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." - ) + 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()." ); lastContextDependency = observedBits; currentlyRenderingFiber.dependencies = { @@ -2180,7 +2127,7 @@ function getStateFromUpdate( : workInProgress ); case 3: - workInProgress.effectTag = (workInProgress.effectTag & -2049) | 64; + workInProgress.effectTag = (workInProgress.effectTag & -4097) | 64; case 0: workInProgress = update.payload; nextProps = @@ -2275,6 +2222,7 @@ function processUpdateQueue( queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = updateExpirationTime; + markUnprocessedUpdateTime(newExpirationTime); workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; } @@ -2291,18 +2239,15 @@ function commitUpdateQueue(finishedWork, finishedQueue, instance) { } function commitUpdateEffects(effect, instance) { for (; null !== effect; ) { - var _callback3 = effect.callback; - if (null !== _callback3) { + var callback = effect.callback; + if (null !== callback) { effect.callback = null; - var context = instance; - if ("function" !== typeof _callback3) - throw ReactError( - Error( - "Invalid argument passed as callback. Expected a function. Instead received: " + - _callback3 - ) + if ("function" !== typeof callback) + throw Error( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback ); - _callback3.call(context); + callback.call(instance); } effect = effect.nextEffect; } @@ -2330,7 +2275,7 @@ function applyDerivedStateFromProps( var classComponentUpdater = { isMounted: function(component) { return (component = component._reactInternalFiber) - ? 2 === isFiberMountedImpl(component) + ? getNearestMountedFiber(component) === component : !1; }, enqueueSetState: function(inst, payload, callback) { @@ -2495,23 +2440,18 @@ function coerceRef(returnFiber, current$$1, element) { ) { if (element._owner) { element = element._owner; - var inst = void 0; if (element) { if (1 !== element.tag) - throw ReactError( - Error( - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ) + throw Error( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" ); - inst = element.stateNode; + var inst = element.stateNode; } if (!inst) - throw ReactError( - Error( - "Missing owner for string ref " + - returnFiber + - ". This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." ); var stringRef = "" + returnFiber; if ( @@ -2530,32 +2470,26 @@ function coerceRef(returnFiber, current$$1, element) { return current$$1; } if ("string" !== typeof returnFiber) - throw ReactError( - Error( - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ) + throw Error( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." ); if (!element._owner) - throw ReactError( - Error( - "Element ref was specified as a string (" + - returnFiber + - ") 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." - ) + throw Error( + "Element ref was specified as a string (" + + returnFiber + + ") 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." ); } return returnFiber; } function throwOnInvalidObjectType(returnFiber, newChild) { if ("textarea" !== returnFiber.type) - throw ReactError( - Error( - "Objects are not valid as a React child (found: " + - ("[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild) + - ")." - ) + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === Object.prototype.toString.call(newChild) + ? "object with keys {" + Object.keys(newChild).join(", ") + "}" + : newChild) + + ")." ); } function ChildReconciler(shouldTrackSideEffects) { @@ -2957,14 +2891,12 @@ function ChildReconciler(shouldTrackSideEffects) { ) { var iteratorFn = getIteratorFn(newChildrenIterable); if ("function" !== typeof iteratorFn) - throw ReactError( - Error( - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." ); newChildrenIterable = iteratorFn.call(newChildrenIterable); if (null == newChildrenIterable) - throw ReactError(Error("An iterable object provided no iterator.")); + throw Error("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -3056,7 +2988,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) { + if (isUnkeyedTopLevelFragment.key === isObject) if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -3081,10 +3013,14 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren( + returnFiber, + isUnkeyedTopLevelFragment + ); + break; } - deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); - break; - } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -3120,7 +3056,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) { + if (currentFirstChild.key === isUnkeyedTopLevelFragment) if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -3140,10 +3076,11 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; + } else { + deleteRemainingChildren(returnFiber, currentFirstChild); + break; } - deleteRemainingChildren(returnFiber, currentFirstChild); - break; - } else deleteChild(returnFiber, currentFirstChild); + else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3198,11 +3135,9 @@ function ChildReconciler(shouldTrackSideEffects) { case 1: case 0: throw ((returnFiber = returnFiber.type), - ReactError( - Error( - (returnFiber.displayName || returnFiber.name || "Component") + - "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." - ) + Error( + (returnFiber.displayName || returnFiber.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." )); } return deleteRemainingChildren(returnFiber, currentFirstChild); @@ -3216,10 +3151,8 @@ var reconcileChildFibers = ChildReconciler(!0), rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { if (c === NO_CONTEXT) - throw ReactError( - Error( - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." ); return c; } @@ -3257,14 +3190,17 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -var SubtreeSuspenseContextMask = 1, - InvisibleParentSuspenseContext = 1, - ForceSuspenseFallback = 2, - suspenseStackCursor = { current: 0 }; +var suspenseStackCursor = { current: 0 }; function findFirstSuspended(row) { for (var node = row; null !== node; ) { if (13 === node.tag) { - if (null !== node.memoizedState) return node; + var state = node.memoizedState; + if ( + null !== state && + ((state = state.dehydrated), + null === state || shim$1(state) || shim$1(state)) + ) + return node; } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) { if (0 !== (node.effectTag & 64)) return node; } else if (null !== node.child) { @@ -3285,15 +3221,7 @@ function findFirstSuspended(row) { function createResponderListener(responder, props) { return { responder: responder, props: props }; } -var NoEffect$1 = 0, - UnmountSnapshot = 2, - UnmountMutation = 4, - MountMutation = 8, - UnmountLayout = 16, - MountLayout = 32, - MountPassive = 64, - UnmountPassive = 128, - ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, renderExpirationTime$1 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3308,16 +3236,14 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - throw ReactError( - Error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." - ) + 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." ); } function areHookInputsEqual(nextDeps, prevDeps) { if (null === prevDeps) return !1; for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) - if (!is(nextDeps[i], prevDeps[i])) return !1; + if (!is$1(nextDeps[i], prevDeps[i])) return !1; return !0; } function renderWithHooks( @@ -3360,10 +3286,8 @@ function renderWithHooks( componentUpdateQueue = null; sideEffectTag = 0; if (current) - throw ReactError( - Error( - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ) + throw Error( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." ); return workInProgress; } @@ -3399,9 +3323,7 @@ function updateWorkInProgressHook() { (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { if (null === nextCurrentHook) - throw ReactError( - Error("Rendered more hooks than during the previous render.") - ); + throw Error("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3425,10 +3347,8 @@ function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; if (null === queue) - throw ReactError( - Error( - "Should have a queue. This is likely a bug in React. Please file an issue." - ) + throw Error( + "Should have a queue. This is likely a bug in React. Please file an issue." ); queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { @@ -3442,7 +3362,7 @@ function updateReducer(reducer) { (newState = reducer(newState, firstRenderPhaseUpdate.action)), (firstRenderPhaseUpdate = firstRenderPhaseUpdate.next); while (null !== firstRenderPhaseUpdate); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); queue.lastRenderedState = newState; @@ -3470,7 +3390,8 @@ function updateReducer(reducer) { (newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && - (remainingExpirationTime = updateExpirationTime)) + ((remainingExpirationTime = updateExpirationTime), + markUnprocessedUpdateTime(remainingExpirationTime))) : (markRenderEventTimeAndConfig( updateExpirationTime, _update.suspenseConfig @@ -3484,7 +3405,7 @@ function updateReducer(reducer) { } while (null !== _update && _update !== _dispatch); didSkip || ((newBaseUpdate = baseUpdate), (firstRenderPhaseUpdate = newState)); - is(newState, hook.memoizedState) || (didReceiveUpdate = !0); + is$1(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; @@ -3524,7 +3445,7 @@ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (null !== deps && areHookInputsEqual(deps, prevEffect.deps)) { - pushEffect(NoEffect$1, create, destroy, deps); + pushEffect(0, create, destroy, deps); return; } } @@ -3552,10 +3473,8 @@ function imperativeHandleEffect(create, ref) { function mountDebugValue() {} function dispatchAction(fiber, queue, action) { if (!(25 > numberOfReRenders)) - throw ReactError( - Error( - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ) + throw Error( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." ); var alternate = fiber.alternate; if ( @@ -3583,28 +3502,24 @@ function dispatchAction(fiber, queue, action) { } else { var currentTime = requestCurrentTime(), - _suspenseConfig = ReactCurrentBatchConfig.suspense; - currentTime = computeExpirationForFiber( - currentTime, - fiber, - _suspenseConfig - ); - _suspenseConfig = { + suspenseConfig = ReactCurrentBatchConfig.suspense; + currentTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig); + suspenseConfig = { expirationTime: currentTime, - suspenseConfig: _suspenseConfig, + suspenseConfig: suspenseConfig, action: action, eagerReducer: null, eagerState: null, next: null }; - var _last = queue.last; - if (null === _last) _suspenseConfig.next = _suspenseConfig; + var last = queue.last; + if (null === last) suspenseConfig.next = suspenseConfig; else { - var first = _last.next; - null !== first && (_suspenseConfig.next = first); - _last.next = _suspenseConfig; + var first = last.next; + null !== first && (suspenseConfig.next = first); + last.next = suspenseConfig; } - queue.last = _suspenseConfig; + queue.last = suspenseConfig; if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && @@ -3612,10 +3527,10 @@ function dispatchAction(fiber, queue, action) { ) try { var currentState = queue.lastRenderedState, - _eagerState = alternate(currentState, action); - _suspenseConfig.eagerReducer = alternate; - _suspenseConfig.eagerState = _eagerState; - if (is(_eagerState, currentState)) return; + eagerState = alternate(currentState, action); + suspenseConfig.eagerReducer = alternate; + suspenseConfig.eagerState = eagerState; + if (is$1(eagerState, currentState)) return; } catch (error) { } finally { } @@ -3647,19 +3562,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return mountEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return mountEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return mountEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return mountEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return mountEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = mountWorkInProgressHook(); @@ -3727,19 +3642,19 @@ var ContextOnlyDispatcher = { }, useContext: readContext, useEffect: function(create, deps) { - return updateEffectImpl(516, UnmountPassive | MountPassive, create, deps); + return updateEffectImpl(516, 192, create, deps); }, useImperativeHandle: function(ref, create, deps) { deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null; return updateEffectImpl( 4, - UnmountMutation | MountLayout, + 36, imperativeHandleEffect.bind(null, create, ref), deps ); }, useLayoutEffect: function(create, deps) { - return updateEffectImpl(4, UnmountMutation | MountLayout, create, deps); + return updateEffectImpl(4, 36, create, deps); }, useMemo: function(nextCreate, deps) { var hook = updateWorkInProgressHook(); @@ -3805,7 +3720,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { if (!tryHydrate(fiber$jscomp$0, nextInstance)) { nextInstance = shim$1(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber$jscomp$0, nextInstance)) { - fiber$jscomp$0.effectTag |= 2; + fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2; isHydrating = !1; hydrationParentFiber = fiber$jscomp$0; return; @@ -3825,7 +3740,7 @@ function tryToClaimNextHydratableInstance(fiber$jscomp$0) { hydrationParentFiber = fiber$jscomp$0; nextHydratableInstance = shim$1(nextInstance); } else - (fiber$jscomp$0.effectTag |= 2), + (fiber$jscomp$0.effectTag = (fiber$jscomp$0.effectTag & -1025) | 2), (isHydrating = !1), (hydrationParentFiber = fiber$jscomp$0); } @@ -4319,7 +4234,7 @@ function pushHostRootContext(workInProgress) { pushTopLevelContextObject(workInProgress, root.context, !1); pushHostContainer(workInProgress, root.containerInfo); } -var SUSPENDED_MARKER = {}; +var SUSPENDED_MARKER = { dehydrated: null, retryTime: 0 }; function updateSuspenseComponent( current$$1, workInProgress, @@ -4328,164 +4243,171 @@ function updateSuspenseComponent( var mode = workInProgress.mode, nextProps = workInProgress.pendingProps, suspenseContext = suspenseStackCursor.current, - nextState = null, nextDidTimeout = !1, JSCompiler_temp; (JSCompiler_temp = 0 !== (workInProgress.effectTag & 64)) || (JSCompiler_temp = - 0 !== (suspenseContext & ForceSuspenseFallback) && + 0 !== (suspenseContext & 2) && (null === current$$1 || null !== current$$1.memoizedState)); JSCompiler_temp - ? ((nextState = SUSPENDED_MARKER), - (nextDidTimeout = !0), - (workInProgress.effectTag &= -65)) + ? ((nextDidTimeout = !0), (workInProgress.effectTag &= -65)) : (null !== current$$1 && null === current$$1.memoizedState) || void 0 === nextProps.fallback || !0 === nextProps.unstable_avoidThisFallback || - (suspenseContext |= InvisibleParentSuspenseContext); - suspenseContext &= SubtreeSuspenseContextMask; - push(suspenseStackCursor, suspenseContext, workInProgress); - if (null === current$$1) + (suspenseContext |= 1); + push(suspenseStackCursor, suspenseContext & 1, workInProgress); + if (null === current$$1) { + void 0 !== nextProps.fallback && + tryToClaimNextHydratableInstance(workInProgress); if (nextDidTimeout) { - nextProps = nextProps.fallback; - current$$1 = createFiberFromFragment(null, mode, 0, null); - current$$1.return = workInProgress; + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; if (0 === (workInProgress.mode & 2)) for ( - nextDidTimeout = + current$$1 = null !== workInProgress.memoizedState ? workInProgress.child.child : workInProgress.child, - current$$1.child = nextDidTimeout; - null !== nextDidTimeout; + nextProps.child = current$$1; + null !== current$$1; ) - (nextDidTimeout.return = current$$1), - (nextDidTimeout = nextDidTimeout.sibling); + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); renderExpirationTime = createFiberFromFragment( - nextProps, + nextDidTimeout, mode, renderExpirationTime, null ); renderExpirationTime.return = workInProgress; - current$$1.sibling = renderExpirationTime; - mode = current$$1; - } else - mode = renderExpirationTime = mountChildFibers( - workInProgress, - null, - nextProps.children, - renderExpirationTime + nextProps.sibling = renderExpirationTime; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; + } + mode = nextProps.children; + workInProgress.memoizedState = null; + return (workInProgress.child = mountChildFibers( + workInProgress, + null, + mode, + renderExpirationTime + )); + } + if (null !== current$$1.memoizedState) { + current$$1 = current$$1.child; + mode = current$$1.sibling; + if (nextDidTimeout) { + nextProps = nextProps.fallback; + renderExpirationTime = createWorkInProgress( + current$$1, + current$$1.pendingProps, + 0 ); - else { - if (null !== current$$1.memoizedState) + renderExpirationTime.return = workInProgress; if ( - ((suspenseContext = current$$1.child), - (mode = suspenseContext.sibling), - nextDidTimeout) - ) { - nextProps = nextProps.fallback; - renderExpirationTime = createWorkInProgress( - suspenseContext, - suspenseContext.pendingProps, - 0 - ); - renderExpirationTime.return = workInProgress; - if ( - 0 === (workInProgress.mode & 2) && - ((nextDidTimeout = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child), - nextDidTimeout !== suspenseContext.child) - ) - for ( - renderExpirationTime.child = nextDidTimeout; - null !== nextDidTimeout; - - ) - (nextDidTimeout.return = renderExpirationTime), - (nextDidTimeout = nextDidTimeout.sibling); - if (workInProgress.mode & 8) { - nextDidTimeout = 0; - for ( - suspenseContext = renderExpirationTime.child; - null !== suspenseContext; - - ) - (nextDidTimeout += suspenseContext.treeBaseDuration), - (suspenseContext = suspenseContext.sibling); - renderExpirationTime.treeBaseDuration = nextDidTimeout; - } - nextProps = createWorkInProgress(mode, nextProps, mode.expirationTime); - nextProps.return = workInProgress; - renderExpirationTime.sibling = nextProps; - mode = renderExpirationTime; - renderExpirationTime.childExpirationTime = 0; - renderExpirationTime = nextProps; - } else - mode = renderExpirationTime = reconcileChildFibers( - workInProgress, - suspenseContext.child, - nextProps.children, - renderExpirationTime - ); - else if (((suspenseContext = current$$1.child), nextDidTimeout)) { - nextDidTimeout = nextProps.fallback; - nextProps = createFiberFromFragment(null, mode, 0, null); - nextProps.return = workInProgress; - nextProps.child = suspenseContext; - null !== suspenseContext && (suspenseContext.return = nextProps); - if (0 === (workInProgress.mode & 2)) + 0 === (workInProgress.mode & 2) && + ((nextDidTimeout = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child), + nextDidTimeout !== current$$1.child) + ) for ( - suspenseContext = - null !== workInProgress.memoizedState - ? workInProgress.child.child - : workInProgress.child, - nextProps.child = suspenseContext; - null !== suspenseContext; + renderExpirationTime.child = nextDidTimeout; + null !== nextDidTimeout; ) - (suspenseContext.return = nextProps), - (suspenseContext = suspenseContext.sibling); + (nextDidTimeout.return = renderExpirationTime), + (nextDidTimeout = nextDidTimeout.sibling); if (workInProgress.mode & 8) { - suspenseContext = 0; - for (JSCompiler_temp = nextProps.child; null !== JSCompiler_temp; ) - (suspenseContext += JSCompiler_temp.treeBaseDuration), - (JSCompiler_temp = JSCompiler_temp.sibling); - nextProps.treeBaseDuration = suspenseContext; + nextDidTimeout = 0; + for (current$$1 = renderExpirationTime.child; null !== current$$1; ) + (nextDidTimeout += current$$1.treeBaseDuration), + (current$$1 = current$$1.sibling); + renderExpirationTime.treeBaseDuration = nextDidTimeout; } - renderExpirationTime = createFiberFromFragment( - nextDidTimeout, - mode, - renderExpirationTime, - null - ); - renderExpirationTime.return = workInProgress; - nextProps.sibling = renderExpirationTime; - renderExpirationTime.effectTag |= 2; - mode = nextProps; - nextProps.childExpirationTime = 0; - } else - renderExpirationTime = mode = reconcileChildFibers( - workInProgress, - suspenseContext, - nextProps.children, - renderExpirationTime - ); - workInProgress.stateNode = current$$1.stateNode; + mode = createWorkInProgress(mode, nextProps, mode.expirationTime); + mode.return = workInProgress; + renderExpirationTime.sibling = mode; + renderExpirationTime.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = renderExpirationTime; + return mode; + } + renderExpirationTime = reconcileChildFibers( + workInProgress, + current$$1.child, + nextProps.children, + renderExpirationTime + ); + workInProgress.memoizedState = null; + return (workInProgress.child = renderExpirationTime); + } + current$$1 = current$$1.child; + if (nextDidTimeout) { + nextDidTimeout = nextProps.fallback; + nextProps = createFiberFromFragment(null, mode, 0, null); + nextProps.return = workInProgress; + nextProps.child = current$$1; + null !== current$$1 && (current$$1.return = nextProps); + if (0 === (workInProgress.mode & 2)) + for ( + current$$1 = + null !== workInProgress.memoizedState + ? workInProgress.child.child + : workInProgress.child, + nextProps.child = current$$1; + null !== current$$1; + + ) + (current$$1.return = nextProps), (current$$1 = current$$1.sibling); + if (workInProgress.mode & 8) { + current$$1 = 0; + for (suspenseContext = nextProps.child; null !== suspenseContext; ) + (current$$1 += suspenseContext.treeBaseDuration), + (suspenseContext = suspenseContext.sibling); + nextProps.treeBaseDuration = current$$1; + } + renderExpirationTime = createFiberFromFragment( + nextDidTimeout, + mode, + renderExpirationTime, + null + ); + renderExpirationTime.return = workInProgress; + nextProps.sibling = renderExpirationTime; + renderExpirationTime.effectTag |= 2; + nextProps.childExpirationTime = 0; + workInProgress.memoizedState = SUSPENDED_MARKER; + workInProgress.child = nextProps; + return renderExpirationTime; } - workInProgress.memoizedState = nextState; - workInProgress.child = mode; - return renderExpirationTime; + workInProgress.memoizedState = null; + return (workInProgress.child = reconcileChildFibers( + workInProgress, + current$$1, + nextProps.children, + renderExpirationTime + )); +} +function scheduleWorkOnFiber(fiber, renderExpirationTime) { + fiber.expirationTime < renderExpirationTime && + (fiber.expirationTime = renderExpirationTime); + var alternate = fiber.alternate; + null !== alternate && + alternate.expirationTime < renderExpirationTime && + (alternate.expirationTime = renderExpirationTime); + scheduleWorkOnParentPath(fiber.return, renderExpirationTime); } function initSuspenseListRenderState( workInProgress, isBackwards, tail, lastContentRow, - tailMode + tailMode, + lastEffectBeforeRendering ) { var renderState = workInProgress.memoizedState; null === renderState @@ -4495,14 +4417,16 @@ function initSuspenseListRenderState( last: lastContentRow, tail: tail, tailExpiration: 0, - tailMode: tailMode + tailMode: tailMode, + lastEffect: lastEffectBeforeRendering }) : ((renderState.isBackwards = isBackwards), (renderState.rendering = null), (renderState.last = lastContentRow), (renderState.tail = tail), (renderState.tailExpiration = 0), - (renderState.tailMode = tailMode)); + (renderState.tailMode = tailMode), + (renderState.lastEffect = lastEffectBeforeRendering)); } function updateSuspenseListComponent( current$$1, @@ -4519,24 +4443,17 @@ function updateSuspenseListComponent( renderExpirationTime ); nextProps = suspenseStackCursor.current; - if (0 !== (nextProps & ForceSuspenseFallback)) - (nextProps = - (nextProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback), - (workInProgress.effectTag |= 64); + if (0 !== (nextProps & 2)) + (nextProps = (nextProps & 1) | 2), (workInProgress.effectTag |= 64); else { if (null !== current$$1 && 0 !== (current$$1.effectTag & 64)) a: for (current$$1 = workInProgress.child; null !== current$$1; ) { - if (13 === current$$1.tag) { - if (null !== current$$1.memoizedState) { - current$$1.expirationTime < renderExpirationTime && - (current$$1.expirationTime = renderExpirationTime); - var alternate = current$$1.alternate; - null !== alternate && - alternate.expirationTime < renderExpirationTime && - (alternate.expirationTime = renderExpirationTime); - scheduleWorkOnParentPath(current$$1.return, renderExpirationTime); - } - } else if (null !== current$$1.child) { + if (13 === current$$1.tag) + null !== current$$1.memoizedState && + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (19 === current$$1.tag) + scheduleWorkOnFiber(current$$1, renderExpirationTime); + else if (null !== current$$1.child) { current$$1.child.return = current$$1; current$$1 = current$$1.child; continue; @@ -4553,7 +4470,7 @@ function updateSuspenseListComponent( current$$1.sibling.return = current$$1.return; current$$1 = current$$1.sibling; } - nextProps &= SubtreeSuspenseContextMask; + nextProps &= 1; } push(suspenseStackCursor, nextProps, workInProgress); if (0 === (workInProgress.mode & 2)) workInProgress.memoizedState = null; @@ -4562,9 +4479,9 @@ function updateSuspenseListComponent( case "forwards": renderExpirationTime = workInProgress.child; for (revealOrder = null; null !== renderExpirationTime; ) - (nextProps = renderExpirationTime.alternate), - null !== nextProps && - null === findFirstSuspended(nextProps) && + (current$$1 = renderExpirationTime.alternate), + null !== current$$1 && + null === findFirstSuspended(current$$1) && (revealOrder = renderExpirationTime), (renderExpirationTime = renderExpirationTime.sibling); renderExpirationTime = revealOrder; @@ -4578,33 +4495,42 @@ function updateSuspenseListComponent( !1, revealOrder, renderExpirationTime, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "backwards": renderExpirationTime = null; revealOrder = workInProgress.child; for (workInProgress.child = null; null !== revealOrder; ) { - nextProps = revealOrder.alternate; - if (null !== nextProps && null === findFirstSuspended(nextProps)) { + current$$1 = revealOrder.alternate; + if (null !== current$$1 && null === findFirstSuspended(current$$1)) { workInProgress.child = revealOrder; break; } - nextProps = revealOrder.sibling; + current$$1 = revealOrder.sibling; revealOrder.sibling = renderExpirationTime; renderExpirationTime = revealOrder; - revealOrder = nextProps; + revealOrder = current$$1; } initSuspenseListRenderState( workInProgress, !0, renderExpirationTime, null, - tailMode + tailMode, + workInProgress.lastEffect ); break; case "together": - initSuspenseListRenderState(workInProgress, !1, null, null, void 0); + initSuspenseListRenderState( + workInProgress, + !1, + null, + null, + void 0, + workInProgress.lastEffect + ); break; default: workInProgress.memoizedState = null; @@ -4619,9 +4545,11 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.dependencies = current$$1.dependencies); profilerStartTime = -1; + var updateExpirationTime = workInProgress.expirationTime; + 0 !== updateExpirationTime && markUnprocessedUpdateTime(updateExpirationTime); if (workInProgress.childExpirationTime < renderExpirationTime) return null; if (null !== current$$1 && workInProgress.child !== current$$1.child) - throw ReactError(Error("Resuming work not yet implemented.")); + throw Error("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4646,10 +4574,10 @@ function bailoutOnAlreadyFinishedWork( } return workInProgress.child; } -var appendAllChildren = void 0, - updateHostContainer = void 0, - updateHostComponent$1 = void 0, - updateHostText$1 = void 0; +var appendAllChildren, + updateHostContainer, + updateHostComponent$1, + updateHostText$1; appendAllChildren = function(parent, workInProgress) { for (var node = workInProgress.child; null !== node; ) { if (5 === node.tag || 6 === node.tag) parent._children.push(node.stateNode); @@ -4701,7 +4629,7 @@ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { : (_lastTailNode.sibling = null); } } -function completeWork(current, workInProgress, renderExpirationTime) { +function completeWork(current, workInProgress, renderExpirationTime$jscomp$0) { var newProps = workInProgress.pendingProps; switch (workInProgress.tag) { case 2: @@ -4717,12 +4645,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 3: popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); - newProps = workInProgress.stateNode; - newProps.pendingContext && - ((newProps.context = newProps.pendingContext), - (newProps.pendingContext = null)); - if (null === current || null === current.child) - workInProgress.effectTag &= -3; + current = workInProgress.stateNode; + current.pendingContext && + ((current.context = current.pendingContext), + (current.pendingContext = null)); updateHostContainer(workInProgress); break; case 5: @@ -4730,12 +4656,12 @@ function completeWork(current, workInProgress, renderExpirationTime) { var rootContainerInstance = requiredContext( rootInstanceStackCursor.current ); - renderExpirationTime = workInProgress.type; + renderExpirationTime$jscomp$0 = workInProgress.type; if (null !== current && null != workInProgress.stateNode) updateHostComponent$1( current, workInProgress, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance ), @@ -4744,7 +4670,7 @@ function completeWork(current, workInProgress, renderExpirationTime) { else if (newProps) { current = requiredContext(contextStackCursor$1.current); var tag = allocateTag(), - viewConfig = getViewConfigForType(renderExpirationTime), + viewConfig = getViewConfigForType(renderExpirationTime$jscomp$0), updatePayload = diffProperties( null, emptyObject, @@ -4761,20 +4687,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { instanceCache.set(tag, workInProgress); instanceProps.set(tag, newProps); appendAllChildren(viewConfig, workInProgress, !1, !1); + workInProgress.stateNode = viewConfig; finalizeInitialChildren( viewConfig, - renderExpirationTime, + renderExpirationTime$jscomp$0, newProps, rootContainerInstance, current ) && (workInProgress.effectTag |= 4); - workInProgress.stateNode = viewConfig; null !== workInProgress.ref && (workInProgress.effectTag |= 128); } else if (null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); break; case 6: @@ -4787,15 +4711,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { ); else { if ("string" !== typeof newProps && null === workInProgress.stateNode) - throw ReactError( - Error( - "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." ); current = requiredContext(rootInstanceStackCursor.current); if (!requiredContext(contextStackCursor$1.current).isInAParentText) - throw ReactError( - Error("Text strings must be rendered within a component.") + throw Error( + "Text strings must be rendered within a component." ); rootContainerInstance = allocateTag(); ReactNativePrivateInterface.UIManager.createView( @@ -4815,37 +4737,47 @@ function completeWork(current, workInProgress, renderExpirationTime) { newProps = workInProgress.memoizedState; if (0 !== (workInProgress.effectTag & 64)) return ( - (workInProgress.expirationTime = renderExpirationTime), workInProgress + (workInProgress.expirationTime = renderExpirationTime$jscomp$0), + workInProgress ); newProps = null !== newProps; rootContainerInstance = !1; null !== current && - ((renderExpirationTime = current.memoizedState), - (rootContainerInstance = null !== renderExpirationTime), + ((renderExpirationTime$jscomp$0 = current.memoizedState), + (rootContainerInstance = null !== renderExpirationTime$jscomp$0), newProps || - null === renderExpirationTime || - ((renderExpirationTime = current.child.sibling), - null !== renderExpirationTime && + null === renderExpirationTime$jscomp$0 || + ((renderExpirationTime$jscomp$0 = current.child.sibling), + null !== renderExpirationTime$jscomp$0 && ((tag = workInProgress.firstEffect), null !== tag - ? ((workInProgress.firstEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = tag)) - : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime), - (renderExpirationTime.nextEffect = null)), - (renderExpirationTime.effectTag = 8)))); + ? ((workInProgress.firstEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = tag)) + : ((workInProgress.firstEffect = workInProgress.lastEffect = renderExpirationTime$jscomp$0), + (renderExpirationTime$jscomp$0.nextEffect = null)), + (renderExpirationTime$jscomp$0.effectTag = 8)))); if (newProps && !rootContainerInstance && 0 !== (workInProgress.mode & 2)) if ( (null === current && !0 !== workInProgress.memoizedProps.unstable_avoidThisFallback) || - 0 !== (suspenseStackCursor.current & InvisibleParentSuspenseContext) + 0 !== (suspenseStackCursor.current & 1) ) workInProgressRootExitStatus === RootIncomplete && (workInProgressRootExitStatus = RootSuspended); - else if ( - workInProgressRootExitStatus === RootIncomplete || - workInProgressRootExitStatus === RootSuspended - ) - workInProgressRootExitStatus = RootSuspendedWithDelay; + else { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) + workInProgressRootExitStatus = RootSuspendedWithDelay; + 0 !== workInProgressRootNextUnprocessedUpdateTime && + null !== workInProgressRoot && + (markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime), + markRootUpdatedAtTime( + workInProgressRoot, + workInProgressRootNextUnprocessedUpdateTime + )); + } if (newProps || rootContainerInstance) workInProgress.effectTag |= 4; break; case 7: @@ -4868,8 +4800,6 @@ function completeWork(current, workInProgress, renderExpirationTime) { case 17: isContextProvider(workInProgress.type) && popContext(workInProgress); break; - case 18: - break; case 19: pop(suspenseStackCursor, workInProgress); newProps = workInProgress.memoizedState; @@ -4892,8 +4822,10 @@ function completeWork(current, workInProgress, renderExpirationTime) { null !== current && ((workInProgress.updateQueue = current), (workInProgress.effectTag |= 4)); - workInProgress.firstEffect = workInProgress.lastEffect = null; - current = renderExpirationTime; + null === newProps.lastEffect && + (workInProgress.firstEffect = null); + workInProgress.lastEffect = newProps.lastEffect; + current = renderExpirationTime$jscomp$0; for (newProps = workInProgress.child; null !== newProps; ) (rootContainerInstance = newProps), (tag = current), @@ -4901,8 +4833,9 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.nextEffect = null), (rootContainerInstance.firstEffect = null), (rootContainerInstance.lastEffect = null), - (renderExpirationTime = rootContainerInstance.alternate), - null === renderExpirationTime + (renderExpirationTime$jscomp$0 = + rootContainerInstance.alternate), + null === renderExpirationTime$jscomp$0 ? ((rootContainerInstance.childExpirationTime = 0), (rootContainerInstance.expirationTime = tag), (rootContainerInstance.child = null), @@ -4913,18 +4846,18 @@ function completeWork(current, workInProgress, renderExpirationTime) { (rootContainerInstance.selfBaseDuration = 0), (rootContainerInstance.treeBaseDuration = 0)) : ((rootContainerInstance.childExpirationTime = - renderExpirationTime.childExpirationTime), + renderExpirationTime$jscomp$0.childExpirationTime), (rootContainerInstance.expirationTime = - renderExpirationTime.expirationTime), + renderExpirationTime$jscomp$0.expirationTime), (rootContainerInstance.child = - renderExpirationTime.child), + renderExpirationTime$jscomp$0.child), (rootContainerInstance.memoizedProps = - renderExpirationTime.memoizedProps), + renderExpirationTime$jscomp$0.memoizedProps), (rootContainerInstance.memoizedState = - renderExpirationTime.memoizedState), + renderExpirationTime$jscomp$0.memoizedState), (rootContainerInstance.updateQueue = - renderExpirationTime.updateQueue), - (tag = renderExpirationTime.dependencies), + renderExpirationTime$jscomp$0.updateQueue), + (tag = renderExpirationTime$jscomp$0.dependencies), (rootContainerInstance.dependencies = null === tag ? null @@ -4934,14 +4867,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { responders: tag.responders }), (rootContainerInstance.selfBaseDuration = - renderExpirationTime.selfBaseDuration), + renderExpirationTime$jscomp$0.selfBaseDuration), (rootContainerInstance.treeBaseDuration = - renderExpirationTime.treeBaseDuration)), + renderExpirationTime$jscomp$0.treeBaseDuration)), (newProps = newProps.sibling); push( suspenseStackCursor, - (suspenseStackCursor.current & SubtreeSuspenseContextMask) | - ForceSuspenseFallback, + (suspenseStackCursor.current & 1) | 2, workInProgress ); return workInProgress.child; @@ -4955,24 +4887,24 @@ function completeWork(current, workInProgress, renderExpirationTime) { if ( ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), + (current = current.updateQueue), + null !== current && + ((workInProgress.updateQueue = current), + (workInProgress.effectTag |= 4)), cutOffTailIfNeeded(newProps, !0), null === newProps.tail && "hidden" === newProps.tailMode) ) { - current = current.updateQueue; - null !== current && - ((workInProgress.updateQueue = current), - (workInProgress.effectTag |= 4)); workInProgress = workInProgress.lastEffect = newProps.lastEffect; null !== workInProgress && (workInProgress.nextEffect = null); break; } } else now() > newProps.tailExpiration && - 1 < renderExpirationTime && + 1 < renderExpirationTime$jscomp$0 && ((workInProgress.effectTag |= 64), (rootContainerInstance = !0), cutOffTailIfNeeded(newProps, !1), - (current = renderExpirationTime - 1), + (current = renderExpirationTime$jscomp$0 - 1), (workInProgress.expirationTime = workInProgress.childExpirationTime = current), null === spawnedWorkDuringRender ? (spawnedWorkDuringRender = [current]) @@ -4995,20 +4927,23 @@ function completeWork(current, workInProgress, renderExpirationTime) { (newProps.lastEffect = workInProgress.lastEffect), (current.sibling = null), (newProps = suspenseStackCursor.current), - (newProps = rootContainerInstance - ? (newProps & SubtreeSuspenseContextMask) | ForceSuspenseFallback - : newProps & SubtreeSuspenseContextMask), - push(suspenseStackCursor, newProps, workInProgress), + push( + suspenseStackCursor, + rootContainerInstance ? (newProps & 1) | 2 : newProps & 1, + workInProgress + ), current ); break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); } return null; @@ -5018,8 +4953,8 @@ function unwindWork(workInProgress) { case 1: isContextProvider(workInProgress.type) && popContext(workInProgress); var effectTag = workInProgress.effectTag; - return effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + return effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null; case 3: @@ -5027,12 +4962,10 @@ function unwindWork(workInProgress) { popTopLevelContextObject(workInProgress); effectTag = workInProgress.effectTag; if (0 !== (effectTag & 64)) - throw ReactError( - Error( - "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." - ) + throw Error( + "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." ); - workInProgress.effectTag = (effectTag & -2049) | 64; + workInProgress.effectTag = (effectTag & -4097) | 64; return workInProgress; case 5: return popHostContext(workInProgress), null; @@ -5040,13 +4973,11 @@ function unwindWork(workInProgress) { return ( pop(suspenseStackCursor, workInProgress), (effectTag = workInProgress.effectTag), - effectTag & 2048 - ? ((workInProgress.effectTag = (effectTag & -2049) | 64), + effectTag & 4096 + ? ((workInProgress.effectTag = (effectTag & -4097) | 64), workInProgress) : null ); - case 18: - return null; case 19: return pop(suspenseStackCursor, workInProgress), null; case 4: @@ -5068,8 +4999,8 @@ if ( "function" !== typeof ReactNativePrivateInterface.ReactFiberErrorDialog.showErrorDialog ) - throw ReactError( - Error("Expected ReactFiberErrorDialog.showErrorDialog to be a function.") + throw Error( + "Expected ReactFiberErrorDialog.showErrorDialog to be a function." ); function logCapturedError(capturedError) { !1 !== @@ -5077,7 +5008,7 @@ function logCapturedError(capturedError) { capturedError ) && console.error(capturedError.error); } -var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; +var PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5127,24 +5058,57 @@ function safelyDetachRef(current$$1) { } else ref.current = null; } +function commitBeforeMutationLifeCycles(current$$1, finishedWork) { + switch (finishedWork.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(2, 0, finishedWork); + break; + case 1: + if (finishedWork.effectTag & 256 && null !== current$$1) { + var prevProps = current$$1.memoizedProps, + prevState = current$$1.memoizedState; + current$$1 = finishedWork.stateNode; + finishedWork = current$$1.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + current$$1.__reactInternalSnapshotBeforeUpdate = finishedWork; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + break; + default: + 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." + ); + } +} function commitHookEffectList(unmountTag, mountTag, finishedWork) { finishedWork = finishedWork.updateQueue; finishedWork = null !== finishedWork ? finishedWork.lastEffect : null; if (null !== finishedWork) { var effect = (finishedWork = finishedWork.next); do { - if ((effect.tag & unmountTag) !== NoEffect$1) { + if (0 !== (effect.tag & unmountTag)) { var destroy = effect.destroy; effect.destroy = void 0; void 0 !== destroy && destroy(); } - (effect.tag & mountTag) !== NoEffect$1 && + 0 !== (effect.tag & mountTag) && ((destroy = effect.create), (effect.destroy = destroy())); effect = effect.next; } while (effect !== finishedWork); } } -function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { +function commitUnmount(finishedRoot, current$$1$jscomp$0, renderPriorityLevel) { "function" === typeof onCommitFiberUnmount && onCommitFiberUnmount(current$$1$jscomp$0); switch (current$$1$jscomp$0.tag) { @@ -5152,12 +5116,12 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { case 11: case 14: case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; + finishedRoot = current$$1$jscomp$0.updateQueue; if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) + null !== finishedRoot && + ((finishedRoot = finishedRoot.lastEffect), null !== finishedRoot) ) { - var firstEffect = updateQueue.next; + var firstEffect = finishedRoot.next; runWithPriority( 97 < renderPriorityLevel ? 97 : renderPriorityLevel, function() { @@ -5191,7 +5155,11 @@ function commitUnmount(current$$1$jscomp$0, renderPriorityLevel) { safelyDetachRef(current$$1$jscomp$0); break; case 4: - unmountHostComponents(current$$1$jscomp$0, renderPriorityLevel); + unmountHostComponents( + finishedRoot, + current$$1$jscomp$0, + renderPriorityLevel + ); } } function detachFiber(current$$1) { @@ -5220,10 +5188,8 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); } parent = parentFiber.stateNode; @@ -5240,10 +5206,8 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - throw ReactError( - Error( - "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } parentFiber.effectTag & 16 && (parentFiber.effectTag &= -17); @@ -5279,9 +5243,7 @@ function commitPlacement(finishedWork) { if (parentFiber) if (isContainer) { if ("number" === typeof parent) - throw ReactError( - Error("Container does not support insertBefore operation") - ); + throw Error("Container does not support insertBefore operation"); } else { isHost = parent; var beforeChild = parentFiber, @@ -5358,12 +5320,16 @@ function commitPlacement(finishedWork) { node = node.sibling; } } -function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { +function unmountHostComponents( + finishedRoot$jscomp$0, + current$$1, + renderPriorityLevel$jscomp$0 +) { for ( var node = current$$1, currentParentIsValid = !1, - currentParent = void 0, - currentParentIsContainer = void 0; + currentParent, + currentParentIsContainer; ; ) { @@ -5371,10 +5337,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { currentParentIsValid = node.return; a: for (;;) { if (null === currentParentIsValid) - throw ReactError( - Error( - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); currentParent = currentParentIsValid.stateNode; switch (currentParentIsValid.tag) { @@ -5396,14 +5360,15 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { } if (5 === node.tag || 6 === node.tag) { a: for ( - var root = node, + var finishedRoot = finishedRoot$jscomp$0, + root = node, renderPriorityLevel = renderPriorityLevel$jscomp$0, node$jscomp$0 = root; ; ) if ( - (commitUnmount(node$jscomp$0, renderPriorityLevel), + (commitUnmount(finishedRoot, node$jscomp$0, renderPriorityLevel), null !== node$jscomp$0.child && 4 !== node$jscomp$0.tag) ) (node$jscomp$0.child.return = node$jscomp$0), @@ -5419,29 +5384,29 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { node$jscomp$0 = node$jscomp$0.sibling; } currentParentIsContainer - ? ((root = currentParent), + ? ((finishedRoot = currentParent), recursivelyUncacheFiberNode(node.stateNode), ReactNativePrivateInterface.UIManager.manageChildren( - root, + finishedRoot, [], [], [], [], [0] )) - : ((root = currentParent), - (node$jscomp$0 = node.stateNode), - recursivelyUncacheFiberNode(node$jscomp$0), - (renderPriorityLevel = root._children), - (node$jscomp$0 = renderPriorityLevel.indexOf(node$jscomp$0)), - renderPriorityLevel.splice(node$jscomp$0, 1), + : ((finishedRoot = currentParent), + (renderPriorityLevel = node.stateNode), + recursivelyUncacheFiberNode(renderPriorityLevel), + (root = finishedRoot._children), + (renderPriorityLevel = root.indexOf(renderPriorityLevel)), + root.splice(renderPriorityLevel, 1), ReactNativePrivateInterface.UIManager.manageChildren( - root._nativeTag, + finishedRoot._nativeTag, [], [], [], [], - [node$jscomp$0] + [renderPriorityLevel] )); } else if (4 === node.tag) { if (null !== node.child) { @@ -5452,7 +5417,8 @@ function unmountHostComponents(current$$1, renderPriorityLevel$jscomp$0) { continue; } } else if ( - (commitUnmount(node, renderPriorityLevel$jscomp$0), null !== node.child) + (commitUnmount(finishedRoot$jscomp$0, node, renderPriorityLevel$jscomp$0), + null !== node.child) ) { node.child.return = node; node = node.child; @@ -5474,7 +5440,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5504,10 +5470,8 @@ function commitWork(current$$1, finishedWork) { break; case 6: if (null === finishedWork.stateNode) - throw ReactError( - Error( - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." ); ReactNativePrivateInterface.UIManager.updateView( finishedWork.stateNode, @@ -5563,7 +5527,11 @@ function commitWork(current$$1, finishedWork) { } else { if (6 === current$$1.tag) throw Error("Not yet implemented."); - if (13 === current$$1.tag && null !== current$$1.memoizedState) { + if ( + 13 === current$$1.tag && + null !== current$$1.memoizedState && + null === current$$1.memoizedState.dehydrated + ) { updatePayload = current$$1.child.sibling; updatePayload.return = current$$1; current$$1 = updatePayload; @@ -5592,11 +5560,11 @@ function commitWork(current$$1, finishedWork) { break; case 20: break; + case 21: + break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } @@ -5606,11 +5574,12 @@ function attachSuspenseRetryListeners(finishedWork) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + (retryCache = finishedWork.stateNode = new PossiblyWeakSet()); thenables.forEach(function(thenable) { var retry = resolveRetryThenable.bind(null, finishedWork, thenable); retryCache.has(thenable) || - ((retry = tracing.unstable_wrap(retry)), + (!0 !== thenable.__reactDoNotTraceInteractions && + (retry = tracing.unstable_wrap(retry)), retryCache.add(thenable), thenable.then(retry, retry)); }); @@ -5663,18 +5632,21 @@ var ceil = Math.ceil, RenderContext = 16, CommitContext = 32, RootIncomplete = 0, - RootErrored = 1, - RootSuspended = 2, - RootSuspendedWithDelay = 3, - RootCompleted = 4, + RootFatalErrored = 1, + RootErrored = 2, + RootSuspended = 3, + RootSuspendedWithDelay = 4, + RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, renderExpirationTime = 0, workInProgressRootExitStatus = RootIncomplete, + workInProgressRootFatalError = null, workInProgressRootLatestProcessedExpirationTime = 1073741823, workInProgressRootLatestSuspenseTimeout = 1073741823, workInProgressRootCanSuspendUsingConfig = null, + workInProgressRootNextUnprocessedUpdateTime = 0, workInProgressRootHasPendingPing = !1, globalMostRecentFallbackTime = 0, FALLBACK_THROTTLE_MS = 500, @@ -5730,10 +5702,10 @@ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) { 1073741821 - 25 * ((((1073741821 - currentTime + 500) / 25) | 0) + 1); break; case 95: - currentTime = 1; + currentTime = 2; break; default: - throw ReactError(Error("Expected a valid priority level")); + throw Error("Expected a valid priority level"); } null !== workInProgressRoot && currentTime === renderExpirationTime && @@ -5744,35 +5716,22 @@ function scheduleUpdateOnFiber(fiber, expirationTime) { if (50 < nestedUpdateCount) throw ((nestedUpdateCount = 0), (rootWithNestedUpdates = null), - ReactError( - Error( - "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." - ) + 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." )); fiber = markUpdateTimeFromFiberToRoot(fiber, expirationTime); if (null !== fiber) { - fiber.pingTime = 0; var priorityLevel = getCurrentPriorityLevel(); - if (1073741823 === expirationTime) - if ( - (executionContext & LegacyUnbatchedContext) !== NoContext && + 1073741823 === expirationTime + ? (executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext - ) { - scheduleInteractions( - fiber, - expirationTime, - tracing.__interactionsRef.current - ); - for ( - var callback = renderRoot(fiber, 1073741823, !0); - null !== callback; - - ) - callback = callback(!0); - } else - scheduleCallbackForRoot(fiber, 99, 1073741823), - executionContext === NoContext && flushSyncCallbackQueue(); - else scheduleCallbackForRoot(fiber, priorityLevel, expirationTime); + ? (schedulePendingInteractions(fiber, expirationTime), + performSyncWorkOnRoot(fiber)) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime), + executionContext === NoContext && flushSyncCallbackQueue()) + : (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, expirationTime)); (executionContext & 4) === NoContext || (98 !== priorityLevel && 99 !== priorityLevel) || (null === rootsWithPendingDiscreteUpdates @@ -5807,79 +5766,330 @@ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) { node = node.return; } null !== root && - (expirationTime > root.firstPendingTime && - (root.firstPendingTime = expirationTime), - (fiber = root.lastPendingTime), - 0 === fiber || expirationTime < fiber) && - (root.lastPendingTime = expirationTime); + (workInProgressRoot === root && + (markUnprocessedUpdateTime(expirationTime), + workInProgressRootExitStatus === RootSuspendedWithDelay && + markRootSuspendedAtTime(root, renderExpirationTime)), + markRootUpdatedAtTime(root, expirationTime)); return root; } -function scheduleCallbackForRoot(root, priorityLevel, expirationTime) { - if (root.callbackExpirationTime < expirationTime) { - var existingCallbackNode = root.callbackNode; - null !== existingCallbackNode && - existingCallbackNode !== fakeCallbackNode && - Scheduler_cancelCallback(existingCallbackNode); - root.callbackExpirationTime = expirationTime; - 1073741823 === expirationTime - ? (root.callbackNode = scheduleSyncCallback( - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ) - )) - : ((existingCallbackNode = null), - 1 !== expirationTime && - (existingCallbackNode = { - timeout: 10 * (1073741821 - expirationTime) - now() - }), - (root.callbackNode = scheduleCallback( - priorityLevel, - runRootCallback.bind( - null, - root, - renderRoot.bind(null, root, expirationTime) - ), - existingCallbackNode - ))); +function getNextRootExpirationTimeToWorkOn(root) { + var lastExpiredTime = root.lastExpiredTime; + if (0 !== lastExpiredTime) return lastExpiredTime; + lastExpiredTime = root.firstPendingTime; + if (!isRootSuspendedAtTime(root, lastExpiredTime)) return lastExpiredTime; + lastExpiredTime = root.lastPingedTime; + root = root.nextKnownPendingLevel; + return lastExpiredTime > root ? lastExpiredTime : root; +} +function ensureRootIsScheduled(root) { + if (0 !== root.lastExpiredTime) + (root.callbackExpirationTime = 1073741823), + (root.callbackPriority = 99), + (root.callbackNode = scheduleSyncCallback( + performSyncWorkOnRoot.bind(null, root) + )); + else { + var expirationTime = getNextRootExpirationTimeToWorkOn(root), + existingCallbackNode = root.callbackNode; + if (0 === expirationTime) + null !== existingCallbackNode && + ((root.callbackNode = null), + (root.callbackExpirationTime = 0), + (root.callbackPriority = 90)); + else { + var currentTime = requestCurrentTime(); + currentTime = inferPriorityFromExpirationTime( + currentTime, + expirationTime + ); + if (null !== existingCallbackNode) { + var existingCallbackPriority = root.callbackPriority; + if ( + root.callbackExpirationTime === expirationTime && + existingCallbackPriority >= currentTime + ) + return; + existingCallbackNode !== fakeCallbackNode && + Scheduler_cancelCallback(existingCallbackNode); + } + root.callbackExpirationTime = expirationTime; + root.callbackPriority = currentTime; + expirationTime = + 1073741823 === expirationTime + ? scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)) + : scheduleCallback( + currentTime, + performConcurrentWorkOnRoot.bind(null, root), + { timeout: 10 * (1073741821 - expirationTime) - now() } + ); + root.callbackNode = expirationTime; + } } - scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); } -function runRootCallback(root, callback, isSync) { - var prevCallbackNode = root.callbackNode, - continuation = null; - try { +function performConcurrentWorkOnRoot(root, didTimeout) { + currentEventTime = 0; + if (didTimeout) return ( - (continuation = callback(isSync)), - null !== continuation - ? runRootCallback.bind(null, root, continuation) - : null + (didTimeout = requestCurrentTime()), + markRootExpiredAtTime(root, didTimeout), + ensureRootIsScheduled(root), + null ); - } finally { - null === continuation && - prevCallbackNode === root.callbackNode && - ((root.callbackNode = null), (root.callbackExpirationTime = 0)); + var expirationTime = getNextRootExpirationTimeToWorkOn(root); + if (0 !== expirationTime) { + didTimeout = root.callbackNode; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || expirationTime !== renderExpirationTime) + prepareFreshStack(root, expirationTime), + startWorkOnPendingInteractions(root, expirationTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((didTimeout = workInProgressRootFatalError), + prepareFreshStack(root, expirationTime), + markRootSuspendedAtTime(root, expirationTime), + ensureRootIsScheduled(root), + didTimeout); + if (null === workInProgress) + switch ( + ((prevDispatcher = root.finishedWork = root.current.alternate), + (root.finishedExpirationTime = expirationTime), + (prevExecutionContext = workInProgressRootExitStatus), + (workInProgressRoot = null), + prevExecutionContext) + ) { + case RootIncomplete: + case RootFatalErrored: + throw Error("Root did not complete. This is a bug in React."); + case RootErrored: + markRootExpiredAtTime( + root, + 2 < expirationTime ? 2 : expirationTime + ); + break; + case RootSuspended: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + 1073741823 === workInProgressRootLatestProcessedExpirationTime && + ((prevDispatcher = + globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), + 10 < prevDispatcher) + ) { + if ( + workInProgressRootHasPendingPing && + ((prevInteractions = root.lastPingedTime), + 0 === prevInteractions || prevInteractions >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevInteractions = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevInteractions && prevInteractions !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevDispatcher + ); + break; + } + commitRoot(root); + break; + case RootSuspendedWithDelay: + markRootSuspendedAtTime(root, expirationTime); + prevExecutionContext = root.lastSuspendedTime; + expirationTime === prevExecutionContext && + (root.nextKnownPendingLevel = getRemainingExpirationTime( + prevDispatcher + )); + if ( + workInProgressRootHasPendingPing && + ((prevDispatcher = root.lastPingedTime), + 0 === prevDispatcher || prevDispatcher >= expirationTime) + ) { + root.lastPingedTime = expirationTime; + prepareFreshStack(root, expirationTime); + break; + } + prevDispatcher = getNextRootExpirationTimeToWorkOn(root); + if (0 !== prevDispatcher && prevDispatcher !== expirationTime) + break; + if ( + 0 !== prevExecutionContext && + prevExecutionContext !== expirationTime + ) { + root.lastPingedTime = prevExecutionContext; + break; + } + 1073741823 !== workInProgressRootLatestSuspenseTimeout + ? (prevExecutionContext = + 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - + now()) + : 1073741823 === workInProgressRootLatestProcessedExpirationTime + ? (prevExecutionContext = 0) + : ((prevExecutionContext = + 10 * + (1073741821 - + workInProgressRootLatestProcessedExpirationTime) - + 5e3), + (prevDispatcher = now()), + (expirationTime = + 10 * (1073741821 - expirationTime) - prevDispatcher), + (prevExecutionContext = + prevDispatcher - prevExecutionContext), + 0 > prevExecutionContext && (prevExecutionContext = 0), + (prevExecutionContext = + (120 > prevExecutionContext + ? 120 + : 480 > prevExecutionContext + ? 480 + : 1080 > prevExecutionContext + ? 1080 + : 1920 > prevExecutionContext + ? 1920 + : 3e3 > prevExecutionContext + ? 3e3 + : 4320 > prevExecutionContext + ? 4320 + : 1960 * ceil(prevExecutionContext / 1960)) - + prevExecutionContext), + expirationTime < prevExecutionContext && + (prevExecutionContext = expirationTime)); + if (10 < prevExecutionContext) { + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + commitRoot(root); + break; + case RootCompleted: + if ( + 1073741823 !== workInProgressRootLatestProcessedExpirationTime && + null !== workInProgressRootCanSuspendUsingConfig + ) { + prevInteractions = workInProgressRootLatestProcessedExpirationTime; + var suspenseConfig = workInProgressRootCanSuspendUsingConfig; + prevExecutionContext = suspenseConfig.busyMinDurationMs | 0; + 0 >= prevExecutionContext + ? (prevExecutionContext = 0) + : ((prevDispatcher = suspenseConfig.busyDelayMs | 0), + (prevInteractions = + now() - + (10 * (1073741821 - prevInteractions) - + (suspenseConfig.timeoutMs | 0 || 5e3))), + (prevExecutionContext = + prevInteractions <= prevDispatcher + ? 0 + : prevDispatcher + + prevExecutionContext - + prevInteractions)); + if (10 < prevExecutionContext) { + markRootSuspendedAtTime(root, expirationTime); + root.timeoutHandle = scheduleTimeout( + commitRoot.bind(null, root), + prevExecutionContext + ); + break; + } + } + commitRoot(root); + break; + default: + throw Error("Unknown root exit status."); + } + ensureRootIsScheduled(root); + if (root.callbackNode === didTimeout) + return performConcurrentWorkOnRoot.bind(null, root); + } } + return null; } -function resolveLocksOnRoot(root, expirationTime) { - var firstBatch = root.firstBatch; - return null !== firstBatch && - firstBatch._defer && - firstBatch._expirationTime >= expirationTime - ? (scheduleCallback(97, function() { - firstBatch._onComplete(); - return null; - }), - !0) - : !1; +function performSyncWorkOnRoot(root) { + var lastExpiredTime = root.lastExpiredTime; + lastExpiredTime = 0 !== lastExpiredTime ? lastExpiredTime : 1073741823; + if (root.finishedExpirationTime === lastExpiredTime) commitRoot(root); + else { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) + throw Error("Should not already be working."); + flushPassiveEffects(); + if (root !== workInProgressRoot || lastExpiredTime !== renderExpirationTime) + prepareFreshStack(root, lastExpiredTime), + startWorkOnPendingInteractions(root, lastExpiredTime); + if (null !== workInProgress) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(root), + prevInteractions = pushInteractions(root); + do + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root, thrownValue); + } + while (1); + resetContextDependencies(); + executionContext = prevExecutionContext; + ReactCurrentDispatcher.current = prevDispatcher; + tracing.__interactionsRef.current = prevInteractions; + if (workInProgressRootExitStatus === RootFatalErrored) + throw ((prevExecutionContext = workInProgressRootFatalError), + prepareFreshStack(root, lastExpiredTime), + markRootSuspendedAtTime(root, lastExpiredTime), + ensureRootIsScheduled(root), + prevExecutionContext); + if (null !== workInProgress) + throw Error( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.finishedWork = root.current.alternate; + root.finishedExpirationTime = lastExpiredTime; + workInProgressRoot = null; + commitRoot(root); + ensureRootIsScheduled(root); + } + } + return null; } function flushPendingDiscreteUpdates() { if (null !== rootsWithPendingDiscreteUpdates) { var roots = rootsWithPendingDiscreteUpdates; rootsWithPendingDiscreteUpdates = null; roots.forEach(function(expirationTime, root) { - scheduleSyncCallback(renderRoot.bind(null, root, expirationTime)); + markRootExpiredAtTime(root, expirationTime); + ensureRootIsScheduled(root); }); flushSyncCallbackQueue(); } @@ -5925,354 +6135,196 @@ function prepareFreshStack(root, expirationTime) { workInProgress = createWorkInProgress(root.current, null, expirationTime); renderExpirationTime = expirationTime; workInProgressRootExitStatus = RootIncomplete; + workInProgressRootFatalError = null; workInProgressRootLatestSuspenseTimeout = workInProgressRootLatestProcessedExpirationTime = 1073741823; workInProgressRootCanSuspendUsingConfig = null; + workInProgressRootNextUnprocessedUpdateTime = 0; workInProgressRootHasPendingPing = !1; spawnedWorkDuringRender = null; } -function renderRoot(root$jscomp$0, expirationTime, isSync) { - if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - if (root$jscomp$0.firstPendingTime < expirationTime) return null; - if (isSync && root$jscomp$0.finishedExpirationTime === expirationTime) - return commitRoot.bind(null, root$jscomp$0); - flushPassiveEffects(); - if ( - root$jscomp$0 !== workInProgressRoot || - expirationTime !== renderExpirationTime - ) - prepareFreshStack(root$jscomp$0, expirationTime), - startWorkOnPendingInteractions(root$jscomp$0, expirationTime); - else if (workInProgressRootExitStatus === RootSuspendedWithDelay) - if (workInProgressRootHasPendingPing) - prepareFreshStack(root$jscomp$0, expirationTime); - else { - var lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - } - if (null !== workInProgress) { - lastPendingTime = executionContext; - executionContext |= RenderContext; - var prevDispatcher = ReactCurrentDispatcher.current; - null === prevDispatcher && (prevDispatcher = ContextOnlyDispatcher); - ReactCurrentDispatcher.current = ContextOnlyDispatcher; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root$jscomp$0.memoizedInteractions; - if (isSync) { - if (1073741823 !== expirationTime) { - var currentTime = requestCurrentTime(); - if (currentTime < expirationTime) - return ( - (executionContext = lastPendingTime), - resetContextDependencies(), - (ReactCurrentDispatcher.current = prevDispatcher), - (tracing.__interactionsRef.current = prevInteractions), - renderRoot.bind(null, root$jscomp$0, currentTime) - ); - } - } else currentEventTime = 0; - do - try { - if (isSync) - for (; null !== workInProgress; ) - workInProgress = performUnitOfWork(workInProgress); - else - for (; null !== workInProgress && !Scheduler_shouldYield(); ) - workInProgress = performUnitOfWork(workInProgress); - break; - } catch (thrownValue) { - resetContextDependencies(); - resetHooks(); - currentTime = workInProgress; - if (null === currentTime || null === currentTime.return) - throw (prepareFreshStack(root$jscomp$0, expirationTime), - (executionContext = lastPendingTime), - thrownValue); - currentTime.mode & 8 && - stopProfilerTimerIfRunningAndRecordDelta(currentTime, !0); - a: { - var root = root$jscomp$0, - returnFiber = currentTime.return, - sourceFiber = currentTime, - value = thrownValue, - renderExpirationTime$jscomp$0 = renderExpirationTime; - sourceFiber.effectTag |= 1024; - sourceFiber.firstEffect = sourceFiber.lastEffect = null; - if ( - null !== value && - "object" === typeof value && - "function" === typeof value.then - ) { - var thenable = value, - hasInvisibleParentBoundary = - 0 !== - (suspenseStackCursor.current & InvisibleParentSuspenseContext); - value = returnFiber; - do { - var JSCompiler_temp; - if ((JSCompiler_temp = 13 === value.tag)) - null !== value.memoizedState - ? (JSCompiler_temp = !1) - : ((JSCompiler_temp = value.memoizedProps), - (JSCompiler_temp = - void 0 === JSCompiler_temp.fallback +function handleError(root$jscomp$0, thrownValue) { + do { + try { + resetContextDependencies(); + resetHooks(); + if (null === workInProgress || null === workInProgress.return) + return ( + (workInProgressRootExitStatus = RootFatalErrored), + (workInProgressRootFatalError = thrownValue), + null + ); + workInProgress.mode & 8 && + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, !0); + a: { + var root = root$jscomp$0, + returnFiber = workInProgress.return, + sourceFiber = workInProgress, + value = thrownValue; + thrownValue = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.firstEffect = sourceFiber.lastEffect = null; + if ( + null !== value && + "object" === typeof value && + "function" === typeof value.then + ) { + var thenable = value, + hasInvisibleParentBoundary = + 0 !== (suspenseStackCursor.current & 1), + _workInProgress = returnFiber; + do { + var JSCompiler_temp; + if ((JSCompiler_temp = 13 === _workInProgress.tag)) { + var nextState = _workInProgress.memoizedState; + if (null !== nextState) + JSCompiler_temp = null !== nextState.dehydrated ? !0 : !1; + else { + var props = _workInProgress.memoizedProps; + JSCompiler_temp = + void 0 === props.fallback + ? !1 + : !0 !== props.unstable_avoidThisFallback + ? !0 + : hasInvisibleParentBoundary ? !1 - : !0 !== JSCompiler_temp.unstable_avoidThisFallback - ? !0 - : hasInvisibleParentBoundary - ? !1 - : !0)); - if (JSCompiler_temp) { - returnFiber = value.updateQueue; - null === returnFiber - ? ((returnFiber = new Set()), - returnFiber.add(thenable), - (value.updateQueue = returnFiber)) - : returnFiber.add(thenable); - if (0 === (value.mode & 2)) { - value.effectTag |= 64; - sourceFiber.effectTag &= -1957; - 1 === sourceFiber.tag && - (null === sourceFiber.alternate - ? (sourceFiber.tag = 17) - : ((renderExpirationTime$jscomp$0 = createUpdate( - 1073741823, - null - )), - (renderExpirationTime$jscomp$0.tag = 2), - enqueueUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ))); - sourceFiber.expirationTime = 1073741823; - break a; - } - sourceFiber = root; - root = renderExpirationTime$jscomp$0; - hasInvisibleParentBoundary = sourceFiber.pingCache; - null === hasInvisibleParentBoundary - ? ((hasInvisibleParentBoundary = sourceFiber.pingCache = new PossiblyWeakMap()), - (returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber)) - : ((returnFiber = hasInvisibleParentBoundary.get(thenable)), - void 0 === returnFiber && - ((returnFiber = new Set()), - hasInvisibleParentBoundary.set(thenable, returnFiber))); - returnFiber.has(root) || - (returnFiber.add(root), - (sourceFiber = pingSuspendedRoot.bind( - null, - sourceFiber, - thenable, - root - )), - (sourceFiber = tracing.unstable_wrap(sourceFiber)), - thenable.then(sourceFiber, sourceFiber)); - value.effectTag |= 2048; - value.expirationTime = renderExpirationTime$jscomp$0; + : !0; + } + } + if (JSCompiler_temp) { + var thenables = _workInProgress.updateQueue; + if (null === thenables) { + var updateQueue = new Set(); + updateQueue.add(thenable); + _workInProgress.updateQueue = updateQueue; + } else thenables.add(thenable); + if (0 === (_workInProgress.mode & 2)) { + _workInProgress.effectTag |= 64; + sourceFiber.effectTag &= -2981; + if (1 === sourceFiber.tag) + if (null === sourceFiber.alternate) sourceFiber.tag = 17; + else { + var update = createUpdate(1073741823, null); + update.tag = 2; + enqueueUpdate(sourceFiber, update); + } + sourceFiber.expirationTime = 1073741823; break a; } - value = value.return; - } while (null !== value); - value = Error( - (getComponentName(sourceFiber.type) || "A React component") + - " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + - getStackByFiberInDevAndProd(sourceFiber) - ); - } - workInProgressRootExitStatus !== RootCompleted && - (workInProgressRootExitStatus = RootErrored); - value = createCapturedValue(value, sourceFiber); - sourceFiber = returnFiber; - do { - switch (sourceFiber.tag) { - case 3: - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createRootErrorUpdate( - sourceFiber, - value, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 + value = void 0; + sourceFiber = thrownValue; + var pingCache = root.pingCache; + null === pingCache + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (value = new Set()), + pingCache.set(thenable, value)) + : ((value = pingCache.get(thenable)), + void 0 === value && + ((value = new Set()), pingCache.set(thenable, value))); + if (!value.has(sourceFiber)) { + value.add(sourceFiber); + var ping = pingSuspendedRoot.bind( + null, + root, + thenable, + sourceFiber ); - break a; - case 1: - if ( - ((thenable = value), - (root = sourceFiber.type), - (returnFiber = sourceFiber.stateNode), - 0 === (sourceFiber.effectTag & 64) && - ("function" === typeof root.getDerivedStateFromError || - (null !== returnFiber && - "function" === typeof returnFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - returnFiber - ))))) - ) { - sourceFiber.effectTag |= 2048; - sourceFiber.expirationTime = renderExpirationTime$jscomp$0; - renderExpirationTime$jscomp$0 = createClassErrorUpdate( - sourceFiber, - thenable, - renderExpirationTime$jscomp$0 - ); - enqueueCapturedUpdate( - sourceFiber, - renderExpirationTime$jscomp$0 - ); - break a; - } + thenable.then(ping, ping); + } + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + break a; } - sourceFiber = sourceFiber.return; - } while (null !== sourceFiber); - } - workInProgress = completeUnitOfWork(currentTime); - } - while (1); - executionContext = lastPendingTime; - resetContextDependencies(); - ReactCurrentDispatcher.current = prevDispatcher; - tracing.__interactionsRef.current = prevInteractions; - if (null !== workInProgress) - return renderRoot.bind(null, root$jscomp$0, expirationTime); - } - root$jscomp$0.finishedWork = root$jscomp$0.current.alternate; - root$jscomp$0.finishedExpirationTime = expirationTime; - if (resolveLocksOnRoot(root$jscomp$0, expirationTime)) return null; - workInProgressRoot = null; - switch (workInProgressRootExitStatus) { - case RootIncomplete: - throw ReactError(Error("Should have a work-in-progress.")); - case RootErrored: - return ( - (lastPendingTime = root$jscomp$0.lastPendingTime), - lastPendingTime < expirationTime - ? renderRoot.bind(null, root$jscomp$0, lastPendingTime) - : isSync - ? commitRoot.bind(null, root$jscomp$0) - : (prepareFreshStack(root$jscomp$0, expirationTime), - scheduleSyncCallback( - renderRoot.bind(null, root$jscomp$0, expirationTime) - ), - null) - ); - case RootSuspended: - if ( - 1073741823 === workInProgressRootLatestProcessedExpirationTime && - !isSync && - ((isSync = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now()), - 10 < isSync) - ) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - lastPendingTime = root$jscomp$0.lastPendingTime; - if (lastPendingTime < expirationTime) - return renderRoot.bind(null, root$jscomp$0, lastPendingTime); - root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - ); - return null; - } - return commitRoot.bind(null, root$jscomp$0); - case RootSuspendedWithDelay: - if (!isSync) { - if (workInProgressRootHasPendingPing) - return ( - prepareFreshStack(root$jscomp$0, expirationTime), - renderRoot.bind(null, root$jscomp$0, expirationTime) - ); - isSync = root$jscomp$0.lastPendingTime; - if (isSync < expirationTime) - return renderRoot.bind(null, root$jscomp$0, isSync); - 1073741823 !== workInProgressRootLatestSuspenseTimeout - ? (isSync = - 10 * (1073741821 - workInProgressRootLatestSuspenseTimeout) - - now()) - : 1073741823 === workInProgressRootLatestProcessedExpirationTime - ? (isSync = 0) - : ((isSync = - 10 * - (1073741821 - - workInProgressRootLatestProcessedExpirationTime) - - 5e3), - (lastPendingTime = now()), - (expirationTime = - 10 * (1073741821 - expirationTime) - lastPendingTime), - (isSync = lastPendingTime - isSync), - 0 > isSync && (isSync = 0), - (isSync = - (120 > isSync - ? 120 - : 480 > isSync - ? 480 - : 1080 > isSync - ? 1080 - : 1920 > isSync - ? 1920 - : 3e3 > isSync - ? 3e3 - : 4320 > isSync - ? 4320 - : 1960 * ceil(isSync / 1960)) - isSync), - expirationTime < isSync && (isSync = expirationTime)); - if (10 < isSync) - return ( - (root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - isSync - )), - null + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); + value = Error( + (getComponentName(sourceFiber.type) || "A React component") + + " suspended while rendering, but no fallback UI was specified.\n\nAdd a component higher in the tree to provide a loading indicator or placeholder to display." + + getStackByFiberInDevAndProd(sourceFiber) ); + } + workInProgressRootExitStatus !== RootCompleted && + (workInProgressRootExitStatus = RootErrored); + value = createCapturedValue(value, sourceFiber); + _workInProgress = returnFiber; + do { + switch (_workInProgress.tag) { + case 3: + thenable = value; + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update = createRootErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update); + break a; + case 1: + thenable = value; + var ctor = _workInProgress.type, + instance = _workInProgress.stateNode; + if ( + 0 === (_workInProgress.effectTag & 64) && + ("function" === typeof ctor.getDerivedStateFromError || + (null !== instance && + "function" === typeof instance.componentDidCatch && + (null === legacyErrorBoundariesThatAlreadyFailed || + !legacyErrorBoundariesThatAlreadyFailed.has(instance)))) + ) { + _workInProgress.effectTag |= 4096; + _workInProgress.expirationTime = thrownValue; + var _update2 = createClassErrorUpdate( + _workInProgress, + thenable, + thrownValue + ); + enqueueCapturedUpdate(_workInProgress, _update2); + break a; + } + } + _workInProgress = _workInProgress.return; + } while (null !== _workInProgress); } - return commitRoot.bind(null, root$jscomp$0); - case RootCompleted: - return !isSync && - 1073741823 !== workInProgressRootLatestProcessedExpirationTime && - null !== workInProgressRootCanSuspendUsingConfig && - ((lastPendingTime = workInProgressRootLatestProcessedExpirationTime), - (prevDispatcher = workInProgressRootCanSuspendUsingConfig), - (expirationTime = prevDispatcher.busyMinDurationMs | 0), - 0 >= expirationTime - ? (expirationTime = 0) - : ((isSync = prevDispatcher.busyDelayMs | 0), - (lastPendingTime = - now() - - (10 * (1073741821 - lastPendingTime) - - (prevDispatcher.timeoutMs | 0 || 5e3))), - (expirationTime = - lastPendingTime <= isSync - ? 0 - : isSync + expirationTime - lastPendingTime)), - 10 < expirationTime) - ? ((root$jscomp$0.timeoutHandle = scheduleTimeout( - commitRoot.bind(null, root$jscomp$0), - expirationTime - )), - null) - : commitRoot.bind(null, root$jscomp$0); - default: - throw ReactError(Error("Unknown root exit status.")); - } + workInProgress = completeUnitOfWork(workInProgress); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + continue; + } + break; + } while (1); +} +function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = ContextOnlyDispatcher; + return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher; +} +function pushInteractions(root) { + var prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + return prevInteractions; } function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) { expirationTime < workInProgressRootLatestProcessedExpirationTime && - 1 < expirationTime && + 2 < expirationTime && (workInProgressRootLatestProcessedExpirationTime = expirationTime); null !== suspenseConfig && expirationTime < workInProgressRootLatestSuspenseTimeout && - 1 < expirationTime && + 2 < expirationTime && ((workInProgressRootLatestSuspenseTimeout = expirationTime), (workInProgressRootCanSuspendUsingConfig = suspenseConfig)); } +function markUnprocessedUpdateTime(expirationTime) { + expirationTime > workInProgressRootNextUnprocessedUpdateTime && + (workInProgressRootNextUnprocessedUpdateTime = expirationTime); +} +function workLoopSync() { + for (; null !== workInProgress; ) + workInProgress = performUnitOfWork(workInProgress); +} +function workLoopConcurrent() { + for (; null !== workInProgress && !Scheduler_shouldYield(); ) + workInProgress = performUnitOfWork(workInProgress); +} function performUnitOfWork(unitOfWork) { var current$$1 = unitOfWork.alternate; 0 !== (unitOfWork.mode & 8) @@ -6291,7 +6343,7 @@ function completeUnitOfWork(unitOfWork) { do { var current$$1 = workInProgress.alternate; unitOfWork = workInProgress.return; - if (0 === (workInProgress.effectTag & 1024)) { + if (0 === (workInProgress.effectTag & 2048)) { if (0 === (workInProgress.mode & 8)) current$$1 = completeWork( current$$1, @@ -6350,7 +6402,7 @@ function completeUnitOfWork(unitOfWork) { } if (null !== current$$1) return current$$1; null !== unitOfWork && - 0 === (unitOfWork.effectTag & 1024) && + 0 === (unitOfWork.effectTag & 2048) && (null === unitOfWork.firstEffect && (unitOfWork.firstEffect = workInProgress.firstEffect), null !== workInProgress.lastEffect && @@ -6377,10 +6429,10 @@ function completeUnitOfWork(unitOfWork) { workInProgress.actualDuration = fiber; } if (null !== current$$1) - return (current$$1.effectTag &= 1023), current$$1; + return (current$$1.effectTag &= 2047), current$$1; null !== unitOfWork && ((unitOfWork.firstEffect = unitOfWork.lastEffect = null), - (unitOfWork.effectTag |= 1024)); + (unitOfWork.effectTag |= 2048)); } current$$1 = workInProgress.sibling; if (null !== current$$1) return current$$1; @@ -6390,134 +6442,90 @@ function completeUnitOfWork(unitOfWork) { (workInProgressRootExitStatus = RootCompleted); return null; } +function getRemainingExpirationTime(fiber) { + var updateExpirationTime = fiber.expirationTime; + fiber = fiber.childExpirationTime; + return updateExpirationTime > fiber ? updateExpirationTime : fiber; +} function commitRoot(root) { var renderPriorityLevel = getCurrentPriorityLevel(); runWithPriority(99, commitRootImpl.bind(null, root, renderPriorityLevel)); - null !== rootWithPendingPassiveEffects && - scheduleCallback(97, function() { - flushPassiveEffects(); - return null; - }); return null; } -function commitRootImpl(root, renderPriorityLevel) { +function commitRootImpl(root$jscomp$0, renderPriorityLevel$jscomp$0) { flushPassiveEffects(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError(Error("Should not already be working.")); - var finishedWork = root.finishedWork, - expirationTime = root.finishedExpirationTime; + throw Error("Should not already be working."); + var finishedWork = root$jscomp$0.finishedWork, + expirationTime = root$jscomp$0.finishedExpirationTime; if (null === finishedWork) return null; - root.finishedWork = null; - root.finishedExpirationTime = 0; - if (finishedWork === root.current) - throw ReactError( - Error( - "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." - ) + root$jscomp$0.finishedWork = null; + root$jscomp$0.finishedExpirationTime = 0; + if (finishedWork === root$jscomp$0.current) + throw Error( + "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." ); - root.callbackNode = null; - root.callbackExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - updateExpirationTimeBeforeCommit = - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit; - root.firstPendingTime = updateExpirationTimeBeforeCommit; - updateExpirationTimeBeforeCommit < root.lastPendingTime && - (root.lastPendingTime = updateExpirationTimeBeforeCommit); - root === workInProgressRoot && + root$jscomp$0.callbackNode = null; + root$jscomp$0.callbackExpirationTime = 0; + root$jscomp$0.callbackPriority = 90; + root$jscomp$0.nextKnownPendingLevel = 0; + var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime( + finishedWork + ); + root$jscomp$0.firstPendingTime = remainingExpirationTimeBeforeCommit; + expirationTime <= root$jscomp$0.lastSuspendedTime + ? (root$jscomp$0.firstSuspendedTime = root$jscomp$0.lastSuspendedTime = root$jscomp$0.nextKnownPendingLevel = 0) + : expirationTime <= root$jscomp$0.firstSuspendedTime && + (root$jscomp$0.firstSuspendedTime = expirationTime - 1); + expirationTime <= root$jscomp$0.lastPingedTime && + (root$jscomp$0.lastPingedTime = 0); + expirationTime <= root$jscomp$0.lastExpiredTime && + (root$jscomp$0.lastExpiredTime = 0); + root$jscomp$0 === workInProgressRoot && ((workInProgress = workInProgressRoot = null), (renderExpirationTime = 0)); 1 < finishedWork.effectTag ? null !== finishedWork.lastEffect ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - if (null !== updateExpirationTimeBeforeCommit) { - childExpirationTimeBeforeCommit = executionContext; + (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect)) + : (remainingExpirationTimeBeforeCommit = finishedWork) + : (remainingExpirationTimeBeforeCommit = finishedWork.firstEffect); + if (null !== remainingExpirationTimeBeforeCommit) { + var prevExecutionContext = executionContext; executionContext |= CommitContext; - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; + var prevInteractions = pushInteractions(root$jscomp$0); ReactCurrentOwner$2.current = null; - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (; null !== nextEffect; ) { - if (0 !== (nextEffect.effectTag & 256)) { - var current$$1 = nextEffect.alternate, - finishedWork$jscomp$0 = nextEffect; - switch (finishedWork$jscomp$0.tag) { - case 0: - case 11: - case 15: - commitHookEffectList( - UnmountSnapshot, - NoEffect$1, - finishedWork$jscomp$0 - ); - break; - case 1: - if ( - finishedWork$jscomp$0.effectTag & 256 && - null !== current$$1 - ) { - var prevProps = current$$1.memoizedProps, - prevState = current$$1.memoizedState, - instance = finishedWork$jscomp$0.stateNode, - snapshot = instance.getSnapshotBeforeUpdate( - finishedWork$jscomp$0.elementType === - finishedWork$jscomp$0.type - ? prevProps - : resolveDefaultProps( - finishedWork$jscomp$0.type, - prevProps - ), - prevState - ); - instance.__reactInternalSnapshotBeforeUpdate = snapshot; - } - break; - case 3: - case 5: - case 6: - case 4: - case 17: - break; - default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) - ); - } - } - nextEffect = nextEffect.nextEffect; - } + commitBeforeMutationEffects(); } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); commitTime = now$1(); - nextEffect = updateExpirationTimeBeforeCommit; + nextEffect = remainingExpirationTimeBeforeCommit; do try { - for (current$$1 = renderPriorityLevel; null !== nextEffect; ) { + for ( + var root = root$jscomp$0, + renderPriorityLevel = renderPriorityLevel$jscomp$0; + null !== nextEffect; + + ) { var effectTag = nextEffect.effectTag; if (effectTag & 128) { - var current$$1$jscomp$0 = nextEffect.alternate; - if (null !== current$$1$jscomp$0) { - var currentRef = current$$1$jscomp$0.ref; + var current$$1 = nextEffect.alternate; + if (null !== current$$1) { + var currentRef = current$$1.ref; null !== currentRef && ("function" === typeof currentRef ? currentRef(null) : (currentRef.current = null)); } } - switch (effectTag & 14) { + switch (effectTag & 1038) { case 2: commitPlacement(nextEffect); nextEffect.effectTag &= -3; @@ -6527,89 +6535,94 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect.effectTag &= -3; commitWork(nextEffect.alternate, nextEffect); break; + case 1024: + nextEffect.effectTag &= -1025; + break; + case 1028: + nextEffect.effectTag &= -1025; + commitWork(nextEffect.alternate, nextEffect); + break; case 4: commitWork(nextEffect.alternate, nextEffect); break; case 8: - (prevProps = nextEffect), - unmountHostComponents(prevProps, current$$1), - detachFiber(prevProps); + var current$$1$jscomp$0 = nextEffect; + unmountHostComponents( + root, + current$$1$jscomp$0, + renderPriorityLevel + ); + detachFiber(current$$1$jscomp$0); } nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } while (null !== nextEffect); - root.current = finishedWork; - nextEffect = updateExpirationTimeBeforeCommit; + root$jscomp$0.current = finishedWork; + nextEffect = remainingExpirationTimeBeforeCommit; do try { for ( - effectTag = root, current$$1$jscomp$0 = expirationTime; + effectTag = root$jscomp$0, current$$1 = expirationTime; null !== nextEffect; ) { var effectTag$jscomp$0 = nextEffect.effectTag; if (effectTag$jscomp$0 & 36) { - prevProps = effectTag; + renderPriorityLevel = effectTag; var current$$1$jscomp$1 = nextEffect.alternate; currentRef = nextEffect; - current$$1 = current$$1$jscomp$0; + root = current$$1; switch (currentRef.tag) { case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, currentRef); + commitHookEffectList(16, 32, currentRef); break; case 1: - var instance$jscomp$0 = currentRef.stateNode; + var instance = currentRef.stateNode; if (currentRef.effectTag & 4) if (null === current$$1$jscomp$1) - instance$jscomp$0.componentDidMount(); + instance.componentDidMount(); else { - var prevProps$jscomp$0 = + var prevProps = currentRef.elementType === currentRef.type ? current$$1$jscomp$1.memoizedProps : resolveDefaultProps( currentRef.type, current$$1$jscomp$1.memoizedProps ); - instance$jscomp$0.componentDidUpdate( - prevProps$jscomp$0, + instance.componentDidUpdate( + prevProps, current$$1$jscomp$1.memoizedState, - instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + instance.__reactInternalSnapshotBeforeUpdate ); } var updateQueue = currentRef.updateQueue; null !== updateQueue && - commitUpdateQueue( - currentRef, - updateQueue, - instance$jscomp$0, - current$$1 - ); + commitUpdateQueue(currentRef, updateQueue, instance, root); break; case 3: var _updateQueue = currentRef.updateQueue; if (null !== _updateQueue) { - prevProps = null; + renderPriorityLevel = null; if (null !== currentRef.child) switch (currentRef.child.tag) { case 5: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; break; case 1: - prevProps = currentRef.child.stateNode; + renderPriorityLevel = currentRef.child.stateNode; } commitUpdateQueue( currentRef, _updateQueue, - prevProps, - current$$1 + renderPriorityLevel, + root ); } break; @@ -6629,44 +6642,43 @@ function commitRootImpl(root, renderPriorityLevel) { currentRef.treeBaseDuration, currentRef.actualStartTime, commitTime, - prevProps.memoizedInteractions + renderPriorityLevel.memoizedInteractions ); break; case 13: + break; case 19: case 17: case 20: + case 21: break; default: - throw ReactError( - Error( - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); } } if (effectTag$jscomp$0 & 128) { + currentRef = void 0; var ref = nextEffect.ref; if (null !== ref) { - var instance$jscomp$1 = nextEffect.stateNode; + var instance$jscomp$0 = nextEffect.stateNode; switch (nextEffect.tag) { case 5: - var instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; break; default: - instanceToUse = instance$jscomp$1; + currentRef = instance$jscomp$0; } "function" === typeof ref - ? ref(instanceToUse) - : (ref.current = instanceToUse); + ? ref(currentRef) + : (ref.current = currentRef); } } - effectTag$jscomp$0 & 512 && (rootDoesHavePassiveEffects = !0); nextEffect = nextEffect.nextEffect; } } catch (error) { - if (null === nextEffect) - throw ReactError(Error("Should be working on an effect.")); + if (null === nextEffect) throw Error("Should be working on an effect."); captureCommitPhaseError(nextEffect, error); nextEffect = nextEffect.nextEffect; } @@ -6674,80 +6686,99 @@ function commitRootImpl(root, renderPriorityLevel) { nextEffect = null; requestPaint(); tracing.__interactionsRef.current = prevInteractions; - executionContext = childExpirationTimeBeforeCommit; - } else (root.current = finishedWork), (commitTime = now$1()); + executionContext = prevExecutionContext; + } else (root$jscomp$0.current = finishedWork), (commitTime = now$1()); if ((effectTag$jscomp$0 = rootDoesHavePassiveEffects)) (rootDoesHavePassiveEffects = !1), - (rootWithPendingPassiveEffects = root), + (rootWithPendingPassiveEffects = root$jscomp$0), (pendingPassiveEffectsExpirationTime = expirationTime), - (pendingPassiveEffectsRenderPriority = renderPriorityLevel); + (pendingPassiveEffectsRenderPriority = renderPriorityLevel$jscomp$0); else - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) - (renderPriorityLevel = nextEffect.nextEffect), + for ( + nextEffect = remainingExpirationTimeBeforeCommit; + null !== nextEffect; + + ) + (renderPriorityLevel$jscomp$0 = nextEffect.nextEffect), (nextEffect.nextEffect = null), - (nextEffect = renderPriorityLevel); - renderPriorityLevel = root.firstPendingTime; - if (0 !== renderPriorityLevel) { - current$$1$jscomp$1 = requestCurrentTime(); - current$$1$jscomp$1 = inferPriorityFromExpirationTime( - current$$1$jscomp$1, - renderPriorityLevel - ); + (nextEffect = renderPriorityLevel$jscomp$0); + renderPriorityLevel$jscomp$0 = root$jscomp$0.firstPendingTime; + if (0 !== renderPriorityLevel$jscomp$0) { if (null !== spawnedWorkDuringRender) for ( - instance$jscomp$0 = spawnedWorkDuringRender, + remainingExpirationTimeBeforeCommit = spawnedWorkDuringRender, spawnedWorkDuringRender = null, - prevProps$jscomp$0 = 0; - prevProps$jscomp$0 < instance$jscomp$0.length; - prevProps$jscomp$0++ + current$$1$jscomp$1 = 0; + current$$1$jscomp$1 < remainingExpirationTimeBeforeCommit.length; + current$$1$jscomp$1++ ) scheduleInteractions( - root, - instance$jscomp$0[prevProps$jscomp$0], - root.memoizedInteractions + root$jscomp$0, + remainingExpirationTimeBeforeCommit[current$$1$jscomp$1], + root$jscomp$0.memoizedInteractions ); - scheduleCallbackForRoot(root, current$$1$jscomp$1, renderPriorityLevel); + schedulePendingInteractions(root$jscomp$0, renderPriorityLevel$jscomp$0); } else legacyErrorBoundariesThatAlreadyFailed = null; - effectTag$jscomp$0 || finishPendingInteractions(root, expirationTime); - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode, expirationTime); - 1073741823 === renderPriorityLevel - ? root === rootWithNestedUpdates + effectTag$jscomp$0 || + finishPendingInteractions(root$jscomp$0, expirationTime); + 1073741823 === renderPriorityLevel$jscomp$0 + ? root$jscomp$0 === rootWithNestedUpdates ? nestedUpdateCount++ - : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root)) + : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root$jscomp$0)) : (nestedUpdateCount = 0); + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork.stateNode, expirationTime); + ensureRootIsScheduled(root$jscomp$0); if (hasUncaughtError) throw ((hasUncaughtError = !1), - (root = firstUncaughtError), + (root$jscomp$0 = firstUncaughtError), (firstUncaughtError = null), - root); + root$jscomp$0); if ((executionContext & LegacyUnbatchedContext) !== NoContext) return null; flushSyncCallbackQueue(); return null; } +function commitBeforeMutationEffects() { + for (; null !== nextEffect; ) { + var effectTag = nextEffect.effectTag; + 0 !== (effectTag & 256) && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect); + 0 === (effectTag & 512) || + rootDoesHavePassiveEffects || + ((rootDoesHavePassiveEffects = !0), + scheduleCallback(97, function() { + flushPassiveEffects(); + return null; + })); + nextEffect = nextEffect.nextEffect; + } +} function flushPassiveEffects() { + if (90 !== pendingPassiveEffectsRenderPriority) { + var priorityLevel = + 97 < pendingPassiveEffectsRenderPriority + ? 97 + : pendingPassiveEffectsRenderPriority; + pendingPassiveEffectsRenderPriority = 90; + return runWithPriority(priorityLevel, flushPassiveEffectsImpl); + } +} +function flushPassiveEffectsImpl() { if (null === rootWithPendingPassiveEffects) return !1; var root = rootWithPendingPassiveEffects, - expirationTime = pendingPassiveEffectsExpirationTime, - renderPriorityLevel = pendingPassiveEffectsRenderPriority; + expirationTime = pendingPassiveEffectsExpirationTime; rootWithPendingPassiveEffects = null; pendingPassiveEffectsExpirationTime = 0; - pendingPassiveEffectsRenderPriority = 90; - return runWithPriority( - 97 < renderPriorityLevel ? 97 : renderPriorityLevel, - flushPassiveEffectsImpl.bind(null, root, expirationTime) - ); -} -function flushPassiveEffectsImpl(root, expirationTime) { - var prevInteractions = tracing.__interactionsRef.current; - tracing.__interactionsRef.current = root.memoizedInteractions; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) - throw ReactError( - Error("Cannot flush passive effects while already rendering.") - ); + throw Error("Cannot flush passive effects while already rendering."); var prevExecutionContext = executionContext; executionContext |= CommitContext; - for (var effect = root.current.firstEffect; null !== effect; ) { + for ( + var prevInteractions = pushInteractions(root), + effect = root.current.firstEffect; + null !== effect; + + ) { try { var finishedWork = effect; if (0 !== (finishedWork.effectTag & 512)) @@ -6755,12 +6786,11 @@ function flushPassiveEffectsImpl(root, expirationTime) { case 0: case 11: case 15: - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork), - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork), + commitHookEffectList(0, 64, finishedWork); } } catch (error) { - if (null === effect) - throw ReactError(Error("Should be working on an effect.")); + if (null === effect) throw Error("Should be working on an effect."); captureCommitPhaseError(effect, error); } finishedWork = effect.nextEffect; @@ -6778,7 +6808,9 @@ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { sourceFiber = createRootErrorUpdate(rootFiber, sourceFiber, 1073741823); enqueueUpdate(rootFiber, sourceFiber); rootFiber = markUpdateTimeFromFiberToRoot(rootFiber, 1073741823); - null !== rootFiber && scheduleCallbackForRoot(rootFiber, 99, 1073741823); + null !== rootFiber && + (ensureRootIsScheduled(rootFiber), + schedulePendingInteractions(rootFiber, 1073741823)); } function captureCommitPhaseError(sourceFiber, error) { if (3 === sourceFiber.tag) @@ -6800,7 +6832,9 @@ function captureCommitPhaseError(sourceFiber, error) { sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); fiber = markUpdateTimeFromFiberToRoot(fiber, 1073741823); - null !== fiber && scheduleCallbackForRoot(fiber, 99, 1073741823); + null !== fiber && + (ensureRootIsScheduled(fiber), + schedulePendingInteractions(fiber, 1073741823)); break; } } @@ -6817,27 +6851,28 @@ function pingSuspendedRoot(root, thenable, suspendedTime) { now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) ? prepareFreshStack(root, renderExpirationTime) : (workInProgressRootHasPendingPing = !0) - : root.lastPendingTime < suspendedTime || - ((thenable = root.pingTime), + : isRootSuspendedAtTime(root, suspendedTime) && + ((thenable = root.lastPingedTime), (0 !== thenable && thenable < suspendedTime) || - ((root.pingTime = suspendedTime), + ((root.lastPingedTime = suspendedTime), root.finishedExpirationTime === suspendedTime && ((root.finishedExpirationTime = 0), (root.finishedWork = null)), - (thenable = requestCurrentTime()), - (thenable = inferPriorityFromExpirationTime(thenable, suspendedTime)), - scheduleCallbackForRoot(root, thenable, suspendedTime))); + ensureRootIsScheduled(root), + schedulePendingInteractions(root, suspendedTime))); } function resolveRetryThenable(boundaryFiber, thenable) { var retryCache = boundaryFiber.stateNode; null !== retryCache && retryCache.delete(thenable); - retryCache = requestCurrentTime(); - thenable = computeExpirationForFiber(retryCache, boundaryFiber, null); - retryCache = inferPriorityFromExpirationTime(retryCache, thenable); + thenable = 0; + 0 === thenable && + ((thenable = requestCurrentTime()), + (thenable = computeExpirationForFiber(thenable, boundaryFiber, null))); boundaryFiber = markUpdateTimeFromFiberToRoot(boundaryFiber, thenable); null !== boundaryFiber && - scheduleCallbackForRoot(boundaryFiber, retryCache, thenable); + (ensureRootIsScheduled(boundaryFiber), + schedulePendingInteractions(boundaryFiber, thenable)); } -var beginWork$$1 = void 0; +var beginWork$$1; beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (null !== current$$1) @@ -6886,7 +6921,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); workInProgress = bailoutOnAlreadyFinishedWork( @@ -6898,7 +6933,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { } push( suspenseStackCursor, - suspenseStackCursor.current & SubtreeSuspenseContextMask, + suspenseStackCursor.current & 1, workInProgress ); break; @@ -6930,6 +6965,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } + didReceiveUpdate = !1; } else didReceiveUpdate = !1; workInProgress.expirationTime = 0; @@ -7014,7 +7050,9 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); current$$1 = workInProgress.pendingProps; - renderState = readLazyComponentType(renderState); + initializeLazyComponentType(renderState); + if (1 !== renderState._status) throw renderState._result; + renderState = renderState._result; workInProgress.type = renderState; hasContext = workInProgress.tag = resolveLazyComponentTag(renderState); current$$1 = resolveDefaultProps(renderState, current$$1); @@ -7057,12 +7095,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { ); break; default: - throw ReactError( - Error( - "Element type is invalid. Received a promise that resolves to: " + - renderState + - ". Lazy element type must resolve to a class or function." - ) + throw Error( + "Element type is invalid. Received a promise that resolves to: " + + renderState + + ". Lazy element type must resolve to a class or function." ); } return workInProgress; @@ -7102,10 +7138,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); updateExpirationTime = workInProgress.updateQueue; if (null === updateExpirationTime) - throw ReactError( - Error( - "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); renderState = workInProgress.memoizedState; renderState = null !== renderState ? renderState.element : null; @@ -7143,7 +7177,8 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - workInProgress.child + (workInProgress = workInProgress.child), + workInProgress ); case 6: return ( @@ -7234,7 +7269,7 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { pushProvider(workInProgress, hasContext); if (null !== getDerivedStateFromProps) { var oldValue = getDerivedStateFromProps.value; - hasContext = is(oldValue, hasContext) + hasContext = is$1(oldValue, hasContext) ? 0 : ("function" === typeof updateExpirationTime._calculateChangedBits ? updateExpirationTime._calculateChangedBits( @@ -7423,10 +7458,10 @@ beginWork$$1 = function(current$$1, workInProgress, renderExpirationTime) { renderExpirationTime ); } - throw ReactError( - Error( - "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Unknown unit of work tag (" + + workInProgress.tag + + "). This error is likely caused by a bug in React. Please file an issue." ); }; function scheduleInteractions(root, expirationTime, interactions) { @@ -7450,6 +7485,9 @@ function scheduleInteractions(root, expirationTime, interactions) { ); } } +function schedulePendingInteractions(root, expirationTime) { + scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current); +} function startWorkOnPendingInteractions(root, expirationTime) { var interactions = new Set(); root.pendingInteractionMap.forEach(function( @@ -7477,13 +7515,10 @@ function startWorkOnPendingInteractions(root, expirationTime) { } } function finishPendingInteractions(root, committedExpirationTime) { - var earliestRemainingTimeAfterCommit = root.firstPendingTime, - subscriber = void 0; + var earliestRemainingTimeAfterCommit = root.firstPendingTime; try { - if ( - ((subscriber = tracing.__subscriberRef.current), - null !== subscriber && 0 < root.memoizedInteractions.size) - ) + var subscriber = tracing.__subscriberRef.current; + if (null !== subscriber && 0 < root.memoizedInteractions.size) subscriber.onWorkStopped( root.memoizedInteractions, 1e3 * committedExpirationTime + root.interactionThreadID @@ -7691,12 +7726,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - throw ReactError( - Error( - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + - (null == type ? type : typeof type) + - "." - ) + throw Error( + "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + + (null == type ? type : typeof type) + + "." ); } key = createFiber(fiberTag, pendingProps, key, mode); @@ -7740,22 +7773,57 @@ function FiberRootNode(containerInfo, tag, hydrate) { this.timeoutHandle = -1; this.pendingContext = this.context = null; this.hydrate = hydrate; - this.callbackNode = this.firstBatch = null; - this.pingTime = this.lastPendingTime = this.firstPendingTime = this.callbackExpirationTime = 0; + this.callbackNode = null; + this.callbackPriority = 90; + this.lastExpiredTime = this.lastPingedTime = this.nextKnownPendingLevel = this.lastSuspendedTime = this.firstSuspendedTime = this.firstPendingTime = 0; this.interactionThreadID = tracing.unstable_getThreadID(); this.memoizedInteractions = new Set(); this.pendingInteractionMap = new Map(); } +function isRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime; + root = root.lastSuspendedTime; + return ( + 0 !== firstSuspendedTime && + firstSuspendedTime >= expirationTime && + root <= expirationTime + ); +} +function markRootSuspendedAtTime(root, expirationTime) { + var firstSuspendedTime = root.firstSuspendedTime, + lastSuspendedTime = root.lastSuspendedTime; + firstSuspendedTime < expirationTime && + (root.firstSuspendedTime = expirationTime); + if (lastSuspendedTime > expirationTime || 0 === firstSuspendedTime) + root.lastSuspendedTime = expirationTime; + expirationTime <= root.lastPingedTime && (root.lastPingedTime = 0); + expirationTime <= root.lastExpiredTime && (root.lastExpiredTime = 0); +} +function markRootUpdatedAtTime(root, expirationTime) { + expirationTime > root.firstPendingTime && + (root.firstPendingTime = expirationTime); + var firstSuspendedTime = root.firstSuspendedTime; + 0 !== firstSuspendedTime && + (expirationTime >= firstSuspendedTime + ? (root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = 0) + : expirationTime >= root.lastSuspendedTime && + (root.lastSuspendedTime = expirationTime + 1), + expirationTime > root.nextKnownPendingLevel && + (root.nextKnownPendingLevel = expirationTime)); +} +function markRootExpiredAtTime(root, expirationTime) { + var lastExpiredTime = root.lastExpiredTime; + if (0 === lastExpiredTime || lastExpiredTime > expirationTime) + root.lastExpiredTime = expirationTime; +} function findHostInstance(component) { var fiber = component._reactInternalFiber; if (void 0 === fiber) { if ("function" === typeof component.render) - throw ReactError(Error("Unable to find node on an unmounted component.")); - throw ReactError( - Error( - "Argument appears to not be a ReactComponent. Keys: " + - Object.keys(component) - ) + throw Error("Unable to find node on an unmounted component."); + throw Error( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) ); } component = findCurrentHostFiber(fiber); @@ -7765,23 +7833,20 @@ function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, currentTime = requestCurrentTime(), suspenseConfig = ReactCurrentBatchConfig.suspense; - current$$1 = computeExpirationForFiber( + currentTime = computeExpirationForFiber( currentTime, current$$1, suspenseConfig ); - currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { if ( - 2 !== isFiberMountedImpl(parentComponent) || + getNearestMountedFiber(parentComponent) !== parentComponent || 1 !== parentComponent.tag ) - throw ReactError( - Error( - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ) + 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." ); var parentContext = parentComponent; do { @@ -7799,10 +7864,8 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - throw ReactError( - Error( - "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." - ) + throw Error( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); } if (1 === parentComponent.tag) { @@ -7821,14 +7884,13 @@ function updateContainer(element, container, parentComponent, callback) { null === container.context ? (container.context = parentComponent) : (container.pendingContext = parentComponent); - container = callback; - suspenseConfig = createUpdate(current$$1, suspenseConfig); - suspenseConfig.payload = { element: element }; - container = void 0 === container ? null : container; - null !== container && (suspenseConfig.callback = container); - enqueueUpdate(currentTime, suspenseConfig); - scheduleUpdateOnFiber(currentTime, current$$1); - return current$$1; + container = createUpdate(currentTime, suspenseConfig); + container.payload = { element: element }; + callback = void 0 === callback ? null : callback; + null !== callback && (container.callback = callback); + enqueueUpdate(current$$1, container); + scheduleUpdateOnFiber(current$$1, currentTime); + return currentTime; } function createPortal(children, containerInfo, implementation) { var key = @@ -7841,31 +7903,11 @@ function createPortal(children, containerInfo, implementation) { implementation: implementation }; } -function _inherits(subClass, superClass) { - if ("function" !== typeof superClass && null !== superClass) - throw new TypeError( - "Super expression must either be null or a function, not " + - typeof superClass - ); - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - superClass && - (Object.setPrototypeOf - ? Object.setPrototypeOf(subClass, superClass) - : (subClass.__proto__ = superClass)); -} -var getInspectorDataForViewTag = void 0; -getInspectorDataForViewTag = function() { - throw ReactError( - Error("getInspectorDataForViewTag() is not available in production") - ); -}; +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; if ("number" === typeof componentOrHandle) return componentOrHandle; @@ -7898,33 +7940,23 @@ var roots = new Map(), NativeComponent: (function(findNodeHandle, findHostInstance) { return (function(_React$Component) { function ReactNativeComponent() { - if (!(this instanceof ReactNativeComponent)) - throw new TypeError("Cannot call a class as a function"); - var call = _React$Component.apply(this, arguments); - if (!this) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return !call || - ("object" !== typeof call && "function" !== typeof call) - ? this - : call; + return _React$Component.apply(this, arguments) || this; } - _inherits(ReactNativeComponent, _React$Component); - ReactNativeComponent.prototype.blur = function() { + _inheritsLoose(ReactNativeComponent, _React$Component); + var _proto = ReactNativeComponent.prototype; + _proto.blur = function() { ReactNativePrivateInterface.TextInputState.blurTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.focus = function() { + _proto.focus = function() { ReactNativePrivateInterface.TextInputState.focusTextInput( findNodeHandle(this) ); }; - ReactNativeComponent.prototype.measure = function(callback) { - var maybeInstance = void 0; + _proto.measure = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7937,10 +7969,9 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureInWindow = function(callback) { - var maybeInstance = void 0; + _proto.measureInWindow = function(callback) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -7953,34 +7984,32 @@ var roots = new Map(), mountSafeCallback_NOT_REALLY_SAFE(this, callback) )); }; - ReactNativeComponent.prototype.measureLayout = function( + _proto.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }; - ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { - var maybeInstance = void 0; + _proto.setNativeProps = function(nativeProps) { try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8060,9 +8089,8 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -8076,9 +8104,8 @@ var roots = new Map(), )); }, measureInWindow: function(callback) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} null != maybeInstance && (maybeInstance.canonical @@ -8092,29 +8119,27 @@ var roots = new Map(), )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} - null == maybeInstance || - maybeInstance.canonical || - ((maybeInstance = void 0), - "number" === typeof relativeToNativeNode - ? (maybeInstance = relativeToNativeNode) - : relativeToNativeNode._nativeTag && - (maybeInstance = relativeToNativeNode._nativeTag), - null != maybeInstance && + if (null != maybeInstance && !maybeInstance.canonical) { + if ("number" === typeof relativeToNativeNode) + var relativeNode = relativeToNativeNode; + else + relativeToNativeNode._nativeTag && + (relativeNode = relativeToNativeNode._nativeTag); + null != relativeNode && ReactNativePrivateInterface.UIManager.measureLayout( findNodeHandle(this), - maybeInstance, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - )); + ); + } }, setNativeProps: function(nativeProps) { - var maybeInstance = void 0; try { - maybeInstance = findHostInstance(this); + var maybeInstance = findHostInstance(this); } catch (error) {} if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = @@ -8181,9 +8206,11 @@ var roots = new Map(), ); })({ findFiberByHostInstance: getInstanceFromTag, - getInspectorDataForViewTag: getInspectorDataForViewTag, + getInspectorDataForViewTag: function() { + throw Error("getInspectorDataForViewTag() is not available in production"); + }, bundleType: 0, - version: "16.8.6", + version: "16.10.2", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/shims/ReactNativeTypes.js b/Libraries/Renderer/shims/ReactNativeTypes.js index 7f6209afb0f3d7..0ef08d294d8e5d 100644 --- a/Libraries/Renderer/shims/ReactNativeTypes.js +++ b/Libraries/Renderer/shims/ReactNativeTypes.js @@ -83,7 +83,6 @@ export type ViewConfigGetter = () => ReactNativeBaseComponentViewConfig<>; /** * Class only exists for its Flow type. */ -export type {ReactNativeComponent}; class ReactNativeComponent extends React.Component { blur(): void {} focus(): void {} @@ -201,7 +200,6 @@ export type ReactFaricEvent = { export type ReactNativeResponderEvent = { nativeEvent: ReactFaricEvent, - responderTarget: null | ReactNativeEventTarget, target: null | ReactNativeEventTarget, type: string, }; @@ -227,9 +225,8 @@ export type ReactNativeResponderContext = { ): void, addRootEventTypes: (rootEventTypes: Array) => void, removeRootEventTypes: (rootEventTypes: Array) => void, - setTimeout: (func: () => void, timeout: number) => number, - clearTimeout: (timerId: number) => void, getTimeStamp: () => number, + getResponderNode(): ReactNativeEventTarget | null, }; export type PointerType = diff --git a/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js b/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js index 9b70337bfdfe9e..4653e2db9be486 100644 --- a/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js +++ b/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js @@ -12,16 +12,27 @@ 'use strict'; -const invariant = require('invariant'); - import type { ReactNativeBaseComponentViewConfig, ViewConfigGetter, } from './ReactNativeTypes'; +const invariant = require('invariant'); + // Event configs -const customBubblingEventTypes: {...} = {}; -const customDirectEventTypes: {...} = {}; +const customBubblingEventTypes: { + [eventName: string]: $ReadOnly<{| + phasedRegistrationNames: $ReadOnly<{| + captured: string, + bubbled: string, + |}>, + |}>, +} = {}; +const customDirectEventTypes: { + [eventName: string]: $ReadOnly<{| + registrationName: string, + |}>, +} = {}; exports.customBubblingEventTypes = customBubblingEventTypes; exports.customDirectEventTypes = customDirectEventTypes; diff --git a/Libraries/Renderer/shims/ReactTypes.js b/Libraries/Renderer/shims/ReactTypes.js index 7f72ce6782c09a..97033ba9170353 100644 --- a/Libraries/Renderer/shims/ReactTypes.js +++ b/Libraries/Renderer/shims/ReactTypes.js @@ -85,7 +85,6 @@ export type ReactEventResponderInstance = {| responder: ReactEventResponder, rootEventTypes: null | Set, state: Object, - target: mixed, |}; export type ReactEventResponderListener = {| @@ -97,6 +96,7 @@ export type ReactEventResponder = { $$typeof: Symbol | number, displayName: string, targetEventTypes: null | Array, + targetPortalPropagation: boolean, rootEventTypes: null | Array, getInitialState: null | ((props: Object) => Object), onEvent: @@ -107,9 +107,6 @@ export type ReactEventResponder = { | ((event: E, context: C, props: Object, state: Object) => void), onMount: null | ((context: C, props: Object, state: Object) => void), onUnmount: null | ((context: C, props: Object, state: Object) => void), - onOwnershipChange: - | null - | ((context: C, props: Object, state: Object) => void), }; export type EventPriority = 0 | 1 | 2; @@ -162,3 +159,26 @@ export type ReactFundamentalComponent = {| $$typeof: Symbol | number, impl: ReactFundamentalImpl, |}; + +export type ReactScope = {| + $$typeof: Symbol | number, +|}; + +export type ReactScopeMethods = {| + getChildren(): null | Array, + getChildrenFromRoot(): null | Array, + getParent(): null | ReactScopeMethods, + getProps(): Object, + queryAllNodes( + (type: string | Object, props: Object) => boolean, + ): null | Array, + queryFirstNode( + (type: string | Object, props: Object) => boolean, + ): null | Object, + containsNode(Object): boolean, +|}; + +export type ReactScopeInstance = {| + fiber: Object, + methods: null | ReactScopeMethods, +|}; diff --git a/package.json b/package.json index 682c86d42650e6..7d1f50c0dd4c35 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,7 @@ "test-ios": "./scripts/objc-test.sh test" }, "peerDependencies": { - "react": "16.9.0" + "react": "16.10.2" }, "dependencies": { "@babel/runtime": "^7.0.0", @@ -111,7 +111,7 @@ "react-devtools-core": "^4.0.6", "react-refresh": "^0.4.0", "regenerator-runtime": "^0.13.2", - "scheduler": "0.15.0", + "scheduler": "0.16.2", "stacktrace-parser": "^0.1.3", "use-subscription": "^1.0.0", "whatwg-fetch": "^3.0.0" @@ -147,8 +147,8 @@ "jscodeshift": "^0.6.2", "mkdirp": "^0.5.1", "prettier": "1.17.0", - "react": "16.9.0", - "react-test-renderer": "16.9.0", + "react": "16.10.2", + "react-test-renderer": "16.10.2", "shelljs": "^0.7.8", "signedsource": "^1.0.0", "ws": "^6.1.4", diff --git a/yarn.lock b/yarn.lock index 53583871e85eac..f5ec894a4498e1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5873,30 +5873,30 @@ react-is@^16.8.1, react-is@^16.8.4: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.4.tgz#90f336a68c3a29a096a3d648ab80e87ec61482a2" integrity sha512-PVadd+WaUDOAciICm/J1waJaSvgq+4rHE/K70j0PFqKhkTBsPv/82UGQJNXAngz1fOQLLxI6z1sEDmJDQhCTAA== -react-is@^16.9.0: - version "16.9.0" - resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.9.0.tgz#21ca9561399aad0ff1a7701c01683e8ca981edcb" - integrity sha512-tJBzzzIgnnRfEm046qRcURvwQnZVXmuCbscxUO5RWrGTXpon2d4c8mI0D8WE6ydVIm29JiLB6+RslkIvym9Rjw== +react-is@^16.8.6: + version "16.10.2" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.10.2.tgz#984120fd4d16800e9a738208ab1fba422d23b5ab" + integrity sha512-INBT1QEgtcCCgvccr5/86CfD71fw9EPmDxgiJX4I2Ddr6ZsV6iFXsuby+qWJPtmNuMY0zByTsG4468P7nHuNWA== react-refresh@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.4.0.tgz#d421f9bd65e0e4b9822a399f14ac56bda9c92292" integrity sha512-bacjSio8GOtzNZKZZM6EWqbhlbb6pr28JWJWFTLwEBKvPIBRo6/Ob68D2EWZA2VyTdQxAh+TRnCYOPNKsQiXTA== -react-test-renderer@16.9.0: - version "16.9.0" - resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-16.9.0.tgz#7ed657a374af47af88f66f33a3ef99c9610c8ae9" - integrity sha512-R62stB73qZyhrJo7wmCW9jgl/07ai+YzvouvCXIJLBkRlRqLx4j9RqcLEAfNfU3OxTGucqR2Whmn3/Aad6L3hQ== +react-test-renderer@16.10.2: + version "16.10.2" + resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-16.10.2.tgz#4d8492f8678c9b43b721a7d79ed0840fdae7c518" + integrity sha512-k9Qzyev6cTIcIfrhgrFlYQAFxh5EEDO6ALNqYqmKsWVA7Q/rUMTay5nD3nthi6COmYsd4ghVYyi8U86aoeMqYQ== dependencies: object-assign "^4.1.1" prop-types "^15.6.2" - react-is "^16.9.0" - scheduler "^0.15.0" + react-is "^16.8.6" + scheduler "^0.16.2" -react@16.9.0: - version "16.9.0" - resolved "https://registry.yarnpkg.com/react/-/react-16.9.0.tgz#40ba2f9af13bc1a38d75dbf2f4359a5185c4f7aa" - integrity sha512-+7LQnFBwkiw+BobzOF6N//BdoNw0ouwmSJTEm9cglOOmsg/TMiFHZLe2sEoN5M7LgJTj9oHH0gxklfnQe66S1w== +react@16.10.2: + version "16.10.2" + resolved "https://registry.yarnpkg.com/react/-/react-16.10.2.tgz#a5ede5cdd5c536f745173c8da47bda64797a4cf0" + integrity sha512-MFVIq0DpIhrHFyqLU0S3+4dIcBhhOvBE8bJ/5kHPVOVaGdo0KuiQzpcjCPsf585WvhypqtrMILyoE2th6dT+Lw== dependencies: loose-envify "^1.1.0" object-assign "^4.1.1" @@ -6291,10 +6291,10 @@ sax@^1.2.1, sax@^1.2.4: resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== -scheduler@0.15.0, scheduler@^0.15.0: - version "0.15.0" - resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.15.0.tgz#6bfcf80ff850b280fed4aeecc6513bc0b4f17f8e" - integrity sha512-xAefmSfN6jqAa7Kuq7LIJY0bwAPG3xlCj0HMEBQk1lxYiDKZscY2xJ5U/61ZTrYbmNQbXa+gc7czPkVo11tnCg== +scheduler@0.16.2, scheduler@^0.16.2: + version "0.16.2" + resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.16.2.tgz#f74cd9d33eff6fc554edfb79864868e4819132c1" + integrity sha512-BqYVWqwz6s1wZMhjFvLfVR5WXP7ZY32M/wYPo04CcuPM7XZEbV2TBNW7Z0UkguPTl0dWMA59VbNXxK6q+pHItg== dependencies: loose-envify "^1.1.0" object-assign "^4.1.1"