From 5f00f4c6ea20d5cb88ca264419233b0230dc1676 Mon Sep 17 00:00:00 2001 From: Eli White Date: Wed, 17 Apr 2019 11:59:48 -0700 Subject: [PATCH] React sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: This sync includes the following changes: - **[1b2159acc](https://github.com/facebook/react/commit/1b2159acc )**: [React Native] measure calls will now call FabricUIManager (#15324) //// - **[c7a959982](https://github.com/facebook/react/commit/c7a959982 )**: [React Native] Add tests to paper renderer for measure, measureLayout (#15323) //// - **[aece8119c](https://github.com/facebook/react/commit/aece8119c )**: Refactor EventComponent logic + add onOwnershipChange callback (#15354) //// - **[183d1f42e](https://github.com/facebook/react/commit/183d1f42e )**: Fix: Measure expiration times relative to module initialization (#15357) //// - **[b4bc33a58](https://github.com/facebook/react/commit/b4bc33a58 )**: Fix areHookInputsEqual method warning params order (#15345) //<砖家>// - **[29fb5862f](https://github.com/facebook/react/commit/29fb5862f )**: Move EventComponent state creation to complete phase + tests (#15352) //// - **[745baf2e0](https://github.com/facebook/react/commit/745baf2e0 )**: Provide new jsx transform target for reactjs/rfcs#107 (#15141) //// - **[81a61b1d1](https://github.com/facebook/react/commit/81a61b1d1 )**: React events: add delay props to Press module (#15340) //// - **[4064ea9fa](https://github.com/facebook/react/commit/4064ea9fa )**: Experimental event API: Support EventComponent onUnmount responder callback (#15335) //// - **[4fbbae8af](https://github.com/facebook/react/commit/4fbbae8af )**: Add full TouchHitTarget hit slop (experimental event API) to ReactDOM (#15308) //// - **[958b6173f](https://github.com/facebook/react/commit/958b6173f )**: Add delay props to Hover event module (#15325) //// - **[c3cc936da](https://github.com/facebook/react/commit/c3cc936da )**: Add Hover,Focus,Press docs to REAMDE (#15328) //// - **[49595e921](https://github.com/facebook/react/commit/49595e921 )**: [New Scheduler] Fix: Suspending an expired update (#15326) //// - **[b93a8a9bb](https://github.com/facebook/react/commit/b93a8a9bb )**: Experimental event API: refactor responder modules for lifecycle inclusion (#15322) //// - **[937d262f5](https://github.com/facebook/react/commit/937d262f5 )**: React events: keyboard press, types, tests (#15314) //// - **[7a2dc4853](https://github.com/facebook/react/commit/7a2dc4853 )**: Allow DevTools to toggle Suspense fallbacks (#15232) //// - **[43b1f74c8](https://github.com/facebook/react/commit/43b1f74c8 )**: Alternate fix for #14198 //// - **[41aa345d2](https://github.com/facebook/react/commit/41aa345d2 )**: Fix a crash in Suspense with findDOMNode //// - **[6d0effad7](https://github.com/facebook/react/commit/6d0effad7 )**: Expose extra internals in FB build of react-dom/unstable-new-scheduler (#15311) //// - **[3a44ccefe](https://github.com/facebook/react/commit/3a44ccefe )**: Fix feature flags react-dom/unstable-new-scheduler (#15309) //// - **[92a1d8fea](https://github.com/facebook/react/commit/92a1d8fea )**: mark react-events as private so we publish script skips it for now (#15307) //// - **[e5c59359c](https://github.com/facebook/react/commit/e5c59359c )**: Prevent bundling of Node polyfills when importing TestUtils/TestRenderer (#15305) //// - **[73187239a](https://github.com/facebook/react/commit/73187239a )**: writing unit tests in experimental event Drag API (#15297) //// - **[89064fe68](https://github.com/facebook/react/commit/89064fe68 )**: Adds displayName to EventComponent and EventTarget (#15268) //// - **[fc6a9f1a1](https://github.com/facebook/react/commit/fc6a9f1a1 )**: Add test for async event dispatching (#15300) //// - **[38fa84088](https://github.com/facebook/react/commit/38fa84088 )**: Experiemental event API - wrap async dispatched events (#15299) //// - **[4d5cb64aa](https://github.com/facebook/react/commit/4d5cb64aa )**: Rewrite ReactFiberScheduler for better integration with Scheduler package (#15151) //// - **[aed0e1c30](https://github.com/facebook/react/commit/aed0e1c30 )**: await act(async () => ...) (#14853) //// - **[4c75881ee](https://github.com/facebook/react/commit/4c75881ee )**: Remove maxDuration from tests (#15272) //// - **[9307932fe](https://github.com/facebook/react/commit/9307932fe )**: Refactor event object creation for the experimental event API (#15295) //// - **[6a1e6b2f7](https://github.com/facebook/react/commit/6a1e6b2f7 )**: Experimental event API: loosen EventTarget constraints and warnings (#15292) //// - **[f243deab8](https://github.com/facebook/react/commit/f243deab8 )**: Add tests for Press responder event module (#15290) //// - **[296c4393d](https://github.com/facebook/react/commit/296c4393d )**: Add Press event prop types and fix a check in Safari (#15288) //// - **[4482fdded](https://github.com/facebook/react/commit/4482fdded )**: Fix host context issues around EventComponents and EventTargets (#15284) //// - **[5ef0d1d29](https://github.com/facebook/react/commit/5ef0d1d29 )**: Rename hover props in experimental event API and write unit tests (#15283) //// - **[9444a5472](https://github.com/facebook/react/commit/9444a5472 )**: Warn on nested EventTragets in experimental event API (#15287) //// - **[7f1f5ddc3](https://github.com/facebook/react/commit/7f1f5ddc3 )**: Rename press props in experimental event API (#15263) //// - **[2e02469fa](https://github.com/facebook/react/commit/2e02469fa )**: ReactNative's ref.measureLayout now takes a ref (#15126) //// - **[1b94fd215](https://github.com/facebook/react/commit/1b94fd215 )**: Make setNativeProps a no-op with Fabric renderer (#15094) //// - **[08055a625](https://github.com/facebook/react/commit/08055a625 )**: Fix Press module in experimental event API (#15262) //// - **[f4625f518](https://github.com/facebook/react/commit/f4625f518 )**: Fix on(Long)PressChange events in experimental press event API (#15256) //// - **[a41b21770](https://github.com/facebook/react/commit/a41b21770 )**: Add additional event API responder surfaces (#15248) //// - **[700f17be6](https://github.com/facebook/react/commit/700f17be6 )**: Fix longpress in experimental Press event module (#15246) //// - **[5d336df70](https://github.com/facebook/react/commit/5d336df70 )**: Allow for null targetFiber for root event handling (#15247) //// - **[c6f3524df](https://github.com/facebook/react/commit/c6f3524df )**: Adds React event component and React event target support to SSR renderer (#15242) //// - **[c7a2dce50](https://github.com/facebook/react/commit/c7a2dce50 )**: Disable JS urls at build level for www (#15230) //// - **[fb6b50871](https://github.com/facebook/react/commit/fb6b50871 )**: Update versions for 16.8.6 //// - **[1cfd25668](https://github.com/facebook/react/commit/1cfd25668 )**: Fix circular module imports causing file size increase (#15231) //// - **[669cafb36](https://github.com/facebook/react/commit/669cafb36 )**: Adds experimental event component responder surfaces (#15228) //// - **[d8cb10f11](https://github.com/facebook/react/commit/d8cb10f11 )**: Enabled warnAboutDeprecatedLifecycles flag by default (#15186) //// - **[80f8b0d51](https://github.com/facebook/react/commit/80f8b0d51 )**: Add part of the event responder system for experimental event API (#15179) //// - **[5c2b2c085](https://github.com/facebook/react/commit/5c2b2c085 )**: Warn about async infinite useEffect loop (#15180) //// - **[8e9a013c0](https://github.com/facebook/react/commit/8e9a013c0 )**: Release 16.8.5 //// - **[f33e5790b](https://github.com/facebook/react/commit/f33e5790b )**: eslint-plugin-react-hooks@1.6.0 //// - **[b1cccd1ed](https://github.com/facebook/react/commit/b1cccd1ed )**: Warn about setState directly in dep-less useEffect (#15184) //// - **[78f2775ed](https://github.com/facebook/react/commit/78f2775ed )**: Flip event passive logic on passiveBrowserEventsSupported (#15190) //// - **[f161ee2eb](https://github.com/facebook/react/commit/f161ee2eb )**: React.warn() and React.error() (#15170) //// - **[78968bb3d](https://github.com/facebook/react/commit/78968bb3d )**: Validate useEffect without deps too (#15183) //// - **[4b8e1641b](https://github.com/facebook/react/commit/4b8e1641b )**: Fork performWork instead of using boolean flag (#15169) //// - **[56035dac6](https://github.com/facebook/react/commit/56035dac6 )**: unstable_Profiler -> Profiler (#15172) //// - **[31518135c](https://github.com/facebook/react/commit/31518135c )**: Strengthen nested update counter test coverage (#15166) //// - **[66f280c87](https://github.com/facebook/react/commit/66f280c87 )**: Add internal logic for listening to event responders (#15168) //// - **[b1a56abd6](https://github.com/facebook/react/commit/b1a56abd6 )**: Fork ReactFiberScheduler with feature flag //// - **[45f571736](https://github.com/facebook/react/commit/45f571736 )**: ReactFiberScheduler -> ReactFiberScheduler.old //// - **[c05b4b81f](https://github.com/facebook/react/commit/c05b4b81f )**: Link to useLayoutEffect gist in a warning (#15158) //// - **[061d6ce3c](https://github.com/facebook/react/commit/061d6ce3c )**: fix(react-dom): access iframe contentWindow instead of contentDocument (#15099) //// - **[b83e01cad](https://github.com/facebook/react/commit/b83e01cad )**: Adds more scaffolding for experimental event API (#15112) //// - **[daeda44d8](https://github.com/facebook/react/commit/daeda44d8 )**: Follow up to 15150 (#15152) //// - **[acd65db5b](https://github.com/facebook/react/commit/acd65db5b )**: Deprecate module pattern (factory) components (#15145) //// - **[55cc921c5](https://github.com/facebook/react/commit/55cc921c5 )**: Adds react-events package for internal testing (#15150) //// - **[7ad738630](https://github.com/facebook/react/commit/7ad738630 )**: Improve warning for invalid class contextType (#15142) //// - **[1e3364e76](https://github.com/facebook/react/commit/1e3364e76 )**: Test that we don't suspend when disabling yielding (#15143) //// - **[42c3c967d](https://github.com/facebook/react/commit/42c3c967d )**: Compile invariant directly to throw expressions (#15071) //// - **[df7b87d25](https://github.com/facebook/react/commit/df7b87d25 )**: Warn for Context.Consumer with contextType (#14831) //// - **[2b93d686e](https://github.com/facebook/react/commit/2b93d686e )**: Add more info to invalid hook call error message (#15139) //// - **[d926936f0](https://github.com/facebook/react/commit/d926936f0 )**: Eager bailout optimization should always compare to latest reducer (#15124) //// - **[4162f6026](https://github.com/facebook/react/commit/4162f6026 )**: Add feature flag to disable yielding (#15119) //// - **[8d60bd4dc](https://github.com/facebook/react/commit/8d60bd4dc )**: [Shallow] Implement setState for Hooks and remount on type change (#15120) //// - **[035e4cffb](https://github.com/facebook/react/commit/035e4cffb )**: Change passive checker to use defineProperty (#15121) //// - **[b283d75c1](https://github.com/facebook/react/commit/b283d75c1 )**: Support React.memo in ReactShallowRenderer (#14816) //// - **[f0621fe23](https://github.com/facebook/react/commit/f0621fe23 )**: Use same example code for async effect warning (#15118) //// - **[52c870c8d](https://github.com/facebook/react/commit/52c870c8d )**: Fix shallow renderer not allowing hooks in forwardRef render functions (#15100) //// - **[f1ff4348c](https://github.com/facebook/react/commit/f1ff4348c )**: Don't suggest a function as its own dep (#15115) //// - **[371bbf36b](https://github.com/facebook/react/commit/371bbf36b )**: Add infrastructure for passive/non-passive event support for future API exploration (#15036) //// - **[ab5fe174c](https://github.com/facebook/react/commit/ab5fe174c )**: Don't set the first option as selected in select tag with `size` attribute (#14242) //// - **[935f60083](https://github.com/facebook/react/commit/935f60083 )**: eslint-plugin-react-hooks@1.5.1 //// - **[0c03a4743](https://github.com/facebook/react/commit/0c03a4743 )**: Adds experimental event API scaffolding (#15108) //// - **[1204c7897](https://github.com/facebook/react/commit/1204c7897 )**: [eslint] Wording tweaks (#15078) //// - **[9d77a317b](https://github.com/facebook/react/commit/9d77a317b )**: Improve async useEffect warning (#15104) //// - **[103378b1e](https://github.com/facebook/react/commit/103378b1e )**: Warn for javascript: URLs in DOM sinks (#15047) //// - **[5d0c3c6c7](https://github.com/facebook/react/commit/5d0c3c6c7 )**: [Partial Hydration] Render client-only content at normal priority (#15061) //// - **[6a4a261ee](https://github.com/facebook/react/commit/6a4a261ee )**: Test suspended children are hidden before layout in persistent mode (#15030) //// - **[bc8bd24c1](https://github.com/facebook/react/commit/bc8bd24c1 )**: Run persistent mode tests in CI (#15029) //// - **[3f4852fa5](https://github.com/facebook/react/commit/3f4852fa5 )**: Run Placeholder tests in persistent mode, too (#15013) //// - **[d0289c7e3](https://github.com/facebook/react/commit/d0289c7e3 )**: eslint-plugin-react-hooks@1.5.0 //// - **[03ad9c73e](https://github.com/facebook/react/commit/03ad9c73e )**: [ESLint] Tweak setState updater message and add useEffect(async) warning (#15055) //// - **[eb6247a9a](https://github.com/facebook/react/commit/eb6247a9a )**: More concise messages (#15053) //// - **[197703ecc](https://github.com/facebook/react/commit/197703ecc )**: [ESLint] Add more hints to lint messages (#15046) //// - **[6d2666bab](https://github.com/facebook/react/commit/6d2666bab )**: Fix ESLint rule crash (#15044) //// - **[9b7e1d138](https://github.com/facebook/react/commit/9b7e1d138 )**: [ESLint] Suggest moving inside a Hook or useCallback when bare function is a dependency (#15026) //// - **[1e3b6192b](https://github.com/facebook/react/commit/1e3b6192b )**: Import Scheduler directly, not via host config (#14984) //// - **[5d49dafac](https://github.com/facebook/react/commit/5d49dafac )**: Enforce deps array in useMemo and useCallback (#15025) //// - **[a9aa24ed8](https://github.com/facebook/react/commit/a9aa24ed8 )**: 16.8.4 and changelog //// - **[fa5d4ee43](https://github.com/facebook/react/commit/fa5d4ee43 )**: [ESLint] Treat functions that don't capture anything as static (#14996) //// - **[fd557d453](https://github.com/facebook/react/commit/fd557d453 )**: Warn on mount when deps are not an array (#15018) //// - **[ce45ca9ba](https://github.com/facebook/react/commit/ce45ca9ba )**: Prettier //// - **[757a70b25](https://github.com/facebook/react/commit/757a70b25 )**: ReactNoop.yield -> Scheduler.yieldValue (#15008) //// - **[9d756d903](https://github.com/facebook/react/commit/9d756d903 )**: Revert #14756 changes to ReactFiberScheduler (#14992) //// - **[f16442a10](https://github.com/facebook/react/commit/f16442a10 )**: eslint-plugin-react-hooks@1.4.0 //// - **[e1e45fb36](https://github.com/facebook/react/commit/e1e45fb36 )**: [ESLint] Suggest to destructure props when they are only used as members (#14993) //// - **[59ef28437](https://github.com/facebook/react/commit/59ef28437 )**: Warn about dependencies outside of render scope (#14990) //// - **[df7b4768c](https://github.com/facebook/react/commit/df7b4768c )**: [ESLint] Deduplicate suggested dependencies (#14982) //// - **[02404d793](https://github.com/facebook/react/commit/02404d793 )**: Avoid dynamic dispatch for scheduler calls (#14968) //// - **[bb2939ccc](https://github.com/facebook/react/commit/bb2939ccc )**: Support editable useState hooks in DevTools (#14906) //// - **[69060e1da](https://github.com/facebook/react/commit/69060e1da )**: Swap expect(ReactNoop) for expect(Scheduler) (#14971) //// - **[ccb2a8a44](https://github.com/facebook/react/commit/ccb2a8a44 )**: Replace test renderer's fake Scheduler implementation with mock build (#14970) //// - **[53e787b45](https://github.com/facebook/react/commit/53e787b45 )**: Replace noop's fake Scheduler implementation with mock Scheduler build (#14969) //// - **[3ada82b74](https://github.com/facebook/react/commit/3ada82b74 )**: Allow extraneous effect dependencies (#14967) //// - **[00748c53e](https://github.com/facebook/react/commit/00748c53e )**: Add new mock build of Scheduler with flush, yield API (#14964) //// - **[4186952a6](https://github.com/facebook/react/commit/4186952a6 )**: Fixed incompatibility between react-debug-tools and useContext() (#14940) //// - **[0b8efb229](https://github.com/facebook/react/commit/0b8efb229 )**: Allow omitting constant primitive deps (#14959) //// - **[875d05d55](https://github.com/facebook/react/commit/875d05d55 )**: Include full error messages in React Native build (#15363) //// - **[c64b33003](https://github.com/facebook/react/commit/c64b33003 )**: Move EventTypes to ReactTypes (#15364) //// - **[4c78ac0b9](https://github.com/facebook/react/commit/4c78ac0b9 )**: Track Event Time as the Start Time for Suspense (#15358) //// Changelog: [General][Changed] - React sync for revisions 8e25ed2...c64b330 Reviewed By: hramos Differential Revision: D14862650 fbshipit-source-id: 350447246d26c69e7f462c5eb4e3ec02e99d05bb --- Libraries/Renderer/REVISION | 2 +- Libraries/Renderer/oss/ReactFabric-dev.js | 6417 ++++++++++++----- Libraries/Renderer/oss/ReactFabric-prod.js | 2675 ++++--- .../Renderer/oss/ReactFabric-profiling.js | 2156 +++--- .../Renderer/oss/ReactNativeRenderer-dev.js | 6300 ++++++++++++---- .../Renderer/oss/ReactNativeRenderer-prod.js | 2621 ++++--- .../oss/ReactNativeRenderer-profiling.js | 2247 +++--- Libraries/Renderer/shims/ReactNativeTypes.js | 4 +- Libraries/Renderer/shims/ReactTypes.js | 94 +- package.json | 10 +- yarn.lock | 48 +- 11 files changed, 14435 insertions(+), 8139 deletions(-) diff --git a/Libraries/Renderer/REVISION b/Libraries/Renderer/REVISION index b51f74404e8..878748d2ea9 100644 --- a/Libraries/Renderer/REVISION +++ b/Libraries/Renderer/REVISION @@ -1 +1 @@ -8e25ed20bd27d126f670d04680db85209f779056 \ No newline at end of file +c64b330032cef887ac5f787ac4a50bb4eeca4e1d \ No newline at end of file diff --git a/Libraries/Renderer/oss/ReactFabric-dev.js b/Libraries/Renderer/oss/ReactFabric-dev.js index 3dbff8b0852..2e3871931b5 100644 --- a/Libraries/Renderer/oss/ReactFabric-dev.js +++ b/Libraries/Renderer/oss/ReactFabric-dev.js @@ -26,10 +26,20 @@ var deepFreezeAndThrowOnMutationInDev = require("deepFreezeAndThrowOnMutationInD var TextInputState = require("TextInputState"); var FabricUIManager = require("FabricUIManager"); var checkPropTypes = require("prop-types/checkPropTypes"); +var Scheduler = require("scheduler"); var tracing = require("scheduler/tracing"); -var scheduler = require("scheduler"); var ExceptionsManager = require("ExceptionsManager"); +// Do not require this module directly! Use a normal error constructor with +// template literal strings. The messages will be converted to ReactError during +// build, and in production they will be minified. + +function ReactError(message) { + var error = new Error(message); + error.name = "Invariant Violation"; + return error; +} + /** * Use invariant() to assert state which your program assumes to be true. * @@ -41,39 +51,237 @@ var ExceptionsManager = require("ExceptionsManager"); * will remain to ensure logic does not differ in production. */ -var validateFormat = function() {}; +/** + * Injectable ordering of event plugins. + */ +var eventPluginOrder = null; -{ - validateFormat = function(format) { - if (format === undefined) { - throw new Error("invariant requires an error message argument"); +/** + * Injectable mapping from names to event plugin modules. + */ +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( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + })(); + if (plugins[pluginIndex]) { + continue; } - }; + (function() { + if (!pluginModule.extractEvents) { + throw ReactError( + "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( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + })(); + } + } } -function invariant(condition, format, a, b, c, d, e, f) { - validateFormat(format); - - if (!condition) { - var error = void 0; - if (format === undefined) { - error = new Error( - "Minified exception occurred; use the non-minified dev environment " + - "for the full error message and additional helpful warnings." +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + (function() { + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - error.name = "Invariant Violation"; } + })(); + eventNameDispatchConfigs[eventName] = dispatchConfig; - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName( + phasedRegistrationName, + pluginModule, + eventName + ); + } + } + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName( + dispatchConfig.registrationName, + pluginModule, + eventName + ); + return true; + } + return false; +} + +/** + * Publishes a registration name that is used to identify dispatched events. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ +function publishRegistrationName(registrationName, pluginModule, eventName) { + (function() { + if (!!registrationNameModules[registrationName]) { + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + })(); + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = + pluginModule.eventTypes[eventName].dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + } +} + +/** + * Registers plugins so that they can extract and dispatch events. + * + * @see {EventPluginHub} + */ + +/** + * Ordered list of injected plugins. + */ +var plugins = []; + +/** + * Mapping from event name to dispatch config + */ +var eventNameDispatchConfigs = {}; + +/** + * Mapping from registration name to plugin module + */ +var registrationNameModules = {}; + +/** + * Mapping from registration name to event name + */ +var registrationNameDependencies = {}; + +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ + +// Trust the developer to only use possibleRegistrationNames in true + +/** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ +function injectEventPluginOrder(injectedEventPluginOrder) { + (function() { + if (!!eventPluginOrder) { + throw ReactError( + "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`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @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( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + })(); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); } } @@ -141,16 +349,13 @@ 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. - invariant( - typeof document !== "undefined", - "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." - ); + (function() { + if (!(typeof document !== "undefined")) { + throw ReactError( + "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"); // Keeps track of whether the user-provided callback threw an error. We @@ -373,221 +578,13 @@ function clearCaughtError() { caughtError = null; return error; } else { - invariant( - false, - "clearCaughtError was called but no error was captured. This error " + - "is likely caused by a bug in React. Please file an issue." - ); - } -} - -/** - * Injectable ordering of event plugins. - */ -var eventPluginOrder = null; - -/** - * Injectable mapping from names to event plugin modules. - */ -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); - invariant( - pluginIndex > -1, - "EventPluginRegistry: Cannot inject event plugins that do not exist in " + - "the plugin ordering, `%s`.", - pluginName - ); - if (plugins[pluginIndex]) { - continue; - } - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` " + - "method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - var publishedEvents = pluginModule.eventTypes; - for (var eventName in publishedEvents) { - invariant( - publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ), - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } -} - -/** - * Publishes an event so that it can be dispatched by the supplied plugin. - * - * @param {object} dispatchConfig Dispatch configuration for the event. - * @param {object} PluginModule Plugin publishing the event. - * @return {boolean} True if the event was successfully published. - * @private - */ -function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName), - "EventPluginHub: More than one plugin attempted to publish the same " + - "event name, `%s`.", - eventName - ); - eventNameDispatchConfigs[eventName] = dispatchConfig; - - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (var phaseName in phasedRegistrationNames) { - if (phasedRegistrationNames.hasOwnProperty(phaseName)) { - var phasedRegistrationName = phasedRegistrationNames[phaseName]; - publishRegistrationName( - phasedRegistrationName, - pluginModule, - eventName + (function() { + { + throw ReactError( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); } - } - return true; - } else if (dispatchConfig.registrationName) { - publishRegistrationName( - dispatchConfig.registrationName, - pluginModule, - eventName - ); - return true; - } - return false; -} - -/** - * Publishes a registration name that is used to identify dispatched events. - * - * @param {string} registrationName Registration name to add. - * @param {object} PluginModule Plugin publishing the event. - * @private - */ -function publishRegistrationName(registrationName, pluginModule, eventName) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same " + - "registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; - registrationNameDependencies[registrationName] = - pluginModule.eventTypes[eventName].dependencies; - - { - var lowerCasedName = registrationName.toLowerCase(); - } -} - -/** - * Registers plugins so that they can extract and dispatch events. - * - * @see {EventPluginHub} - */ - -/** - * Ordered list of injected plugins. - */ -var plugins = []; - -/** - * Mapping from event name to dispatch config - */ -var eventNameDispatchConfigs = {}; - -/** - * Mapping from registration name to plugin module - */ -var registrationNameModules = {}; - -/** - * Mapping from registration name to event name - */ -var registrationNameDependencies = {}; - -/** - * Mapping from lowercase registration names to the properly cased version, - * used to warn in the case of missing event handlers. Available - * only in true. - * @type {Object} - */ - -// Trust the developer to only use possibleRegistrationNames in true - -/** - * Injects an ordering of plugins (by plugin name). This allows the ordering - * to be decoupled from injection of the actual plugins so that ordering is - * always deterministic regardless of packaging, on-the-fly injection, etc. - * - * @param {array} InjectedEventPluginOrder - * @internal - * @see {EventPluginHub.injection.injectEventPluginOrder} - */ -function injectEventPluginOrder(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "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`. - * - * Plugins can be injected as part of page initialization or on-the-fly. - * - * @param {object} injectedNamesToPlugins Map from names to plugin modules. - * @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 - ) { - invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins " + - "using the same name, `%s`.", - pluginName - ); - namesToPlugins[pluginName] = pluginModule; - isOrderingDirty = true; - } - } - if (isOrderingDirty) { - recomputePluginOrdering(); + })(); } } @@ -796,10 +793,11 @@ function executeDirectDispatch(event) { } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + (function() { + if (!!Array.isArray(dispatchListener)) { + throw ReactError("executeDirectDispatch(...): Invalid `event`."); + } + })(); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -832,10 +830,13 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - invariant( - next != null, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + (function() { + if (!(next != null)) { + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } + })(); if (current == null) { return next; @@ -902,6 +903,32 @@ var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(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 + // events get enqueued while processing. + var processingEventQueue = eventQueue; + eventQueue = null; + + if (!processingEventQueue) { + return; + } + + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + (function() { + if (!!eventQueue) { + throw ReactError( + "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(); +} + function isInteractive(tag) { return ( tag === "button" || @@ -992,12 +1019,17 @@ function getListener(inst, registrationName) { if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - invariant( - !listener || typeof listener === "function", - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + (function() { + if (!(!listener || typeof listener === "function")) { + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + })(); return listener; } @@ -1008,7 +1040,7 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ -function extractEvents( +function extractPluginEvents( topLevelType, targetInst, nativeEvent, @@ -1033,37 +1065,13 @@ function extractEvents( return events; } -function runEventsInBatch(events) { - if (events !== null) { - eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more - // events get enqueued while processing. - var processingEventQueue = eventQueue; - eventQueue = null; - - if (!processingEventQueue) { - return; - } - - forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - invariant( - !eventQueue, - "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(); -} - -function runExtractedEventsInBatch( +function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, nativeEventTarget ) { - var events = extractEvents( + var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, @@ -1091,6 +1099,8 @@ var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedSuspenseComponent = 18; +var EventComponent = 19; +var EventTarget = 20; function getParent(inst) { do { @@ -1609,10 +1619,13 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - invariant( - event instanceof EventConstructor, - "Trying to release an event instance into a pool of a different type." - ); + (function() { + if (!(event instanceof EventConstructor)) { + throw ReactError( + "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); @@ -1719,7 +1732,11 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - invariant(identifier != null, "Touch object is missing identifier."); + (function() { + if (!(identifier != null)) { + throw ReactError("Touch object is missing identifier."); + } + })(); { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1847,10 +1864,13 @@ var ResponderTouchHistoryStore = { * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { - invariant( - next != null, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + (function() { + if (!(next != null)) { + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); + } + })(); if (current == null) { return next; @@ -2462,11 +2482,13 @@ var ReactNativeBridgeEventPlugin = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType]; var directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + (function() { + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + })(); var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -2516,7 +2538,11 @@ function getInstanceFromInstance(instanceHandle) { function getTagFromInstance(inst) { var tag = inst.stateNode.canonical._nativeTag; - invariant(tag, "All native instances should have a tag."); + (function() { + if (!tag) { + throw ReactError("All native instances should have a tag."); + } + })(); return tag; } @@ -2605,6 +2631,17 @@ var REACT_FORWARD_REF_TYPE = hasSymbol var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 0xead4; +var REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 0xead5; +var REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 0xead6; + +// React event targets +var REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; @@ -2688,6 +2725,25 @@ function getComponentName(type) { if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; + } + case REACT_EVENT_COMPONENT_TYPE: { + var eventComponent = type; + var displayName = eventComponent.displayName; + if (displayName !== undefined) { + return displayName; + } + break; + } + case REACT_EVENT_TARGET_TYPE: { + var eventTarget = type; + if (eventTarget.type === REACT_EVENT_TARGET_TOUCH_HIT) { + return "TouchHitTarget"; + } + var _displayName = eventTarget.displayName; + if (_displayName !== undefined) { + return _displayName; + } } } } @@ -2787,10 +2843,11 @@ function isMounted(component) { } function assertIsMounted(fiber) { - invariant( - isFiberMountedImpl(fiber) === MOUNTED, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(isFiberMountedImpl(fiber) === MOUNTED)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } function findCurrentFiberUsingSlowPath(fiber) { @@ -2798,10 +2855,11 @@ function findCurrentFiberUsingSlowPath(fiber) { if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. var state = isFiberMountedImpl(fiber); - invariant( - state !== UNMOUNTED, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(state !== UNMOUNTED)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); if (state === MOUNTING) { return null; } @@ -2814,11 +2872,24 @@ function findCurrentFiberUsingSlowPath(fiber) { var b = alternate; while (true) { var parentA = a.return; - var parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) { + 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 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 @@ -2840,7 +2911,11 @@ function findCurrentFiberUsingSlowPath(fiber) { } // 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. - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } if (a.return !== b.return) { @@ -2891,26 +2966,31 @@ function findCurrentFiberUsingSlowPath(fiber) { } _child = _child.sibling; } - invariant( - didFindChild, - "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 (!didFindChild) { + throw ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); + } + })(); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(a.alternate === b)) { + throw ReactError( + "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. - invariant( - a.tag === HostRoot, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(a.tag === HostRoot)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; @@ -3457,66 +3537,6 @@ function diff(prevProps, nextProps, validAttributes) { ); } -var hasNativePerformanceNow = - typeof performance === "object" && typeof performance.now === "function"; - -var now$1 = hasNativePerformanceNow - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }; - -var scheduledCallback = null; -var frameDeadline = 0; - -function setTimeoutCallback() { - // TODO (bvaughn) Hard-coded 5ms unblocks initial async testing. - // React API probably changing to boolean rather than time remaining. - // Longer-term plan is to rewrite this using shared memory, - // And just return the value of the bit as the boolean. - frameDeadline = now$1() + 5; - - var callback = scheduledCallback; - scheduledCallback = null; - if (callback !== null) { - callback(); - } -} - -// RN has a poor polyfill for requestIdleCallback so we aren't using it. -// This implementation is only intended for short-term use anyway. -// We also don't implement cancel functionality b'c Fiber doesn't currently need it. -function scheduleDeferredCallback$1(callback, options) { - // We assume only one callback is scheduled at a time b'c that's how Fiber works. - scheduledCallback = callback; - var timeoutId = setTimeout(setTimeoutCallback, 1); - return timeoutId; // Timeouts are always numbers on RN -} - -function cancelDeferredCallback$1(callbackID) { - scheduledCallback = null; - clearTimeout(callbackID); // Timeouts are always numbers on RN -} - -function shouldYield$1() { - return frameDeadline <= now$1(); -} - -var debugRenderPhaseSideEffects = false; -var debugRenderPhaseSideEffectsForStrictMode = false; -var enableUserTimingAPI = true; -var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; -var warnAboutDeprecatedLifecycles = false; -var enableProfilerTimer = true; -var enableSchedulerTracing = true; -var enableSuspenseServerRenderer = false; - -var warnAboutDeprecatedSetNativeProps = false; - -// Only used in www builds. - // Use to restore controlled state after a change event has fired. var restoreImpl = null; @@ -3531,11 +3551,13 @@ function restoreStateOfTarget(target) { // Unmounted return; } - invariant( - typeof restoreImpl === "function", - "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() { + if (!(typeof restoreImpl === "function")) { + throw ReactError( + "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); } @@ -3612,7 +3634,7 @@ function setBatchingImplementation( function dispatchEvent(target, topLevelType, nativeEvent) { var targetFiber = target; batchedUpdates(function() { - runExtractedEventsInBatch( + runExtractedPluginEventsInBatch( topLevelType, targetFiber, nativeEvent, @@ -3627,12 +3649,13 @@ function dispatchEvent(target, topLevelType, nativeEvent) { // can re-export everything from this module. function shim() { - invariant( - false, - "The current renderer does not support mutation. " + - "This error is likely caused by a bug in React. " + - "Please file an issue." - ); + (function() { + { + throw ReactError( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } // Mutation (when unsupported) @@ -3656,12 +3679,13 @@ var unhideTextInstance = shim; // can re-export everything from this module. function shim$1() { - invariant( - false, - "The current renderer does not support hydration. " + - "This error is likely caused by a bug in React. " + - "Please file an issue." - ); + (function() { + { + throw ReactError( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } // Hydration (when unsupported) @@ -3717,12 +3741,18 @@ if (FabricUIManager.registerEventHandler) { */ var ReactFabricHostComponent = (function() { - function ReactFabricHostComponent(tag, viewConfig, props) { + function ReactFabricHostComponent( + tag, + viewConfig, + props, + internalInstanceHandle + ) { _classCallCheck(this, ReactFabricHostComponent); this._nativeTag = tag; this.viewConfig = viewConfig; this.currentProps = props; + this._internalInstanceHandle = internalInstanceHandle; } ReactFabricHostComponent.prototype.blur = function blur() { @@ -3733,30 +3763,42 @@ var ReactFabricHostComponent = (function() { TextInputState.focusTextInput(this._nativeTag); }; - ReactFabricHostComponent.prototype.measure = function measure(callback) { - UIManager.measure( - this._nativeTag, + ReactFabricHostComponent.prototype.measure = function measure$$1(callback) { + FabricUIManager.measure( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureInWindow = function measureInWindow( + ReactFabricHostComponent.prototype.measureInWindow = function measureInWindow$$1( callback ) { - UIManager.measureInWindow( - this._nativeTag, + FabricUIManager.measureInWindow( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactFabricHostComponent.prototype.measureLayout = function measureLayout( + ReactFabricHostComponent.prototype.measureLayout = function measureLayout$$1( relativeToNativeNode, onSuccess, onFail /* currently unused */ ) { - UIManager.measureLayout( - this._nativeTag, - relativeToNativeNode, + if ( + typeof relativeToNativeNode === "number" || + !(relativeToNativeNode instanceof ReactFabricHostComponent) + ) { + warningWithoutStack$1( + false, + "Warning: ref.measureLayout must be called with a ref to a native component." + ); + + return; + } + + FabricUIManager.measureLayout( + this._internalInstanceHandle.stateNode.node, + relativeToNativeNode._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); @@ -3765,31 +3807,12 @@ var ReactFabricHostComponent = (function() { ReactFabricHostComponent.prototype.setNativeProps = function setNativeProps( nativeProps ) { - { - if (warnAboutDeprecatedSetNativeProps) { - warningWithoutStack$1( - false, - "Warning: Calling ref.setNativeProps(nativeProps) " + - "is deprecated and will be removed in a future release. " + - "Use the setNativeProps export from the react-native package instead." + - "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" - ); - } - warnForStyleProps(nativeProps, this.viewConfig.validAttributes); - } + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); - 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) { - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - updatePayload - ); - } + return; }; return ReactFabricHostComponent; @@ -3819,10 +3842,13 @@ function createInstance( } } - invariant( - type !== "RCTView" || !hostContext.isInAParentText, - "Nesting of within is not currently supported." - ); + (function() { + if (!(type !== "RCTView" || !hostContext.isInAParentText)) { + throw ReactError( + "Nesting of within is not currently supported." + ); + } + })(); var updatePayload = create(props, viewConfig.validAttributes); @@ -3834,7 +3860,12 @@ function createInstance( internalInstanceHandle // internalInstanceHandle ); - var component = new ReactFabricHostComponent(tag, viewConfig, props); + var component = new ReactFabricHostComponent( + tag, + viewConfig, + props, + internalInstanceHandle + ); return { node: node, @@ -3848,10 +3879,13 @@ function createTextInstance( hostContext, internalInstanceHandle ) { - invariant( - hostContext.isInAParentText, - "Text strings must be rendered within a component." - ); + (function() { + if (!hostContext.isInAParentText) { + throw ReactError( + "Text strings must be rendered within a component." + ); + } + })(); var tag = nextReactTag; nextReactTag += 2; @@ -3899,6 +3933,16 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { } } +function getChildHostContextForEventComponent(parentHostContext) { + // TODO: add getChildHostContextForEventComponent implementation + return parentHostContext; +} + +function getChildHostContextForEventTarget(parentHostContext, type) { + // TODO: add getChildHostContextForEventTarget implementation + return parentHostContext; +} + function getPublicInstance(instance) { return instance.canonical; } @@ -3944,16 +3988,10 @@ function shouldSetTextContent(type, props) { // The Fabric renderer is secondary to the existing React Native renderer. var isPrimaryRenderer = false; -var now$$1 = now$1; -var scheduleDeferredCallback$$1 = scheduleDeferredCallback$1; -var cancelDeferredCallback$$1 = cancelDeferredCallback$1; -var shouldYield$$1 = shouldYield$1; var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; var noTimeout = -1; -var schedulePassiveEffects = scheduleDeferredCallback$$1; -var cancelPassiveEffects = cancelDeferredCallback$$1; // ------------------- // Persistence @@ -4008,26 +4046,7 @@ function cloneHiddenInstance(instance, type, props, internalInstanceHandle) { }; } -function cloneUnhiddenInstance(instance, type, props, internalInstanceHandle) { - var viewConfig = instance.canonical.viewConfig; - var node = instance.node; - var updatePayload = diff( - Object.assign({}, props, { style: [props.style, { display: "none" }] }), - props, - viewConfig.validAttributes - ); - return { - node: FabricUIManager.cloneNodeWithNewProps(node, updatePayload), - canonical: instance.canonical - }; -} - -function createHiddenTextInstance( - text, - rootContainerInstance, - hostContext, - internalInstanceHandle -) { +function cloneHiddenTextInstance(instance, text, internalInstanceHandle) { throw new Error("Not yet implemented."); } @@ -4043,6 +4062,35 @@ function finalizeContainerChildren(container, newChildren) { FabricUIManager.completeRoot(container, newChildren); } +function mountEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function updateEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function unmountEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function getEventTargetChildElement(type, props) { + throw new Error("Not yet implemented."); +} + +function handleEventTarget( + type, + props, + rootContainerInstance, + internalInstanceHandle +) { + throw new Error("Not yet implemented."); +} + +function commitEventTarget(type, props, instance, parentInstance) { + throw new Error("Not yet implemented."); +} + var BEFORE_SLASH_RE = /^(.*)[\\\/]/; var describeComponentFrame = function(name, source, ownerName) { @@ -4154,6 +4202,23 @@ function setCurrentPhase(lifeCyclePhase) { } } +var debugRenderPhaseSideEffects = false; +var debugRenderPhaseSideEffectsForStrictMode = false; +var enableUserTimingAPI = true; +var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; +var warnAboutDeprecatedLifecycles = true; +var enableProfilerTimer = true; +var enableSchedulerTracing = true; +var enableSuspenseServerRenderer = false; + +var disableYielding = false; + +var warnAboutDeprecatedSetNativeProps = false; +var enableEventAPI = false; +var enableNewScheduler = false; + +// Only used in www builds. + // Prefix measurements so that it's possible to filter them. // Longer prefixes are hard to read in DevTools. var reactEmoji = "\u269B"; @@ -4789,11 +4854,13 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(contextStackCursor.current === emptyContextObject)) { + throw ReactError( + "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); @@ -4835,12 +4902,16 @@ function processChildContext(fiber, type, parentContext) { setCurrentPhase(null); } for (var contextKey in childContext) { - invariant( - contextKey in childContextTypes, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + (function() { + if (!(contextKey in childContextTypes)) { + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } + })(); } { var name = getComponentName(type) || "Unknown"; @@ -4885,11 +4956,13 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "Expected to have an instance by this point. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!instance) { + throw ReactError( + "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. @@ -4918,11 +4991,13 @@ function invalidateContextProvider(workInProgress, type, didChange) { function findCurrentUnmaskedContext(fiber) { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - invariant( - isFiberMounted(fiber) && fiber.tag === ClassComponent, - "Expected subtree parent to be a mounted class component. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + throw ReactError( + "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 { @@ -4939,11 +5014,13 @@ function findCurrentUnmaskedContext(fiber) { } node = node.return; } while (node !== null); - invariant( - false, - "Found unexpected detached subtree parent. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var onCommitFiberRoot = null; @@ -5031,14 +5108,166 @@ function onCommitUnmount(fiber) { // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 -var maxSigned31BitInt = 1073741823; +var MAX_SIGNED_31_BIT_INT = 1073741823; + +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority; +var Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback; +var Scheduler_cancelCallback = Scheduler.unstable_cancelCallback; +var Scheduler_shouldYield = Scheduler.unstable_shouldYield; +var Scheduler_now = Scheduler.unstable_now; +var Scheduler_getCurrentPriorityLevel = + Scheduler.unstable_getCurrentPriorityLevel; +var Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority; +var Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; +var Scheduler_NormalPriority = Scheduler.unstable_NormalPriority; +var Scheduler_LowPriority = Scheduler.unstable_LowPriority; +var Scheduler_IdlePriority = Scheduler.unstable_IdlePriority; + +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 now = Scheduler_now; +var shouldYield = disableYielding + ? function() { + return false; + } // Never yield when `disableYielding` is on + : Scheduler_shouldYield; + +var immediateQueue = null; +var immediateQueueCallbackNode = null; +var isFlushingImmediate = false; + +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("Unknown priority level."); + } + })(); + } +} + +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("Unknown priority level."); + } + })(); + } +} + +function runWithPriority(reactPriorityLevel, fn) { + var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); + return Scheduler_runWithPriority(priorityLevel, fn); +} + +function scheduleCallback(reactPriorityLevel, callback, options) { + if (reactPriorityLevel === ImmediatePriority) { + // Push this callback into an internal queue. We'll flush these either in + // the next tick, or earlier if something calls `flushImmediateQueue`. + if (immediateQueue === null) { + immediateQueue = [callback]; + // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( + Scheduler_ImmediatePriority, + flushImmediateQueueImpl + ); + } else { + // Push onto existing queue. Don't need to schedule a callback because + // we already scheduled one when we created the queue. + immediateQueue.push(callback); + } + return fakeCallbackNode; + } + // Otherwise pass through to Scheduler. + var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); + return Scheduler_scheduleCallback(priorityLevel, callback, options); +} + +function cancelCallback(callbackNode) { + if (callbackNode !== fakeCallbackNode) { + Scheduler_cancelCallback(callbackNode); + } +} + +function flushImmediateQueue() { + if (immediateQueueCallbackNode !== null) { + Scheduler_cancelCallback(immediateQueueCallbackNode); + } + flushImmediateQueueImpl(); +} + +function flushImmediateQueueImpl() { + if (!isFlushingImmediate && immediateQueue !== null) { + // Prevent re-entrancy. + isFlushingImmediate = true; + var i = 0; + try { + var _isSync = true; + for (; i < immediateQueue.length; i++) { + var callback = immediateQueue[i]; + do { + callback = callback(_isSync); + } while (callback !== null); + } + immediateQueue = null; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + if (immediateQueue !== null) { + immediateQueue = immediateQueue.slice(i + 1); + } + // Resume flushing in the next tick + Scheduler_scheduleCallback( + Scheduler_ImmediatePriority, + flushImmediateQueue + ); + throw error; + } finally { + isFlushingImmediate = false; + } + } +} var NoWork = 0; var Never = 1; -var Sync = maxSigned31BitInt; +var Sync = MAX_SIGNED_31_BIT_INT; var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1; +var MAGIC_NUMBER_OFFSET = MAX_SIGNED_31_BIT_INT - 1; // 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { @@ -5064,6 +5293,8 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { ); } +// 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; @@ -5075,6 +5306,12 @@ function computeAsyncExpiration(currentTime) { ); } +// Same as computeAsyncExpiration but without the bucketing logic. This is +// used to compute timestamps instead of actual expiration times. +function computeAsyncExpirationNoBucket(currentTime) { + return currentTime - LOW_PRIORITY_EXPIRATION / UNIT_SIZE; +} + // We intentionally set a higher expiration time for interactive updates in // dev than in production. // @@ -5097,6 +5334,31 @@ function computeInteractiveExpiration(currentTime) { ); } +function inferPriorityFromExpirationTime(currentTime, expirationTime) { + if (expirationTime === Sync) { + return ImmediatePriority; + } + if (expirationTime === Never) { + return IdlePriority; + } + var msUntil = + msToExpirationTime(expirationTime) - msToExpirationTime(currentTime); + if (msUntil <= 0) { + return ImmediatePriority; + } + if (msUntil <= HIGH_PRIORITY_EXPIRATION) { + return UserBlockingPriority; + } + if (msUntil <= LOW_PRIORITY_EXPIRATION) { + return NormalPriority; + } + + // TODO: Handle LowPriority + + // Assume anything lower has idle priority + return IdlePriority; +} + var NoContext = 0; var ConcurrentMode = 1; var StrictMode = 2; @@ -5198,6 +5460,7 @@ function FiberNode(tag, pendingProps, key, mode) { this._debugSource = null; this._debugOwner = null; this._debugIsCurrentlyTiming = false; + this._debugHookTypes = null; if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } @@ -5274,6 +5537,7 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress._debugID = current._debugID; workInProgress._debugSource = current._debugSource; workInProgress._debugOwner = current._debugOwner; + workInProgress._debugHookTypes = current._debugHookTypes; } workInProgress.alternate = current; @@ -5401,6 +5665,28 @@ function createFiberFromTypeAndProps( fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_EVENT_COMPONENT_TYPE: + if (enableEventAPI) { + return createFiberFromEventComponent( + type, + pendingProps, + mode, + expirationTime, + key + ); + } + break; + case REACT_EVENT_TARGET_TYPE: + if (enableEventAPI) { + return createFiberFromEventTarget( + type, + pendingProps, + mode, + expirationTime, + key + ); + } + break; } } var info = ""; @@ -5421,14 +5707,16 @@ function createFiberFromTypeAndProps( info += "\n\nCheck the render method of `" + ownerName + "`."; } } - invariant( - false, - "Element type is invalid: expected a string (for built-in " + - "components) or a class/function (for composite components) " + - "but got: %s.%s", - type == null ? type : typeof type, - info - ); + (function() { + { + throw ReactError( + "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 + ); + } + })(); } } } @@ -5470,6 +5758,34 @@ function createFiberFromFragment(elements, mode, expirationTime, key) { return fiber; } +function createFiberFromEventComponent( + eventComponent, + pendingProps, + mode, + expirationTime, + key +) { + var fiber = createFiber(EventComponent, pendingProps, key, mode); + fiber.elementType = eventComponent; + fiber.type = eventComponent; + fiber.expirationTime = expirationTime; + return fiber; +} + +function createFiberFromEventTarget( + eventTarget, + pendingProps, + mode, + expirationTime, + key +) { + var fiber = createFiber(EventTarget, pendingProps, key, mode); + fiber.elementType = eventTarget; + fiber.type = eventTarget; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -5592,6 +5908,7 @@ function assignFiberPropertiesInDEV(target, source) { target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming; + target._debugHookTypes = source._debugHookTypes; return target; } @@ -5608,78 +5925,53 @@ function assignFiberPropertiesInDEV(target, source) { // 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, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.pingCache = null; + this.pendingCommitExpirationTime = NoWork; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.hydrate = hydrate; + this.firstBatch = null; + + if (enableNewScheduler) { + this.callbackNode = null; + this.callbackExpirationTime = NoWork; + this.firstPendingTime = NoWork; + this.lastPendingTime = NoWork; + this.pingTime = NoWork; + } else { + this.earliestPendingTime = NoWork; + this.latestPendingTime = NoWork; + this.earliestSuspendedTime = NoWork; + this.latestSuspendedTime = NoWork; + this.latestPingedTime = NoWork; + this.didError = false; + this.nextExpirationTimeToWorkOn = NoWork; + this.expirationTime = NoWork; + this.nextScheduledRoot = null; + } + + if (enableSchedulerTracing) { + this.interactionThreadID = tracing.unstable_getThreadID(); + this.memoizedInteractions = new Set(); + this.pendingInteractionMap = new Map(); + } +} + function createFiberRoot(containerInfo, isConcurrent, hydrate) { + var root = new FiberRootNode(containerInfo, hydrate); + // Cyclic construction. This cheats the type system right now because // stateNode is any. var uninitializedFiber = createHostRootFiber(isConcurrent); - - var root = void 0; - if (enableSchedulerTracing) { - root = { - current: uninitializedFiber, - containerInfo: containerInfo, - pendingChildren: null, - - earliestPendingTime: NoWork, - latestPendingTime: NoWork, - earliestSuspendedTime: NoWork, - latestSuspendedTime: NoWork, - latestPingedTime: NoWork, - - pingCache: null, - - didError: false, - - pendingCommitExpirationTime: NoWork, - finishedWork: null, - timeoutHandle: noTimeout, - context: null, - pendingContext: null, - hydrate: hydrate, - nextExpirationTimeToWorkOn: NoWork, - expirationTime: NoWork, - firstBatch: null, - nextScheduledRoot: null, - - interactionThreadID: tracing.unstable_getThreadID(), - memoizedInteractions: new Set(), - pendingInteractionMap: new Map() - }; - } else { - root = { - current: uninitializedFiber, - containerInfo: containerInfo, - pendingChildren: null, - - pingCache: null, - - earliestPendingTime: NoWork, - latestPendingTime: NoWork, - earliestSuspendedTime: NoWork, - latestSuspendedTime: NoWork, - latestPingedTime: NoWork, - - didError: false, - - pendingCommitExpirationTime: NoWork, - finishedWork: null, - timeoutHandle: noTimeout, - context: null, - pendingContext: null, - hydrate: hydrate, - nextExpirationTimeToWorkOn: NoWork, - expirationTime: NoWork, - firstBatch: null, - nextScheduledRoot: null - }; - } - + root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - // The reason for the way the Flow types are structured in this file, - // Is to avoid needing :any casts everywhere interaction tracing fields are used. - // Unfortunately that requires an :any cast for non-interaction tracing capable builds. - // $FlowFixMe Remove this :any cast and replace it with something better. return root; } @@ -6082,6 +6374,43 @@ var ReactStrictModeWarnings = { }; } +/** + * 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; + // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. // This is not part of the public API, not even for React DevTools. @@ -6281,20 +6610,6 @@ function clearPing(root, completedTime) { } } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestExpirationTime = renderExpirationTime; - - var earliestPendingTime = root.earliestPendingTime; - var earliestSuspendedTime = root.earliestSuspendedTime; - if (earliestPendingTime > earliestExpirationTime) { - earliestExpirationTime = earliestPendingTime; - } - if (earliestSuspendedTime > earliestExpirationTime) { - earliestExpirationTime = earliestSuspendedTime; - } - return earliestExpirationTime; -} - function didExpireAtExpirationTime(root, currentTime) { var expirationTime = root.expirationTime; if (expirationTime !== NoWork && currentTime <= expirationTime) { @@ -6337,43 +6652,6 @@ function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { root.expirationTime = expirationTime; } -/** - * 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; - /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is @@ -6569,15 +6847,13 @@ var didWarnAboutInvalidateContextType = void 0; Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - invariant( - false, - "_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)." - ); + (function() { + { + throw ReactError( + "_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); @@ -6626,8 +6902,8 @@ var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.payload = payload; @@ -6638,14 +6914,14 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); }, enqueueReplaceState: function(inst, payload, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ReplaceState; @@ -6658,14 +6934,14 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); }, enqueueForceUpdate: function(inst, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ForceUpdate; @@ -6677,9 +6953,9 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); } }; @@ -6991,23 +7267,51 @@ function constructClassInstance( var unmaskedContext = emptyContextObject; var context = null; var contextType = ctor.contextType; - if (typeof contextType === "object" && contextType !== null) { - { - if ( - contextType.$$typeof !== REACT_CONTEXT_TYPE && - !didWarnAboutInvalidateContextType.has(ctor) - ) { + + { + if ("contextType" in ctor) { + var isValid = + // Allow null for conditional declaration + contextType === null || + (contextType !== undefined && + contextType.$$typeof === REACT_CONTEXT_TYPE && + contextType._context === undefined); // Not a + + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); + + var addendum = ""; + if (contextType === undefined) { + addendum = + " However, it is set to undefined. " + + "This can be caused by a typo or by mixing up named and default imports. " + + "This can also happen due to a circular dependency, so " + + "try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = " Did you accidentally pass the Context.Provider instead?"; + } else if (contextType._context !== undefined) { + // + addendum = " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = + " However, it is set to an object with keys {" + + Object.keys(contextType).join(", ") + + "}."; + } warningWithoutStack$1( false, "%s defines an invalid contextType. " + - "contextType should point to the Context object returned by React.createContext(). " + - "Did you accidentally pass the Context.Provider instead?", - getComponentName(ctor) || "Component" + "contextType should point to the Context object returned by React.createContext().%s", + getComponentName(ctor) || "Component", + addendum ); } } + } + if (typeof contextType === "object" && contextType !== null) { context = readContext(contextType); } else { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); @@ -7649,11 +7953,13 @@ var warnForMissingKey = function(child) {}; if (!child._store || child._store.validated || child.key != null) { return; } - invariant( - typeof child._store === "object", - "React Component in warnForMissingKey should have a _store. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(typeof child._store === "object")) { + throw ReactError( + "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 = @@ -7709,19 +8015,24 @@ function coerceRef(returnFiber, current$$1, element) { var inst = void 0; if (owner) { var ownerFiber = owner; - invariant( - ownerFiber.tag === ClassComponent, - "Function components cannot have refs. " + - "Did you mean to use React.forwardRef()?" - ); + (function() { + if (!(ownerFiber.tag === ClassComponent)) { + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + } + })(); inst = ownerFiber.stateNode; } - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a " + - "bug in React. Please file an issue.", - mixedRef - ); + (function() { + if (!inst) { + throw ReactError( + "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 ( @@ -7747,20 +8058,22 @@ function coerceRef(returnFiber, current$$1, element) { ref._stringRef = stringRef; return ref; } else { - invariant( - typeof mixedRef === "string", - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) but no owner was set. This could happen for one of" + - " the following reasons:\n" + - "1. You may be adding a ref to a function component\n" + - "2. You may be adding a ref to a component that was not created inside a component's render method\n" + - "3. You have multiple copies of React loaded\n" + - "See https://fb.me/react-refs-must-have-owner for more information.", - mixedRef - ); + (function() { + if (!(typeof mixedRef === "string")) { + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + })(); + (function() { + if (!element._owner) { + throw ReactError( + "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; @@ -7775,14 +8088,18 @@ function throwOnInvalidObjectType(returnFiber, newChild) { "instead." + getCurrentFiberStackInDev(); } - invariant( - false, - "Objects are not valid as a React child (found: %s).%s", - Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - addendum - ); + (function() { + { + throw ReactError( + "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 + ); + } + })(); } } @@ -8441,11 +8758,13 @@ function ChildReconciler(shouldTrackSideEffects) { // but using the iterator instead. var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - typeof iteratorFn === "function", - "An object is not an iterable. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + if (!(typeof iteratorFn === "function")) { + throw ReactError( + "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. @@ -8495,7 +8814,11 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - invariant(newChildren != null, "An iterable object provided no iterator."); + (function() { + if (!(newChildren != null)) { + throw ReactError("An iterable object provided no iterator."); + } + })(); var resultingFirstChild = null; var previousNewFiber = null; @@ -8866,13 +9189,14 @@ function ChildReconciler(shouldTrackSideEffects) { // eslint-disable-next-lined no-fallthrough case FunctionComponent: { var Component = returnFiber.type; - invariant( - false, - "%s(...): Nothing was returned from render. This usually means a " + - "return statement is missing. Or, to render nothing, " + - "return null.", - Component.displayName || Component.name || "Component" - ); + (function() { + { + throw ReactError( + (Component.displayName || Component.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." + ); + } + })(); } } } @@ -8888,10 +9212,11 @@ var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); function cloneChildFibers(current$$1, workInProgress) { - invariant( - current$$1 === null || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + (function() { + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw ReactError("Resuming work not yet implemented."); + } + })(); if (workInProgress.child === null) { return; @@ -8925,11 +9250,13 @@ var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + if (!(c !== NO_CONTEXT)) { + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); return c; } @@ -8985,6 +9312,37 @@ function pushHostContext(fiber) { push(contextStackCursor$1, nextContext, fiber); } +function pushHostContextForEventComponent(fiber) { + var context = requiredContext(contextStackCursor$1.current); + var nextContext = getChildHostContextForEventComponent(context); + + // Don't push this Fiber's context unless it's unique. + if (context === nextContext) { + return; + } + + // 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); +} + +function pushHostContextForEventTarget(fiber) { + var context = requiredContext(contextStackCursor$1.current); + var eventTargetType = fiber.type.type; + var nextContext = getChildHostContextForEventTarget(context, eventTargetType); + + // Don't push this Fiber's context unless it's unique. + if (context === nextContext) { + return; + } + + // 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); +} + function popHostContext(fiber) { // Do not pop unless this Fiber provided the current context. // pushHostContext() only pushes Fibers that provide unique contexts. @@ -9022,7 +9380,6 @@ var currentlyRenderingFiber$1 = null; // 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 firstCurrentHook = null; var currentHook = null; var nextCurrentHook = null; var firstWorkInProgressHook = null; @@ -9052,60 +9409,107 @@ var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev = null; -function warnOnHookMismatchInDev() { +// 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; + +function mountHookTypesDev() { { - var componentName = getComponentName(currentlyRenderingFiber$1.type); - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); + var hookName = currentHookNameInDev; - var secondColumnStart = 22; + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } +} - var table = ""; - var prevHook = firstCurrentHook; - var nextHook = firstWorkInProgressHook; - var n = 1; - while (prevHook !== null && nextHook !== null) { - var oldHookName = prevHook._debugType; - var newHookName = nextHook._debugType; +function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; - var row = n + ". " + oldHookName; - - // Extra space so second column lines up - // lol @ IE not supporting String#repeat - while (row.length < secondColumnStart) { - row += " "; - } - - row += newHookName + "\n"; - - table += row; - prevHook = prevHook.next; - nextHook = nextHook.next; - n++; + if (hookTypesDev !== null) { + hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { + warnOnHookMismatchInDev(hookName); } + } + } +} +function checkDepsAreArrayDev(deps) { + { + if (deps !== undefined && deps !== null && !Array.isArray(deps)) { + // Verify deps, but only on mount to avoid extra checks. + // It's unlikely their type would change as usually you define them inline. warning$1( false, - "React has detected a change in the order of Hooks called by %s. " + - "This will lead to bugs and errors if not fixed. " + - "For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n" + - " Previous render Next render\n" + - " -------------------------------\n" + - "%s" + - " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", - componentName, - table + "%s received a final argument that is not an array (instead, received `%s`). When " + + "specified, the final argument must be an array.", + currentHookNameInDev, + typeof deps ); } } } +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 + // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { + row += " "; + } + + row += newHookName + "\n"; + + table += row; + } + + warning$1( + false, + "React has detected a change in the order of Hooks called by %s. " + + "This will lead to bugs and errors if not fixed. " + + "For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n" + + " Previous render Next render\n" + + " ------------------------------------------------------\n" + + "%s" + + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + componentName, + table + ); + } + } + } +} + function throwInvalidHookError() { - invariant( - false, - "Hooks can only be called inside the body of a function component. " + - "(https://fb.me/react-invalid-hook-call)" - ); + (function() { + { + throw ReactError( + "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) { @@ -9133,8 +9537,8 @@ function areHookInputsEqual(nextDeps, prevDeps) { "Previous: %s\n" + "Incoming: %s", currentHookNameInDev, - "[" + nextDeps.join(", ") + "]", - "[" + prevDeps.join(", ") + "]" + "[" + prevDeps.join(", ") + "]", + "[" + nextDeps.join(", ") + "]" ); } } @@ -9157,8 +9561,12 @@ function renderWithHooks( ) { renderExpirationTime = nextRenderExpirationTime; currentlyRenderingFiber$1 = workInProgress; - firstCurrentHook = nextCurrentHook = - current !== null ? current.memoizedState : null; + nextCurrentHook = current !== null ? current.memoizedState : null; + + { + hookTypesDev = current !== null ? current._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; + } // The following should have already been reset // currentHook = null; @@ -9172,11 +9580,26 @@ function renderWithHooks( // 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. { - ReactCurrentDispatcher$1.current = - nextCurrentHook === null - ? HooksDispatcherOnMountInDEV - : HooksDispatcherOnUpdateInDEV; + if (nextCurrentHook !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + // This dispatcher handles an edge case where a component is updating, + // but no stateful hooks have been used. + // We want to match the production code behavior (which will use HooksDispatcherOnMount), + // but with the extra DEV validation to ensure hooks ordering hasn't changed. + // This dispatcher does that. + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } } var children = Component(props, refOrContext); @@ -9187,14 +9610,18 @@ function renderWithHooks( numberOfReRenders += 1; // Start over from the beginning of the list - firstCurrentHook = nextCurrentHook = - current !== null ? current.memoizedState : null; + nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; currentHook = null; workInProgressHook = null; componentUpdateQueue = null; + { + // Also validate hook order for cascading updates. + hookTypesUpdateIndexDev = -1; + } + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; children = Component(props, refOrContext); @@ -9204,10 +9631,6 @@ function renderWithHooks( numberOfReRenders = 0; } - { - currentHookNameInDev = null; - } - // 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; @@ -9219,18 +9642,29 @@ function renderWithHooks( renderedWork.updateQueue = componentUpdateQueue; renderedWork.effectTag |= sideEffectTag; + { + renderedWork._debugHookTypes = hookTypesDev; + } + + // 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; renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; - firstCurrentHook = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + } + remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; @@ -9240,11 +9674,13 @@ function renderWithHooks( // renderPhaseUpdates = null; // numberOfReRenders = 0; - invariant( - !didRenderTooFewHooks, - "Rendered fewer hooks than expected. This may be caused by an accidental " + - "early return statement." - ); + (function() { + if (!!didRenderTooFewHooks) { + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } + })(); return children; } @@ -9268,21 +9704,23 @@ function resetHooks() { renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; - firstCurrentHook = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; + { + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + + currentHookNameInDev = null; + } + remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - { - currentHookNameInDev = null; - } - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -9299,9 +9737,6 @@ function mountWorkInProgressHook() { next: null }; - { - hook._debugType = currentHookNameInDev; - } if (workInProgressHook === null) { // This is the first hook in the list firstWorkInProgressHook = workInProgressHook = hook; @@ -9327,10 +9762,13 @@ function updateWorkInProgressHook() { nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - invariant( - nextCurrentHook !== null, - "Rendered more hooks than during the previous render." - ); + (function() { + if (!(nextCurrentHook !== null)) { + throw ReactError( + "Rendered more hooks than during the previous render." + ); + } + })(); currentHook = nextCurrentHook; var newHook = { @@ -9351,13 +9789,6 @@ function updateWorkInProgressHook() { workInProgressHook = workInProgressHook.next = newHook; } nextCurrentHook = currentHook.next; - - { - newHook._debugType = currentHookNameInDev; - if (currentHookNameInDev !== currentHook._debugType) { - warnOnHookMismatchInDev(); - } - } } return workInProgressHook; } @@ -9372,20 +9803,6 @@ function basicStateReducer(state, action) { return typeof action === "function" ? action(state) : action; } -function mountContext(context, observedBits) { - { - mountWorkInProgressHook(); - } - return readContext(context, observedBits); -} - -function updateContext(context, observedBits) { - { - updateWorkInProgressHook(); - } - return readContext(context, observedBits); -} - function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); var initialState = void 0; @@ -9398,8 +9815,8 @@ function mountReducer(reducer, initialArg, init) { var queue = (hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialState + lastRenderedReducer: reducer, + lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( null, @@ -9413,10 +9830,15 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - invariant( - queue !== null, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + (function() { + if (!(queue !== null)) { + throw ReactError( + "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 @@ -9452,8 +9874,7 @@ function updateReducer(reducer, initialArg, init) { hook.baseState = newState; } - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } @@ -9503,6 +9924,16 @@ function updateReducer(reducer, initialArg, init) { remainingExpirationTime = 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. + markRenderEventTime$$1(updateExpirationTime); + // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the @@ -9532,8 +9963,7 @@ function updateReducer(reducer, initialArg, init) { hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.eagerReducer = reducer; - queue.eagerState = _newState; + queue.lastRenderedState = _newState; } var dispatch = queue.dispatch; @@ -9549,8 +9979,8 @@ function mountState(initialState) { var queue = (hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( null, @@ -9793,25 +10223,14 @@ function updateMemo(nextCreate, deps) { return nextValue; } -// in a test-like environment, we want to warn if dispatchAction() -// is called outside of a batchedUpdates/TestUtils.act(...) call. -var shouldWarnForUnbatchedSetState = false; - -{ - // jest isn't a 'global', it's just exposed to tests via a wrapped function - // further, this isn't a test file, so flow doesn't recognize the symbol. So... - // $FlowExpectedError - because requirements don't give a damn about your type sigs. - if ("undefined" !== typeof jest) { - shouldWarnForUnbatchedSetState = true; - } -} - function dispatchAction(fiber, queue, action) { - invariant( - numberOfReRenders < RE_RENDER_LIMIT, - "Too many re-renders. React limits the number of renders to prevent " + - "an infinite loop." - ); + (function() { + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } + })(); { !(arguments.length <= 3) @@ -9855,10 +10274,10 @@ function dispatchAction(fiber, queue, action) { lastRenderPhaseUpdate.next = update; } } else { - flushPassiveEffects(); + flushPassiveEffects$$1(); - var currentTime = requestCurrentTime(); - var _expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var _expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: _expirationTime, @@ -9890,21 +10309,21 @@ 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 _eagerReducer = queue.eagerReducer; - if (_eagerReducer !== null) { + var _lastRenderedReducer = queue.lastRenderedReducer; + if (_lastRenderedReducer !== null) { var prevDispatcher = void 0; { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { - var currentState = queue.eagerState; - var _eagerState = _eagerReducer(currentState, action); + var currentState = queue.lastRenderedState; + 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 = _eagerReducer; + _update2.eagerReducer = _lastRenderedReducer; _update2.eagerState = _eagerState; if (is(_eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. @@ -9923,11 +10342,14 @@ function dispatchAction(fiber, queue, action) { } } { - if (shouldWarnForUnbatchedSetState === true) { - warnIfNotCurrentlyBatchingInDev(fiber); + // jest isn't a 'global', it's just exposed to tests via a wrapped function + // further, this isn't a test file, so flow doesn't recognize the symbol. So... + // $FlowExpectedError - because requirements don't give a damn about your type sigs. + if ("undefined" !== typeof jest) { + warnIfNotCurrentlyActingUpdatesInDev$$1(fiber); } } - scheduleWork(fiber, _expirationTime); + scheduleWork$$1(fiber, _expirationTime); } } @@ -9947,6 +10369,7 @@ var ContextOnlyDispatcher = { }; var HooksDispatcherOnMountInDEV = null; +var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; var InvalidNestedHooksDispatcherOnMountInDEV = null; var InvalidNestedHooksDispatcherOnUpdateInDEV = null; @@ -9978,26 +10401,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; - return mountContext(context, observedBits); + mountHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10008,6 +10442,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10018,10 +10453,12 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useRef: function(initialValue) { currentHookNameInDev = "useRef"; + mountHookTypesDev(); return mountRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10032,6 +10469,81 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; + mountHookTypesDev(); + return mountDebugValue(value, formatterFn); + } + }; + + HooksDispatcherOnMountWithHookTypesInDEV = { + readContext: function(context, observedBits) { + return readContext(context, observedBits); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + updateHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function(context, observedBits) { + currentHookNameInDev = "useContext"; + updateHookTypesDev(); + return readContext(context, observedBits); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + updateHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + updateHookTypesDev(); + return mountRef(initialValue); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); return mountDebugValue(value, formatterFn); } }; @@ -10042,26 +10554,32 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; + updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; - return updateContext(context, observedBits); + updateHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; + updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10072,6 +10590,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10082,10 +10601,12 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useRef: function(initialValue) { currentHookNameInDev = "useRef"; + updateHookTypesDev(); return updateRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10096,6 +10617,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; @@ -10108,31 +10630,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; warnInvalidHookAccess(); - return mountContext(context, observedBits); + mountHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10144,6 +10672,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10155,11 +10684,13 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useRef: function(initialValue) { currentHookNameInDev = "useRef"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10171,6 +10702,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountDebugValue(value, formatterFn); } }; @@ -10183,31 +10715,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; warnInvalidHookAccess(); - return updateContext(context, observedBits); + updateHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10219,6 +10757,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10230,11 +10769,13 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useRef: function(initialValue) { currentHookNameInDev = "useRef"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10246,11 +10787,16 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; } +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var now$2 = Scheduler.unstable_now; + var commitTime = 0; var profilerStartTime = -1; @@ -10262,7 +10808,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } - commitTime = now$$1(); + commitTime = now$2(); } function startProfilerTimer(fiber) { @@ -10270,10 +10816,10 @@ function startProfilerTimer(fiber) { return; } - profilerStartTime = now$$1(); + profilerStartTime = now$2(); if (fiber.actualStartTime < 0) { - fiber.actualStartTime = now$$1(); + fiber.actualStartTime = now$2(); } } @@ -10290,7 +10836,7 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { } if (profilerStartTime >= 0) { - var elapsedTime = now$$1() - profilerStartTime; + var elapsedTime = now$2() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; @@ -10509,11 +11055,13 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - invariant( - false, - "Expected prepareToHydrateHostInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var instance = fiber.stateNode; @@ -10537,11 +11085,13 @@ function prepareToHydrateHostInstance( function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - invariant( - false, - "Expected prepareToHydrateHostTextInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var textInstance = fiber.stateNode; @@ -10585,18 +11135,22 @@ function prepareToHydrateHostTextInstance(fiber) { function skipPastDehydratedSuspenseInstance(fiber) { if (!supportsHydration) { - invariant( - false, - "Expected skipPastDehydratedSuspenseInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var suspenseInstance = fiber.stateNode; - invariant( - suspenseInstance, - "Expected to have a hydrated suspense instance. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!suspenseInstance) { + throw ReactError( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( suspenseInstance ); @@ -10675,17 +11229,21 @@ 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; { didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; + didWarnAboutMaxDuration = false; } function reconcileChildren( @@ -11351,12 +11909,13 @@ function pushHostRootContext(workInProgress) { function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - invariant( - updateQueue !== null, - "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." - ); + (function() { + if (!(updateQueue !== null)) { + throw ReactError( + "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; @@ -11580,13 +12139,16 @@ function mountLazyComponent( // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - invariant( - false, - "Element type is invalid. Received a promise that resolves to: %s. " + - "Lazy element type must resolve to a class or function.%s", - Component, - hint - ); + (function() { + { + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } + })(); } } return child; @@ -11717,6 +12279,24 @@ function mountIndeterminateComponent( typeof value.render === "function" && value.$$typeof === undefined ) { + { + var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { + warningWithoutStack$1( + false, + "The <%s /> component appears to be a function component that returns a class instance. " + + "Change %s to a class that extends React.Component instead. " + + "If you can't use a class try assigning the prototype on the function as a workaround. " + + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + + "cannot be called with `new` by React.", + _componentName, + _componentName, + _componentName + ); + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; @@ -11838,15 +12418,15 @@ function validateFunctionComponentInDev(workInProgress, Component) { typeof Component.contextType === "object" && Component.contextType !== null ) { - var _componentName = getComponentName(Component) || "Unknown"; + var _componentName2 = getComponentName(Component) || "Unknown"; - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) { + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) { warningWithoutStack$1( false, "%s: Function components do not support contextType.", - _componentName + _componentName2 ); - didWarnAboutContextTypeOnFunctionComponent[_componentName] = true; + didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true; } } } @@ -11859,6 +12439,12 @@ function updateSuspenseComponent( var mode = workInProgress.mode; var nextProps = workInProgress.pendingProps; + { + if (shouldSuspend(workInProgress)) { + workInProgress.effectTag |= DidCapture; + } + } + // We should attempt to render the primary children unless this boundary // already suspended during this render (`alreadyCaptured` is true). var nextState = workInProgress.memoizedState; @@ -11872,12 +12458,26 @@ function updateSuspenseComponent( // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. nextState = { - timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork + fallbackExpirationTime: + nextState !== null ? nextState.fallbackExpirationTime : NoWork }; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } + { + if ("maxDuration" in nextProps) { + if (!didWarnAboutMaxDuration) { + didWarnAboutMaxDuration = true; + warning$1( + false, + "maxDuration has been removed from React. " + + "Remove the maxDuration prop." + ); + } + } + } + // 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 @@ -12128,15 +12728,73 @@ function updateSuspenseComponent( return next; } +function retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime +) { + // Detach from the current dehydrated boundary. + current$$1.alternate = null; + workInProgress.alternate = null; + + // Insert a deletion in the effect list. + var returnFiber = workInProgress.return; + (function() { + if (!(returnFiber !== null)) { + throw ReactError( + "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; + + // 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); +} + function updateDehydratedSuspenseComponent( current$$1, workInProgress, renderExpirationTime ) { + 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. - workInProgress.expirationTime = Never; + 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$$1(); + // 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) { @@ -12145,56 +12803,32 @@ function updateDehydratedSuspenseComponent( workInProgress.child = null; return null; } + 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; - var suspenseInstance = current$$1.stateNode; - if ( - didReceiveUpdate || - hasContextChanged$$1 || - isSuspenseInstanceFallback(suspenseInstance) - ) { + 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. - - // Alternatively, 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. - - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; - - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - invariant( - returnFiber !== null, - "Suspense boundaries are never on the root. " + - "This is probably a bug in React." + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime ); - 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; - - // 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); } else if (isSuspenseInstancePending(suspenseInstance)) { // This component is still pending more data from the server, so we can't hydrate its // content. We treat it as if this component suspended itself. It might seem as if @@ -12211,7 +12845,7 @@ function updateDehydratedSuspenseComponent( // Register a callback to retry this boundary once the server has sent the result. registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryTimedOutBoundary$$1.bind(null, current$$1) ); return null; } else { @@ -12392,6 +13026,55 @@ function updateContextConsumer( return workInProgress.child; } +function updateEventComponent$1( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + pushHostContextForEventComponent(workInProgress); + return workInProgress.child; +} + +function updateEventTarget(current$$1, workInProgress, renderExpirationTime) { + var type = workInProgress.type.type; + var nextProps = workInProgress.pendingProps; + var eventTargetChild = getEventTargetChildElement(type, nextProps); + + { + !(nextProps.children == null) + ? warning$1(false, "Event targets should not have children.") + : void 0; + } + if (eventTargetChild !== null) { + var child = (workInProgress.child = createFiberFromTypeAndProps( + eventTargetChild.type, + null, + eventTargetChild.props, + null, + workInProgress.mode, + renderExpirationTime + )); + child.return = workInProgress; + + if (current$$1 === null || current$$1.child === null) { + child.effectTag = Placement; + } + } else { + reconcileChildren(current$$1, workInProgress, null, renderExpirationTime); + } + pushHostContextForEventTarget(workInProgress); + return workInProgress.child; +} + function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } @@ -12521,8 +13204,19 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { // 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; } + break; + } + case EventComponent: + if (enableEventAPI) { + pushHostContextForEventComponent(workInProgress); + } + break; + case EventTarget: { + if (enableEventAPI) { + pushHostContextForEventTarget(workInProgress); + } + break; } } return bailoutOnAlreadyFinishedWork( @@ -12707,12 +13401,34 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { } break; } + case EventComponent: { + if (enableEventAPI) { + return updateEventComponent$1( + current$$1, + workInProgress, + renderExpirationTime + ); + } + break; + } + case EventTarget: { + if (enableEventAPI) { + return updateEventTarget( + current$$1, + workInProgress, + renderExpirationTime + ); + } + break; + } } - invariant( - false, - "Unknown unit of work tag. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var valueCursor = createCursor(null); @@ -12815,10 +13531,10 @@ function calculateChangedBits(context, newValue, oldValue) { var changedBits = typeof context._calculateChangedBits === "function" ? context._calculateChangedBits(oldValue, newValue) - : maxSigned31BitInt; + : MAX_SIGNED_31_BIT_INT; { - !((changedBits & maxSigned31BitInt) === changedBits) + !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning$1( false, "calculateChangedBits: Expected the return value to be a " + @@ -13021,11 +13737,11 @@ function readContext(context, observedBits) { var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. if ( typeof observedBits !== "number" || - observedBits === maxSigned31BitInt + observedBits === MAX_SIGNED_31_BIT_INT ) { // Observe all updates. lastContextWithAllBitsObserved = context; - resolvedObservedBits = maxSigned31BitInt; + resolvedObservedBits = MAX_SIGNED_31_BIT_INT; } else { resolvedObservedBits = observedBits; } @@ -13037,13 +13753,13 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - invariant( - currentlyRenderingFiber !== null, - "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()." - ); + (function() { + if (!(currentlyRenderingFiber !== null)) { + throw ReactError( + "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. lastContextDependency = contextItem; @@ -13447,8 +14163,17 @@ function processUpdateQueue( newExpirationTime = updateExpirationTime; } } else { - // This update does have sufficient priority. Process it and compute - // a new result. + // 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. + markRenderEventTime$$1(updateExpirationTime); + + // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -13557,12 +14282,14 @@ function processUpdateQueue( } function callCallback(callback, context) { - invariant( - typeof callback === "function", - "Invalid argument passed as callback. Expected a function. Instead " + - "received: %s", - callback - ); + (function() { + if (!(typeof callback === "function")) { + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + })(); callback.call(context); } @@ -13741,43 +14468,19 @@ if (supportsMutation) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; - if (isHidden) { - // This child is inside a timed out tree. Hide it. - instance = cloneHiddenInstance(instance, type, props, node); - } else { - // This child was previously inside a timed out tree. If it was not - // updated during this render, it may need to be unhidden. Clone - // again to be sure. - instance = cloneUnhiddenInstance(instance, type, props, node); - } - node.stateNode = instance; + instance = cloneHiddenInstance(instance, type, props, node); } appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - if (isHidden) { - _instance = createHiddenTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } else { - _instance = createTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } - node.stateNode = _instance; + _instance = cloneHiddenTextInstance(_instance, text, node); } appendInitialChild(parent, _instance); } else if (node.tag === HostPortal) { @@ -13785,22 +14488,28 @@ if (supportsMutation) { // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { - var current = node.alternate; - if (current !== null) { - var oldState = current.memoizedState; - var newState = node.memoizedState; - var oldIsHidden = oldState !== null; - var newIsHidden = newState !== null; - if (oldIsHidden !== newIsHidden) { - // The placeholder either just timed out or switched back to the normal - // children after having previously timed out. Toggle the visibility of - // the direct host children. - var primaryChildParent = newIsHidden ? node.child : node; + 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) { - appendAllChildren(parent, primaryChildParent, true, newIsHidden); + if (primaryChildParent.child !== null) { + primaryChildParent.child.return = primaryChildParent; + appendAllChildren( + parent, + primaryChildParent, + true, + newIsHidden + ); + } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { + fallbackChildParent.return = node; + node = fallbackChildParent; + continue; + } } - // eslint-disable-next-line no-labels - break branches; } } if (node.child !== null) { @@ -13844,43 +14553,19 @@ if (supportsMutation) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; - if (isHidden) { - // This child is inside a timed out tree. Hide it. - instance = cloneHiddenInstance(instance, type, props, node); - } else { - // This child was previously inside a timed out tree. If it was not - // updated during this render, it may need to be unhidden. Clone - // again to be sure. - instance = cloneUnhiddenInstance(instance, type, props, node); - } - node.stateNode = instance; + instance = cloneHiddenInstance(instance, type, props, node); } appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance2 = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - if (isHidden) { - _instance2 = createHiddenTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } else { - _instance2 = createTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } - node.stateNode = _instance2; + _instance2 = cloneHiddenTextInstance(_instance2, text, node); } appendChildToContainerChildSet(containerChildSet, _instance2); } else if (node.tag === HostPortal) { @@ -13888,27 +14573,28 @@ if (supportsMutation) { // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { - var current = node.alternate; - if (current !== null) { - var oldState = current.memoizedState; - var newState = node.memoizedState; - var oldIsHidden = oldState !== null; - var newIsHidden = newState !== null; - if (oldIsHidden !== newIsHidden) { - // The placeholder either just timed out or switched back to the normal - // children after having previously timed out. Toggle the visibility of - // the direct host children. - var primaryChildParent = newIsHidden ? node.child : node; + 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) { - appendAllChildrenToContainer( - containerChildSet, - primaryChildParent, - true, - newIsHidden - ); + if (primaryChildParent.child !== null) { + primaryChildParent.child.return = primaryChildParent; + appendAllChildrenToContainer( + containerChildSet, + primaryChildParent, + true, + newIsHidden + ); + } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { + fallbackChildParent.return = node; + node = fallbackChildParent; + continue; + } } - // eslint-disable-next-line no-labels - break branches; } } if (node.child !== null) { @@ -14112,11 +14798,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - invariant( - workInProgress.stateNode !== null, - "We must have new props for new mounts. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(workInProgress.stateNode !== null)) { + throw ReactError( + "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; } @@ -14185,11 +14873,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - invariant( - workInProgress.stateNode !== null, - "We must have new props for new mounts. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(workInProgress.stateNode !== null)) { + throw ReactError( + "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(); @@ -14222,37 +14912,72 @@ function completeWork(current, workInProgress, renderExpirationTime) { } var nextDidTimeout = nextState !== null; - var prevDidTimeout = current !== null && current.memoizedState !== 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); - } else if (!nextDidTimeout && prevDidTimeout) { - // We just switched from the fallback to the normal children. Delete - // the fallback. - // TODO: Would it be better to store the fallback fragment on - 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; - } else { - workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; - currentFallbackChild.nextEffect = null; + } else { + var prevState = current.memoizedState; + prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { + // We just switched from the fallback to the normal children. + + // Mark the event time of the switching from fallback to normal children, + // based on the start of when we first showed the fallback. This time + var fallbackExpirationTimeExpTime = prevState.fallbackExpirationTime; + markRenderEventTime$$1(fallbackExpirationTimeExpTime); + + // 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; + } else { + workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; + currentFallbackChild.nextEffect = null; + } + currentFallbackChild.effectTag = Deletion; } - currentFallbackChild.effectTag = Deletion; } } - if (nextDidTimeout || prevDidTimeout) { - // If the children are hidden, or if they were previous hidden, schedule - // an effect to toggle their visibility. This is also used to attach a - // retry listener to the promise. - workInProgress.effectTag |= Update; + if (nextDidTimeout && !prevDidTimeout) { + // If this subtreee is running in concurrent mode we can suspend, + // otherwise we won't suspend. + // TODO: This will still suspend a synchronous tree if anything + // in the concurrent tree already suspended during this render. + // This is a known bug. + if ((workInProgress.mode & ConcurrentMode) !== NoContext) { + renderDidSuspend$$1(); + } + } + + if (supportsPersistence) { + // TODO: Only schedule updates if not prevDidTimeout. + if (nextDidTimeout) { + // If this boundary just timed out, schedule an effect to attach a + // retry listener to the proimse. This flag is also used to hide the + // primary children. + workInProgress.effectTag |= Update; + } + } + if (supportsMutation) { + // TODO: Only schedule updates if these values are non equal, i.e. it changed. + if (nextDidTimeout || prevDidTimeout) { + // If this boundary just timed out, schedule an effect to attach a + // retry listener to the proimse. This flag is also used to hide the + // primary children. In mutation mode, we also need the flag to + // *unhide* children that were previously hidden, so check if the + // is currently timed out, too. + workInProgress.effectTag |= Update; + } } break; } @@ -14287,11 +15012,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableSuspenseServerRenderer) { if (current === null) { var _wasHydrated2 = popHydrationState(workInProgress); - invariant( - _wasHydrated2, - "A dehydrated suspense component was completed without a hydrated node. " + - "This is probably a bug in React." - ); + (function() { + if (!_wasHydrated2) { + throw ReactError( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + })(); skipPastDehydratedSuspenseInstance(workInProgress); } else if ((workInProgress.effectTag & DidCapture) === NoEffect) { // This boundary did not suspend so it's now hydrated. @@ -14306,12 +15033,61 @@ function completeWork(current, workInProgress, renderExpirationTime) { } break; } + case EventComponent: { + if (enableEventAPI) { + popHostContext(workInProgress); + var _rootContainerInstance2 = getRootHostContainer(); + var responder = workInProgress.type.responder; + var eventComponentInstance = workInProgress.stateNode; + + if (eventComponentInstance === null) { + var responderState = null; + if (responder.createInitialState !== undefined) { + responderState = responder.createInitialState(newProps); + } + eventComponentInstance = workInProgress.stateNode = { + context: null, + props: newProps, + responder: responder, + rootInstance: _rootContainerInstance2, + state: responderState + }; + mountEventComponent(eventComponentInstance); + } else { + // Update the props on the event component state node + eventComponentInstance.props = newProps; + // Update the root container, so we can properly unmount events at some point + eventComponentInstance.rootInstance = _rootContainerInstance2; + updateEventComponent(eventComponentInstance); + } + } + break; + } + case EventTarget: { + if (enableEventAPI) { + popHostContext(workInProgress); + var _type = workInProgress.type.type; + var _rootContainerInstance3 = getRootHostContainer(); + var shouldUpdate = handleEventTarget( + _type, + newProps, + _rootContainerInstance3, + workInProgress + ); + if (shouldUpdate) { + markUpdate(workInProgress); + } + } + break; + } default: - invariant( - false, - "Unknown unit of work tag. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } return null; @@ -14508,7 +15284,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { ); if (hasCaughtError()) { var unmountError = clearCaughtError(); - captureCommitPhaseError(current$$1, unmountError); + captureCommitPhaseError$$1(current$$1, unmountError); } } } @@ -14521,7 +15297,7 @@ function safelyDetachRef(current$$1) { invokeGuardedCallback(null, ref, null, null); if (hasCaughtError()) { var refError = clearCaughtError(); - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } } } else { @@ -14535,7 +15311,7 @@ function safelyCallDestroy(current$$1, destroy) { invokeGuardedCallback(null, destroy, null); if (hasCaughtError()) { var error = clearCaughtError(); - captureCommitPhaseError(current$$1, error); + captureCommitPhaseError$$1(current$$1, error); } } } @@ -14616,14 +15392,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case HostText: case HostPortal: case IncompleteClassComponent: + case EventTarget: // Nothing to do for these component types return; default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -14659,22 +15438,23 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else if (typeof _destroy.then === "function") { addendum = "\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. " + - "Instead, you may write an async function separately " + - "and then call it from inside the effect:\n\n" + - "async function fetchComment(commentId) {\n" + - " // You can await here\n" + - "}\n\n" + + "Instead, write the async function inside your effect " + + "and call it immediately:\n\n" + "useEffect(() => {\n" + - " fetchComment(commentId);\n" + - "}, [commentId]);\n\n" + - "In the future, React will provide a more idiomatic solution for data fetching " + - "that doesn't involve writing effects manually."; + " async function fetchData() {\n" + + " // You can await here\n" + + " const response = await MyAPI.getData(someId);\n" + + " // ...\n" + + " }\n" + + " fetchData();\n" + + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + + "Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching"; } else { addendum = " You returned: " + _destroy; } warningWithoutStack$1( false, - "An Effect function must not return anything besides a function, " + + "An effect function must not return anything besides a function, " + "which is used for clean-up.%s%s", addendum, getStackByFiberInDevAndProd(finishedWork) @@ -14911,15 +15691,17 @@ function commitLifeCycles( return; } case SuspenseComponent: - break; case IncompleteClassComponent: + case EventTarget: break; default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -15066,6 +15848,13 @@ function commitUnmount(current$$1) { } return; } + case EventComponent: { + if (enableEventAPI) { + var eventComponentInstance = current$$1.stateNode; + unmountEventComponent(eventComponentInstance); + current$$1.stateNode = null; + } + } } } @@ -15139,13 +15928,10 @@ function commitContainer(finishedWork) { } switch (finishedWork.tag) { - case ClassComponent: { - return; - } - case HostComponent: { - return; - } - case HostText: { + case ClassComponent: + case HostComponent: + case HostText: + case EventTarget: { return; } case HostRoot: @@ -15157,11 +15943,13 @@ function commitContainer(finishedWork) { return; } default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -15174,11 +15962,13 @@ function getHostParentFiber(fiber) { } parent = parent.return; } - invariant( - false, - "Expected to find a host parent. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } function isHostParent(fiber) { @@ -15260,11 +16050,13 @@ function commitPlacement(finishedWork) { isContainer = true; break; default: - invariant( - false, - "Invalid host parent fiber. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "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 @@ -15279,17 +16071,18 @@ function commitPlacement(finishedWork) { var node = finishedWork; while (true) { if (node.tag === HostComponent || node.tag === HostText) { + var stateNode = node.stateNode; if (before) { if (isContainer) { - insertInContainerBefore(parent, node.stateNode, before); + insertInContainerBefore(parent, stateNode, before); } else { - insertBefore(parent, node.stateNode, before); + insertBefore(parent, stateNode, before); } } else { if (isContainer) { - appendChildToContainer(parent, node.stateNode); + appendChildToContainer(parent, stateNode); } else { - appendChild$1(parent, node.stateNode); + appendChild$1(parent, stateNode); } } } else if (node.tag === HostPortal) { @@ -15331,11 +16124,13 @@ function unmountHostComponents(current$$1) { if (!currentParentIsValid) { var parent = node.return; findParent: while (true) { - invariant( - parent !== null, - "Expected to find a host parent. This error is likely caused by " + - "a bug in React. Please file an issue." - ); + (function() { + if (!(parent !== null)) { + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); switch (parent.tag) { case HostComponent: currentParent = parent.stateNode; @@ -15438,6 +16233,13 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { + return; + } + case SuspenseComponent: { + commitSuspenseComponent(finishedWork); + return; + } } commitContainer(finishedWork); @@ -15485,11 +16287,13 @@ function commitWork(current$$1, finishedWork) { return; } case HostText: { - invariant( - finishedWork.stateNode !== null, - "This should have a text node initialized. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(finishedWork.stateNode !== null)) { + throw ReactError( + "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 @@ -15499,6 +16303,36 @@ function commitWork(current$$1, finishedWork) { commitTextUpdate(textInstance, oldText, newText); return; } + case EventTarget: { + if (enableEventAPI) { + var _type = finishedWork.type.type; + var props = finishedWork.memoizedProps; + var _instance4 = finishedWork.stateNode; + var parentInstance = null; + + var node = finishedWork.return; + // Traverse up the fiber tree until we find the parent host node. + while (node !== null) { + if (node.tag === HostComponent) { + parentInstance = node.stateNode; + break; + } else if (node.tag === HostRoot) { + parentInstance = node.stateNode.containerInfo; + break; + } + node = node.return; + } + (function() { + if (!(parentInstance !== null)) { + throw ReactError( + "This should have a parent host component initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + commitEventTarget(_type, props, _instance4, parentInstance); + } + return; + } case HostRoot: { return; } @@ -15506,63 +16340,72 @@ function commitWork(current$$1, finishedWork) { return; } case SuspenseComponent: { - var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; - var primaryChildParent = finishedWork; - if (newState === null) { - newDidTimeout = false; - } else { - newDidTimeout = true; - primaryChildParent = finishedWork.child; - if (newState.timedOutAt === NoWork) { - // If the children had not already timed out, record the time. - // This is used to compute the elapsed time during subsequent - // attempts to render the children. - newState.timedOutAt = requestCurrentTime(); - } - } - - if (primaryChildParent !== null) { - hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); - } - - // 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(); - } - thenables.forEach(function(thenable) { - // Memoize using the boundary fiber to prevent redundant listeners. - var retry = resolveRetryThenable.bind(null, finishedWork, thenable); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - thenable.then(retry, retry); - } - }); - } - + commitSuspenseComponent(finishedWork); return; } case IncompleteClassComponent: { return; } default: { - invariant( - false, - "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() { + { + throw ReactError( + "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 primaryChildParent = finishedWork; + if (newState === null) { + newDidTimeout = false; + } else { + newDidTimeout = true; + primaryChildParent = finishedWork.child; + if (newState.fallbackExpirationTime === NoWork) { + // If the children had not already timed out, record the time. + // This is used to compute the elapsed time during subsequent + // attempts to render the children. + // We model this as a normal pri expiration time since that's + // how we infer start time for updates. + newState.fallbackExpirationTime = computeAsyncExpirationNoBucket( + requestCurrentTime$$1() ); } } + + if (supportsMutation && primaryChildParent !== null) { + hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); + } + + // 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(); + } + thenables.forEach(function(thenable) { + // Memoize using the boundary fiber to prevent redundant listeners. + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + if (enableSchedulerTracing) { + retry = tracing.unstable_wrap(retry); + } + if (!retryCache.has(thenable)) { + retryCache.add(thenable); + thenable.then(retry, retry); + } + }); + } } function commitResetTextContent(current$$1) { @@ -15584,7 +16427,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { update.payload = { element: null }; var error = errorInfo.value; update.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return update; @@ -15610,7 +16453,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed$$1(this); } var error = errorInfo.value; var stack = errorInfo.stack; @@ -15658,7 +16501,7 @@ function attachPingListener(root, renderExpirationTime, thenable) { if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); - var ping = pingSuspendedRoot.bind( + var ping = pingSuspendedRoot$$1.bind( null, root, thenable, @@ -15691,48 +16534,8 @@ function throwException( // This is a thenable. var thenable = value; - // Find the earliest timeout threshold of all the placeholders in the - // ancestor path. We could avoid this traversal by storing the thresholds on - // the stack, but we choose not to because we only hit this path if we're - // IO-bound (i.e. if something suspends). Whereas the stack is used even in - // the non-IO- bound case. - var _workInProgress = returnFiber; - var earliestTimeoutMs = -1; - var startTimeMs = -1; - do { - if (_workInProgress.tag === SuspenseComponent) { - var current$$1 = _workInProgress.alternate; - if (current$$1 !== null) { - var currentState = current$$1.memoizedState; - if (currentState !== null) { - // Reached a boundary that already timed out. Do not search - // any further. - var timedOutAt = currentState.timedOutAt; - startTimeMs = expirationTimeToMs(timedOutAt); - // Do not search any further. - break; - } - } - var timeoutPropMs = _workInProgress.pendingProps.maxDuration; - if (typeof timeoutPropMs === "number") { - if (timeoutPropMs <= 0) { - earliestTimeoutMs = 0; - } else if ( - earliestTimeoutMs === -1 || - timeoutPropMs < earliestTimeoutMs - ) { - earliestTimeoutMs = timeoutPropMs; - } - } - } - // If there is a DehydratedSuspenseComponent we don't have to do anything because - // if something suspends inside it, we will simply leave that as dehydrated. It - // will never timeout. - _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // Schedule the nearest Suspense to re-render the timed out view. - _workInProgress = returnFiber; + var _workInProgress = returnFiber; do { if ( _workInProgress.tag === SuspenseComponent && @@ -15758,7 +16561,7 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a concurrent mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & ConcurrentMode) === NoEffect) { + if ((_workInProgress.mode & ConcurrentMode) === NoContext) { _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. @@ -15796,41 +16599,6 @@ function throwException( attachPingListener(root, renderExpirationTime, thenable); - var absoluteTimeoutMs = void 0; - if (earliestTimeoutMs === -1) { - // If no explicit threshold is given, default to an arbitrarily large - // value. The actual size doesn't matter because the threshold for the - // whole tree will be clamped to the expiration time. - absoluteTimeoutMs = maxSigned31BitInt; - } else { - if (startTimeMs === -1) { - // This suspend happened outside of any already timed-out - // placeholders. We don't know exactly when the update was - // scheduled, but we can infer an approximate start time from the - // expiration time. First, find the earliest uncommitted expiration - // time in the tree, including work that is suspended. Then subtract - // the offset used to compute an async update's expiration time. - // This will cause high priority (interactive) work to expire - // earlier than necessary, but we can account for this by adjusting - // for the Just Noticeable Difference. - var earliestExpirationTime = findEarliestOutstandingPriorityLevel( - root, - renderExpirationTime - ); - var earliestExpirationTimeMs = expirationTimeToMs( - earliestExpirationTime - ); - startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; - } - absoluteTimeoutMs = startTimeMs + earliestTimeoutMs; - } - - // Mark the earliest timeout in the suspended fiber's ancestor path. - // After completing the root, we'll take the largest of all the - // suspended fiber's timeouts and use it to compute a timeout for the - // whole tree. - renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime); - _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; @@ -15844,18 +16612,20 @@ function throwException( var retryCache = _workInProgress.memoizedState; if (retryCache === null) { retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var _current = _workInProgress.alternate; - invariant( - _current, - "A dehydrated suspense boundary must commit before trying to render. " + - "This is probably a bug in React." - ); - _current.memoizedState = retryCache; + var current$$1 = _workInProgress.alternate; + (function() { + if (!current$$1) { + throw ReactError( + "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( + var retry = resolveRetryThenable$$1.bind( null, _workInProgress, thenable @@ -15888,7 +16658,7 @@ function throwException( // 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(); + renderDidError$$1(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; do { @@ -15915,7 +16685,7 @@ function throwException( (typeof ctor.getDerivedStateFromError === "function" || (instance !== null && typeof instance.componentDidCatch === "function" && - !isAlreadyFailedLegacyErrorBoundary(instance))) + !isAlreadyFailedLegacyErrorBoundary$$1(instance))) ) { workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; @@ -15954,11 +16724,13 @@ function unwindWork(workInProgress, renderExpirationTime) { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - invariant( - (_effectTag & DidCapture) === NoEffect, - "The root failed to unmount after an error. This is likely a bug in " + - "React. Please file an issue." - ); + (function() { + if (!((_effectTag & DidCapture) === NoEffect)) { + throw ReactError( + "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; } @@ -15995,6 +16767,12 @@ function unwindWork(workInProgress, renderExpirationTime) { case ContextProvider: popProvider(workInProgress); return null; + case EventComponent: + case EventTarget: + if (enableEventAPI) { + popHostContext(workInProgress); + } + return null; default: return null; } @@ -16029,8 +16807,20 @@ function unwindInterruptedWork(interruptedWork) { } } +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback; +var cancelCallback$1 = Scheduler.unstable_cancelCallback; +var shouldYield$1 = Scheduler.unstable_shouldYield; +var now$1 = Scheduler.unstable_now; +var getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel; +var NormalPriority$1 = Scheduler.unstable_NormalPriority; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; +var ReactShouldWarnActingUpdates = + ReactSharedInternals.ReactShouldWarnActingUpdates; var didWarnAboutStateTransition = void 0; var didWarnSetStateChildContext = void 0; @@ -16040,14 +16830,18 @@ var warnAboutInvalidUpdates = void 0; 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 - invariant( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null, - "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" - ); + (function() { + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + throw ReactError( + "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" + ); + } + })(); } { @@ -16102,6 +16896,11 @@ if (enableSchedulerTracing) { }; } +// Represents the expiration time that incoming updates should use. (If this +// is NoWork, use the default strategy: async updates in async mode, sync +// updates in sync mode.) +var expirationContext = NoWork; + var isWorking = false; // The next work in progress fiber that we're currently working on. @@ -16109,7 +16908,8 @@ var nextUnitOfWork = null; var nextRoot = null; // The time at which we're currently rendering work. var nextRenderExpirationTime = NoWork; -var nextLatestAbsoluteTimeoutMs = -1; +var mostRecentEventTime = Sync; +var nextRenderDidSuspend = false; var nextRenderDidError = false; // The next fiber with an effect that we're currently committing. @@ -16232,7 +17032,8 @@ function resetStack() { nextRoot = null; nextRenderExpirationTime = NoWork; - nextLatestAbsoluteTimeoutMs = -1; + mostRecentEventTime = Sync; + nextRenderDidSuspend = false; nextRenderDidError = false; nextUnitOfWork = null; } @@ -16385,14 +17186,16 @@ function commitPassiveEffects(root, firstEffect) { var didError = false; var error = void 0; { + isInPassiveEffectDEV = true; invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + isInPassiveEffectDEV = false; if (hasCaughtError()) { didError = true; error = clearCaughtError(); } } if (didError) { - captureCommitPhaseError(effect, error); + captureCommitPhaseError$1(effect, error); } } effect = effect.nextEffect; @@ -16412,16 +17215,24 @@ function commitPassiveEffects(root, firstEffect) { if (!isBatchingUpdates && !isRendering) { performSyncWork(); } + + { + if (rootWithPendingPassiveEffects === root) { + nestedPassiveEffectCountDEV++; + } else { + nestedPassiveEffectCountDEV = 0; + } + } } -function isAlreadyFailedLegacyErrorBoundary(instance) { +function isAlreadyFailedLegacyErrorBoundary$1(instance) { return ( legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } -function markLegacyErrorBoundaryAsFailed(instance) { +function markLegacyErrorBoundaryAsFailed$1(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); } else { @@ -16429,15 +17240,17 @@ function markLegacyErrorBoundaryAsFailed(instance) { } } -function flushPassiveEffects() { +function flushPassiveEffects$1() { + var didFlushEffects = passiveEffectCallback !== null; if (passiveEffectCallbackHandle !== null) { - cancelPassiveEffects(passiveEffectCallbackHandle); + cancelCallback$1(passiveEffectCallbackHandle); } if (passiveEffectCallback !== null) { // We call the scheduled callback instead of commitPassiveEffects directly // to ensure tracing works correctly. passiveEffectCallback(); } + return didFlushEffects; } function commitRoot(root, finishedWork) { @@ -16445,18 +17258,21 @@ function commitRoot(root, finishedWork) { isCommitting$1 = true; startCommitTimer(); - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug " + - "related to the return field. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + if (!(root.current !== finishedWork)) { + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - committedExpirationTime !== NoWork, - "Cannot commit an incomplete root. This error is likely caused by a " + - "bug in React. Please file an issue." - ); + (function() { + if (!(committedExpirationTime !== NoWork)) { + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); root.pendingCommitExpirationTime = NoWork; // Update the pending priority levels to account for the work that we are @@ -16514,12 +17330,14 @@ function commitRoot(root, finishedWork) { } } if (didError) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, error); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; @@ -16550,12 +17368,14 @@ function commitRoot(root, finishedWork) { } } if (_didError) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, _error); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, _error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; @@ -16595,12 +17415,14 @@ function commitRoot(root, finishedWork) { } } if (_didError2) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, _error2); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, _error2); if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; } @@ -16619,11 +17441,9 @@ function commitRoot(root, finishedWork) { // here because that code is still in flux. callback = tracing.unstable_wrap(callback); } - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return schedulePassiveEffects(callback); - } + passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + callback ); passiveEffectCallback = callback; } @@ -17027,20 +17847,22 @@ function workLoop(isYieldy) { } } else { // Flush asynchronous work until there's a higher priority event - while (nextUnitOfWork !== null && !shouldYield$$1()) { + while (nextUnitOfWork !== null && !shouldYield$1()) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } } function renderRoot(root, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused " + - "by a bug in React. Please file an issue." - ); + (function() { + if (!!isWorking) { + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); - flushPassiveEffects(); + flushPassiveEffects$1(); isWorking = true; var previousDispatcher = ReactCurrentDispatcher.current; @@ -17140,7 +17962,7 @@ function renderRoot(root, isYieldy) { if (nextUnitOfWork === null) { // This is a fatal error. didFatal = true; - onUncaughtError(thrownValue); + onUncaughtError$1(thrownValue); } else { if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) { // Record the time spent rendering before an error was thrown. @@ -17164,12 +17986,13 @@ function renderRoot(root, isYieldy) { // TODO: we already know this isn't true in some cases. // At least this shows a nicer error message until we figure out the cause. // https://github.com/facebook/react/issues/12449#issuecomment-386727431 - invariant( - nextUnitOfWork !== null, - "Failed to replay rendering after an error. This " + - "is likely caused by a bug in React. Please file an issue " + - "with a reproducing case to help us find it." - ); + (function() { + if (!(nextUnitOfWork !== null)) { + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); + } + })(); var sourceFiber = nextUnitOfWork; var returnFiber = sourceFiber.return; @@ -17181,7 +18004,7 @@ function renderRoot(root, isYieldy) { // which phase it fails in, but doesn't seem worth it. At least // for now. didFatal = true; - onUncaughtError(thrownValue); + onUncaughtError$1(thrownValue); } else { throwException( root, @@ -17242,11 +18065,13 @@ function renderRoot(root, isYieldy) { var didCompleteRoot = true; stopWorkLoopTimer(interruptedBy, didCompleteRoot); var rootWorkInProgress = root.current.alternate; - invariant( - rootWorkInProgress !== null, - "Finished root should have a work-in-progress. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(rootWorkInProgress !== null)) { + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); // `nextRoot` points to the in-progress root. A non-null value indicates // that we're in the middle of an async render. Set it to null to indicate @@ -17295,32 +18120,23 @@ function renderRoot(root, isYieldy) { } } - if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) { + // Check if we should suspend this commit. + // If mostRecentEventTime is Sync, that means we didn't track any event + // times. That can happen if we retried but nothing switched from fallback + // to content. There's no reason to delay doing no work. + if (isYieldy && nextRenderDidSuspend && mostRecentEventTime !== Sync) { // The tree was suspended. var _suspendedExpirationTime2 = expirationTime; markSuspendedPriorityLevel(root, _suspendedExpirationTime2); - // Find the earliest uncommitted expiration time in the tree, including - // work that is suspended. The timeout threshold cannot be longer than - // the overall expiration. - var earliestExpirationTime = findEarliestOutstandingPriorityLevel( - root, - expirationTime - ); - var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime); - if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) { - nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs; - } - - // Subtract the current time from the absolute timeout to get the number - // of milliseconds until the timeout. In other words, convert an absolute - // timestamp to a relative time. This is the value that is passed - // to `setTimeout`. - var currentTimeMs = expirationTimeToMs(requestCurrentTime()); - var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs; - msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout; + var eventTimeMs = inferTimeFromExpirationTime(mostRecentEventTime); + var currentTimeMs = now$1(); + var timeElapsed = currentTimeMs - eventTimeMs; // TODO: Account for the Just Noticeable Difference + var timeoutMs = 150; + var msUntilTimeout = timeoutMs - timeElapsed; + msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout; var _rootExpirationTime2 = root.expirationTime; onSuspend( @@ -17337,7 +18153,7 @@ function renderRoot(root, isYieldy) { onComplete(root, rootWorkInProgress, expirationTime); } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { var expirationTime = Sync; var fiber = sourceFiber.return; while (fiber !== null) { @@ -17348,12 +18164,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && - !isAlreadyFailedLegacyErrorBoundary(instance)) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { var errorInfo = createCapturedValue(value, sourceFiber); var update = createClassErrorUpdate(fiber, errorInfo, expirationTime); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$1(fiber, expirationTime); return; } break; @@ -17361,7 +18177,7 @@ function captureCommitPhaseError(sourceFiber, value) { var _errorInfo = createCapturedValue(value, sourceFiber); var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime); enqueueUpdate(fiber, _update); - scheduleWork(fiber, expirationTime); + scheduleWork$1(fiber, expirationTime); return; } } @@ -17379,7 +18195,7 @@ function captureCommitPhaseError(sourceFiber, value) { expirationTime ); enqueueUpdate(rootFiber, _update2); - scheduleWork(rootFiber, expirationTime); + scheduleWork$1(rootFiber, expirationTime); } } @@ -17388,77 +18204,80 @@ function computeThreadID(expirationTime, interactionThreadID) { return expirationTime * 1000 + interactionThreadID; } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(); - +function computeExpirationForFiber$1(currentTime, fiber) { var expirationTime = void 0; - if ((fiber.mode & ConcurrentMode) === NoContext) { - // Outside of concurrent mode, updates are always synchronous. - expirationTime = Sync; - } else if (isWorking && !isCommitting$1) { - // During render phase, updates expire during as the current render. - expirationTime = nextRenderExpirationTime; + if (expirationContext !== NoWork) { + // An explicit expiration context was set; + expirationTime = expirationContext; + } else if (isWorking) { + if (isCommitting$1) { + // Updates that occur during the commit phase should have sync priority + // by default. + expirationTime = Sync; + } else { + // Updates during the render phase should expire at the same time as + // the work that is being rendered. + expirationTime = nextRenderExpirationTime; + } } else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = Sync; - break; - case scheduler.unstable_UserBlockingPriority: + // No explicit expiration context was set, and we're not currently + // performing work. Calculate a new expiration time. + if (fiber.mode & ConcurrentMode) { + if (isBatchingInteractiveUpdates) { + // This is an interactive update expirationTime = computeInteractiveExpiration(currentTime); - break; - case scheduler.unstable_NormalPriority: - // This is a normal, concurrent update + } else { + // This is an async update expirationTime = computeAsyncExpiration(currentTime); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = Never; - break; - default: - invariant( - false, - "Unknown priority level. This error is likely caused by a bug in " + - "React. Please file an issue." - ); - } - - // If we're in the middle of rendering a tree, do not update at the same - // expiration time that is already rendering. - if (nextRoot !== null && expirationTime === nextRenderExpirationTime) { - expirationTime -= 1; + } + // If we're in the middle of rendering a tree, do not update at the same + // expiration time that is already rendering. + if (nextRoot !== null && expirationTime === nextRenderExpirationTime) { + expirationTime -= 1; + } + } else { + // This is a sync update + expirationTime = Sync; } } - - // Keep track of the lowest pending interactive expiration time. This - // allows us to synchronously flush all interactive updates - // when needed. - // TODO: Move this to renderer? - if ( - priorityLevel === scheduler.unstable_UserBlockingPriority && - (lowestPriorityPendingInteractiveExpirationTime === NoWork || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) - ) { - lowestPriorityPendingInteractiveExpirationTime = expirationTime; + if (isBatchingInteractiveUpdates) { + // This is an interactive update. Keep track of the lowest pending + // interactive expiration time. This allows us to synchronously flush + // all interactive updates when needed. + if ( + lowestPriorityPendingInteractiveExpirationTime === NoWork || + expirationTime < lowestPriorityPendingInteractiveExpirationTime + ) { + lowestPriorityPendingInteractiveExpirationTime = expirationTime; + } } - return expirationTime; } -function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) { - // Schedule the timeout. - if ( - absoluteTimeoutMs >= 0 && - nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs - ) { - nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs; +function markRenderEventTime$1(expirationTime) { + if (expirationTime < mostRecentEventTime) { + mostRecentEventTime = expirationTime; } } -function renderDidError() { +function renderDidSuspend$1() { + nextRenderDidSuspend = true; +} + +function renderDidError$1() { nextRenderDidError = true; } -function pingSuspendedRoot(root, thenable, pingTime) { +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 + originalStartTimeMs + ); +} + +function pingSuspendedRoot$1(root, thenable, pingTime) { // A promise that previously suspended React from committing has resolved. // If React is still suspended, try again at the previous level (pingTime). @@ -17486,9 +18305,9 @@ function pingSuspendedRoot(root, thenable, pingTime) { } } -function retryTimedOutBoundary(boundaryFiber) { - var currentTime = requestCurrentTime(); - var retryTime = computeExpirationForFiber(currentTime, boundaryFiber); +function retryTimedOutBoundary$1(boundaryFiber) { + var currentTime = requestCurrentTime$1(); + var retryTime = computeExpirationForFiber$1(currentTime, boundaryFiber); var root = scheduleWorkToRoot(boundaryFiber, retryTime); if (root !== null) { markPendingPriorityLevel(root, retryTime); @@ -17499,7 +18318,7 @@ function retryTimedOutBoundary(boundaryFiber) { } } -function resolveRetryThenable(boundaryFiber, thenable) { +function resolveRetryThenable$1(boundaryFiber, thenable) { // The boundary fiber (a Suspense component) previously timed out and 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 @@ -17513,11 +18332,13 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache = boundaryFiber.memoizedState; break; default: - invariant( - false, - "Pinged unknown suspense boundary type. " + - "This is probably a bug in React." - ); + (function() { + { + throw ReactError( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } + })(); } } else { retryCache = boundaryFiber.stateNode; @@ -17528,7 +18349,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); + retryTimedOutBoundary$1(boundaryFiber); } function scheduleWorkToRoot(fiber, expirationTime) { @@ -17617,9 +18438,20 @@ function scheduleWorkToRoot(fiber, expirationTime) { return root; } -function warnIfNotCurrentlyBatchingInDev(fiber) { +// in a test-like environment, we want to warn if dispatchAction() is +// called outside of a TestUtils.act(...)/batchedUpdates/render call. +// so we have a a step counter for when we descend/ascend from +// act() calls, and test on it for when to warn +// It's a tuple with a single value. Look for shared/createAct to +// see how we change the value inside act() calls + +function warnIfNotCurrentlyActingUpdatesInDev$1(fiber) { { - if (isRendering === false && isBatchingUpdates === false) { + if ( + isBatchingUpdates === false && + isRendering === false && + ReactShouldWarnActingUpdates.current === false + ) { warningWithoutStack$1( false, "An update to %s inside a test was not wrapped in act(...).\n\n" + @@ -17638,7 +18470,7 @@ function warnIfNotCurrentlyBatchingInDev(fiber) { } } -function scheduleWork(fiber, expirationTime) { +function scheduleWork$1(fiber, expirationTime) { var root = scheduleWorkToRoot(fiber, expirationTime); if (root === null) { { @@ -17681,13 +18513,28 @@ function scheduleWork(fiber, expirationTime) { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { // Reset this back to zero so subsequent updates don't throw. nestedUpdateCount = 0; - invariant( - false, - "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." - ); + (function() { + { + throw ReactError( + "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." + ); + } + })(); + } + { + if ( + isInPassiveEffectDEV && + nestedPassiveEffectCountDEV > NESTED_PASSIVE_UPDATE_LIMIT + ) { + nestedPassiveEffectCountDEV = 0; + warning$1( + false, + "Maximum update depth exceeded. This can happen when a " + + "component calls setState inside useEffect, but " + + "useEffect either doesn't have a dependency array, or " + + "one of the dependencies changes on every render." + ); + } } } @@ -17709,10 +18556,11 @@ var unhandledError = null; var isBatchingUpdates = false; var isUnbatchingUpdates = false; +var isBatchingInteractiveUpdates = false; var completedBatches = null; -var originalStartTimeMs = now$$1(); +var originalStartTimeMs = now$1(); var currentRendererTime = msToExpirationTime(originalStartTimeMs); var currentSchedulerTime = currentRendererTime; @@ -17721,8 +18569,17 @@ var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var lastCommittedRootDuringThisBatch = null; +// Similar, but for useEffect infinite loops. These are DEV-only. +var NESTED_PASSIVE_UPDATE_LIMIT = 50; +var nestedPassiveEffectCountDEV = void 0; +var isInPassiveEffectDEV = void 0; +{ + nestedPassiveEffectCountDEV = 0; + isInPassiveEffectDEV = false; +} + function recomputeCurrentRendererTime() { - var currentTimeMs = now$$1() - originalStartTimeMs; + var currentTimeMs = now$1() - originalStartTimeMs; currentRendererTime = msToExpirationTime(currentTimeMs); } @@ -17736,7 +18593,7 @@ function scheduleCallbackWithExpirationTime(root, expirationTime) { if (callbackID !== null) { // Existing callback has insufficient timeout. Cancel and schedule a // new one. - cancelDeferredCallback$$1(callbackID); + cancelCallback$1(callbackID); } } // The request callback timer is already running. Don't start a new one. @@ -17745,10 +18602,11 @@ function scheduleCallbackWithExpirationTime(root, expirationTime) { } callbackExpirationTime = expirationTime; - var currentMs = now$$1() - originalStartTimeMs; + var currentMs = now$1() - originalStartTimeMs; var expirationTimeMs = expirationTimeToMs(expirationTime); var timeout = expirationTimeMs - currentMs; - callbackID = scheduleDeferredCallback$$1(performAsyncWork, { + var priorityLevel = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(priorityLevel, performAsyncWork, { timeout: timeout }); } @@ -17774,7 +18632,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - if (msUntilTimeout === 0 && !shouldYield$$1()) { + if (msUntilTimeout === 0 && (disableYielding || !shouldYield$1())) { // Don't wait an additional tick. Commit the tree immediately. root.pendingCommitExpirationTime = suspendedExpirationTime; root.finishedWork = finishedWork; @@ -17800,7 +18658,7 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { // because we're at the top of a timer event. recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - flushRoot(root, suspendedExpirationTime); + flushRoot$1(root, suspendedExpirationTime); } function onCommit(root, expirationTime) { @@ -17808,7 +18666,7 @@ function onCommit(root, expirationTime) { root.finishedWork = null; } -function requestCurrentTime() { +function requestCurrentTime$1() { // requestCurrentTime is called by the scheduler to compute an expiration // time. // @@ -17920,11 +18778,13 @@ function findHighestPriorityRoot() { // TODO: This check is redudant, but Flow is confused by the branch // below where we set lastScheduledRoot to null, even though we break // from the loop right after. - invariant( - previousScheduledRoot !== null && lastScheduledRoot !== null, - "Should have a previous and last root. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(previousScheduledRoot !== null && lastScheduledRoot !== null)) { + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); if (root === root.nextScheduledRoot) { // This is the only root in the list. root.nextScheduledRoot = null; @@ -17988,19 +18848,18 @@ function performAsyncWork(didTimeout) { } while (root !== firstScheduledRoot); } } - performWork(NoWork, true); -} -function performSyncWork() { - performWork(Sync, false); -} - -function performWork(minExpirationTime, isYieldy) { // Keep working on roots until there's no more work, or until there's a higher // priority event. findHighestPriorityRoot(); - if (isYieldy) { + if (disableYielding) { + // Just do it all + while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork) { + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); + findHighestPriorityRoot(); + } + } else { recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; @@ -18013,8 +18872,7 @@ function performWork(minExpirationTime, isYieldy) { while ( nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && - minExpirationTime <= nextFlushedExpirationTime && - !(shouldYield$$1() && currentRendererTime > nextFlushedExpirationTime) + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime) ) { performWorkOnRoot( nextFlushedRoot, @@ -18025,25 +18883,15 @@ function performWork(minExpirationTime, isYieldy) { recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; } - } else { - while ( - nextFlushedRoot !== null && - nextFlushedExpirationTime !== NoWork && - minExpirationTime <= nextFlushedExpirationTime - ) { - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); - findHighestPriorityRoot(); - } } // We're done flushing work. Either we ran out of time in this callback, // or there's no more work left with sufficient priority. // If we're inside a callback, set this to false since we just completed it. - if (isYieldy) { - callbackExpirationTime = NoWork; - callbackID = null; - } + callbackExpirationTime = NoWork; + callbackID = null; + // If there's work left over, schedule a new callback. if (nextFlushedExpirationTime !== NoWork) { scheduleCallbackWithExpirationTime( @@ -18056,12 +18904,47 @@ function performWork(minExpirationTime, isYieldy) { finishRendering(); } -function flushRoot(root, expirationTime) { - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely " + - "means you attempted to commit from inside a lifecycle method." - ); +function performSyncWork() { + performWork(Sync); +} + +function performWork(minExpirationTime) { + // Keep working on roots until there's no more work, or until there's a higher + // priority event. + findHighestPriorityRoot(); + + while ( + nextFlushedRoot !== null && + nextFlushedExpirationTime !== NoWork && + minExpirationTime <= nextFlushedExpirationTime + ) { + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); + findHighestPriorityRoot(); + } + + // We're done flushing work. Either we ran out of time in this callback, + // or there's no more work left with sufficient priority. + + // If there's work left over, schedule a new callback. + if (nextFlushedExpirationTime !== NoWork) { + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + } + + // Clean-up. + finishRendering(); +} + +function flushRoot$1(root, expirationTime) { + (function() { + if (!!isRendering) { + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); + } + })(); // Perform work on root as if the given expiration time is the current time. // This has the effect of synchronously flushing all work up to and // including the given time. @@ -18076,6 +18959,12 @@ function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; + { + if (rootWithPendingPassiveEffects === null) { + nestedPassiveEffectCountDEV = 0; + } + } + if (completedBatches !== null) { var batches = completedBatches; completedBatches = null; @@ -18101,11 +18990,13 @@ function finishRendering() { } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused " + - "by a bug in React. Please file an issue." - ); + (function() { + if (!!isRendering) { + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); isRendering = true; @@ -18158,7 +19049,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { if (_finishedWork !== null) { // We've completed the root. Check the if we should yield one more time // before committing. - if (!shouldYield$$1()) { + if (!shouldYield$1()) { // Still time left. Commit the root. completeRoot$1(root, _finishedWork, expirationTime); } else { @@ -18205,20 +19096,17 @@ function completeRoot$1(root, finishedWork, expirationTime) { lastCommittedRootDuringThisBatch = root; nestedUpdateCount = 0; } - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); - } - ); + commitRoot(root, finishedWork); } -function onUncaughtError(error) { - invariant( - nextFlushedRoot !== null, - "Should be working on a root. This error is likely caused by a bug in " + - "React. Please file an issue." - ); +function onUncaughtError$1(error) { + (function() { + if (!(nextFlushedRoot !== null)) { + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); // Unschedule this root so we don't work on it again until there's // another update. nextFlushedRoot.expirationTime = NoWork; @@ -18230,7 +19118,7 @@ function onUncaughtError(error) { // TODO: Batching should be implemented at the renderer level, not inside // the reconciler. -function batchedUpdates$1(fn, a) { +function batchedUpdates$2(fn, a) { var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { @@ -18243,7 +19131,10 @@ function batchedUpdates$1(fn, a) { } } -function interactiveUpdates$1(fn, a, b) { +function interactiveUpdates$2(fn, a, b, c) { + if (isBatchingInteractiveUpdates) { + return fn(a, b, c); + } // If there are any pending interactive updates, synchronously flush them. // This needs to happen before we read any handlers, because the effect of // the previous event may influence which handlers are called during @@ -18254,19 +19145,17 @@ function interactiveUpdates$1(fn, a, b) { lowestPriorityPendingInteractiveExpirationTime !== NoWork ) { // Synchronously flush pending interactive updates. - performWork(lowestPriorityPendingInteractiveExpirationTime, false); + performWork(lowestPriorityPendingInteractiveExpirationTime); lowestPriorityPendingInteractiveExpirationTime = NoWork; } + var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates; var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingInteractiveUpdates = true; isBatchingUpdates = true; try { - return scheduler.unstable_runWithPriority( - scheduler.unstable_UserBlockingPriority, - function() { - return fn(a, b); - } - ); + return fn(a, b, c); } finally { + isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates; isBatchingUpdates = previousIsBatchingUpdates; if (!isBatchingUpdates && !isRendering) { performSyncWork(); @@ -18274,17 +19163,1985 @@ function interactiveUpdates$1(fn, a, b) { } } -function flushInteractiveUpdates$1() { +function flushInteractiveUpdates$2() { if ( !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork ) { // Synchronously flush pending interactive updates. - performWork(lowestPriorityPendingInteractiveExpirationTime, false); + performWork(lowestPriorityPendingInteractiveExpirationTime); lowestPriorityPendingInteractiveExpirationTime = NoWork; } } +// TODO: Ahaha Andrew is bad at spellling +// DEV stuff +var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentOwner$4 = ReactSharedInternals.ReactCurrentOwner; +var ReactShouldWarnActingUpdates$1 = + ReactSharedInternals.ReactShouldWarnActingUpdates; + +var NotWorking = 0; +var BatchedPhase = 1; +var LegacyUnbatchedPhase = 2; +var RenderPhase = 4; +var CommitPhase = 5; + +var RootIncomplete = 0; +var RootErrored = 1; +var RootSuspended = 2; +var RootCompleted = 3; + +// The phase of work we're currently in +var workPhase = NotWorking; +// 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$1 = NoWork; +// Whether to root completed, errored, suspended, etc. +var workInProgressRootExitStatus = RootIncomplete; +// 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 workInProgressRootMostRecentEventTime = Sync; + +var nextEffect$1 = null; +var hasUncaughtError = false; +var firstUncaughtError = null; +var legacyErrorBoundariesThatAlreadyFailed$1 = null; + +var rootDoesHavePassiveEffects = false; +var rootWithPendingPassiveEffects$1 = null; +var pendingPassiveEffectsExpirationTime = NoWork; + +var rootsWithPendingDiscreteUpdates = null; + +// Use these to prevent an infinite loop of nested updates +var NESTED_UPDATE_LIMIT$1 = 50; +var nestedUpdateCount$1 = 0; +var rootWithNestedUpdates = null; + +var NESTED_PASSIVE_UPDATE_LIMIT$1 = 50; +var nestedPassiveUpdateCount = 0; + +var interruptedBy$1 = 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 initialTimeMs = now(); +var currentEventTime = NoWork; + +function requestCurrentTime$2() { + if (workPhase === RenderPhase || workPhase === CommitPhase) { + // We're inside React, so it's fine to read the actual time. + return msToExpirationTime(now() - initialTimeMs); + } + // 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. + currentEventTime = msToExpirationTime(now() - initialTimeMs); + return currentEventTime; +} + +function computeExpirationForFiber$2(currentTime, fiber) { + if ((fiber.mode & ConcurrentMode) === NoContext) { + return Sync; + } + + if (workPhase === RenderPhase) { + // Use whatever time we're already rendering + return renderExpirationTime$1; + } + + // Compute an expiration time based on the Scheduler priority. + var expirationTime = void 0; + var priorityLevel = getCurrentPriorityLevel(); + switch (priorityLevel) { + 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; + break; + default: + (function() { + { + throw ReactError("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. + if ( + workInProgressRoot !== null && + expirationTime === renderExpirationTime$1 + ) { + // This is a trick to move this update into a separate batch + expirationTime -= 1; + } + + 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(); + + if (expirationTime === Sync) { + if (workPhase === LegacyUnbatchedPhase) { + // 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$1(root, Sync, true); + while (callback !== null) { + callback = callback(true); + } + } else { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + if (workPhase === NotWorking) { + // Flush the synchronous work now, wnless 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-initated + // updates, to preserve historical behavior of sync mode. + flushImmediateQueue(); + } + } + } else { + // TODO: computeExpirationForFiber also reads the priority. Pass the + // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); + if (priorityLevel === UserBlockingPriority) { + // This is the result of a discrete event. Track the lowest priority + // discrete update per root so we can flush them early, if needed. + if (rootsWithPendingDiscreteUpdates === null) { + rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); + } else { + var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if ( + lastDiscreteTime === undefined || + lastDiscreteTime > expirationTime + ) { + rootsWithPendingDiscreteUpdates.set(root, expirationTime); + } + } + } + scheduleCallbackForRoot(root, priorityLevel, expirationTime); + } +} +var scheduleWork$2 = 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. + 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 + ) { + alternate.childExpirationTime = expirationTime; + } + } else if ( + alternate !== null && + alternate.childExpirationTime < 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; + } + } + + 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; + var options = + expirationTime === Sync + ? null + : { timeout: expirationTimeToMs(expirationTime) }; + root.callbackNode = scheduleCallback( + priorityLevel, + runRootCallback.bind( + null, + root, + renderRoot$1.bind(null, root, expirationTime) + ), + options + ); + if ( + enableUserTimingAPI && + expirationTime !== Sync && + workPhase !== RenderPhase && + workPhase !== CommitPhase + ) { + // 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(); + } + } + + 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); + } + + // Add the current set of interactions to the pending set associated with + // this root. + schedulePendingInteraction(root, expirationTime); +} + +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) { + root.callbackNode = null; + root.callbackExpirationTime = NoWork; + } + } +} + +function flushInteractiveUpdates$3() { + if (workPhase === RenderPhase || workPhase === CommitPhase) { + // Can't synchronously flush interactive updates if React is already + // working. This is currently a no-op. + // TODO: Should we fire a warning? This happens if you synchronously invoke + // an input event inside an effect, like with `element.click()`. + return; + } + flushPendingDiscreteUpdates(); +} + +function resolveLocksOnRoot(root, expirationTime) { + var firstBatch = root.firstBatch; + if ( + firstBatch !== null && + firstBatch._defer && + firstBatch._expirationTime >= expirationTime + ) { + root.finishedWork = root.current.alternate; + root.pendingCommitExpirationTime = expirationTime; + scheduleCallback(NormalPriority, function() { + firstBatch._onComplete(); + return null; + }); + return true; + } else { + return false; + } +} + +function interactiveUpdates$3(fn, a, b, c) { + if (workPhase === NotWorking) { + // TODO: Remove this call. Instead of doing this automatically, the caller + // should explicitly call flushInteractiveUpdates. + flushPendingDiscreteUpdates(); + } + return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); +} + +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) { + scheduleCallback( + ImmediatePriority, + renderRoot$1.bind(null, root, expirationTime) + ); + }); + // Now flush the immediate queue. + flushImmediateQueue(); + } +} + +function batchedUpdates$3(fn, a) { + if (workPhase !== NotWorking) { + // We're already working, or inside a batch, so batchedUpdates is a no-op. + return fn(a); + } + workPhase = BatchedPhase; + try { + return fn(a); + } finally { + workPhase = NotWorking; + // Flush the immediate callbacks that were scheduled during this batch + flushImmediateQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.pendingCommitExpirationTime = 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$1 = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootMostRecentEventTime = Sync; + + { + ReactStrictModeWarnings.discardPendingWarnings(); + } +} + +function renderRoot$1(root, expirationTime, isSync) { + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Should not already be working."); + } + })(); + + if (enableUserTimingAPI && expirationTime !== Sync) { + var didExpire = isSync; + var timeoutMs = expirationTimeToMs(expirationTime); + stopRequestCallbackTimer(didExpire, timeoutMs); + } + + 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.pendingCommitExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + root.pendingCommitExpirationTime = NoWork; + return commitRoot$1.bind(null, root, expirationTime); + } + + flushPassiveEffects$2(); + + // 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$1 + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteraction(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 prevWorkPhase = workPhase; + workPhase = RenderPhase; + var prevDispatcher = ReactCurrentDispatcher$2.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$2.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$2(); + if (currentTime < expirationTime) { + // Restart at the current time. + workPhase = prevWorkPhase; + resetContextDependences(); + ReactCurrentDispatcher$2.current = prevDispatcher; + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + return renderRoot$1.bind(null, root, currentTime); + } + } + } 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$1(); + } + break; + } catch (thrownValue) { + // Reset module-level state that was set during the render phase. + resetContextDependences(); + 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); + workPhase = prevWorkPhase; + 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( + root, + returnFiber, + sourceFiber, + thrownValue, + renderExpirationTime$1 + ); + workInProgress = completeUnitOfWork$1(sourceFiber); + } + } while (true); + + workPhase = prevWorkPhase; + resetContextDependences(); + ReactCurrentDispatcher$2.current = prevDispatcher; + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + + if (workInProgress !== null) { + // There's still work left over. Return a continuation. + stopInterruptedWorkLoopTimer(); + if (expirationTime !== Sync) { + startRequestCallbackTimer(); + } + return renderRoot$1.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(); + + 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; + } + + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + switch (workInProgressRootExitStatus) { + case RootIncomplete: { + (function() { + { + throw ReactError("Should have a work-in-progress."); + } + })(); + } + // Flow knows about invariant, so it compains 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 (root.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$1.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); + scheduleCallback( + ImmediatePriority, + renderRoot$1.bind(null, root, expirationTime) + ); + return null; + } + // If we're already rendering synchronously, commit the root in its + // errored state. + return commitRoot$1.bind(null, root, expirationTime); + } + case RootSuspended: { + if (!isSync) { + var _lastPendingTime = root.lastPendingTime; + if (root.lastPendingTime < expirationTime) { + // There's lower priority work. It might be unsuspended. Try rendering + // at that level. + return renderRoot$1.bind(null, root, _lastPendingTime); + } + // If workInProgressRootMostRecentEventTime is Sync, that means we didn't + // track any event times. That can happen if we retried but nothing switched + // from fallback to content. There's no reason to delay doing no work. + if (workInProgressRootMostRecentEventTime !== Sync) { + var msUntilTimeout = computeMsUntilTimeout( + workInProgressRootMostRecentEventTime + ); + if (msUntilTimeout > 0) { + // 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$1.bind(null, root, expirationTime), + msUntilTimeout + ); + return null; + } + } + } + // The work expired. Commit immediately. + return commitRoot$1.bind(null, root, expirationTime); + } + case RootCompleted: { + // The work completed. Ready to commit. + return commitRoot$1.bind(null, root, expirationTime); + } + default: { + (function() { + { + throw ReactError("Unknown root exit status."); + } + })(); + } + } +} + +function markRenderEventTime$2(expirationTime) { + if (expirationTime < workInProgressRootMostRecentEventTime) { + workInProgressRootMostRecentEventTime = expirationTime; + } +} + +function renderDidSuspend$2() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} + +function renderDidError$2() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootErrored; + } +} + +function inferTimeFromExpirationTime$1(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 + initialTimeMs; +} + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + workInProgress = performUnitOfWork$1(workInProgress); + } +} + +function workLoop$1() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + workInProgress = performUnitOfWork$1(workInProgress); + } +} + +function performUnitOfWork$1(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 = void 0; + if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1); + } + + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { + // If this doesn't spawn new work, complete the current work. + next = completeUnitOfWork$1(unitOfWork); + } + + ReactCurrentOwner$4.current = null; + return next; +} + +function completeUnitOfWork$1(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; + + // 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) === NoContext + ) { + next = completeWork(current$$1, workInProgress, renderExpirationTime$1); + } else { + startProfilerTimer(workInProgress); + next = completeWork(current$$1, workInProgress, renderExpirationTime$1); + // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + } + stopWorkTimer(workInProgress); + resetCurrentFiber(); + resetChildExpirationTime$1(workInProgress); + + if (next !== null) { + // Completing this fiber spawned new work. Work on that next. + return next; + } + + if ( + 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 + // list of the parent. The completion order of the children affects the + // side-effect order. + 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 + // 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 + // 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; + } + } + } else { + // 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$1); + + // Because this fiber did not complete, don't reset its expiration time. + + if ( + enableProfilerTimer && + (workInProgress.mode & ProfileMode) !== NoContext + ) { + // Record the render duration for the fiber that errored. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + + // 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; + } + + if (_next !== null) { + // If completing this work spawned new work, do that next. We'll come + // back here again. + // Since we're restarting, remove anything that is not a host effect + // from the effect tag. + // TODO: The name stopFailedWorkTimer is misleading because Suspense + // also captures and restarts. + stopFailedWorkTimer(workInProgress); + _next.effectTag &= HostEffectMask; + return _next; + } + stopWorkTimer(workInProgress); + + if (returnFiber !== null) { + // Mark the parent fiber as incomplete and clear its effect list. + returnFiber.firstEffect = returnFiber.lastEffect = null; + returnFiber.effectTag |= Incomplete; + } + } + + 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 + workInProgress = returnFiber; + } while (workInProgress !== null); + + // We've reached the root. + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootCompleted; + } + return null; +} + +function resetChildExpirationTime$1(completedWork) { + if ( + renderExpirationTime$1 !== Never && + completedWork.childExpirationTime === Never + ) { + // The children of this component are hidden. Don't bubble their + // expiration times. + return; + } + + var newChildExpirationTime = NoWork; + + // Bubble up the earliest expiration time. + if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) { + // 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 + // 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; + } + } + + completedWork.childExpirationTime = newChildExpirationTime; +} + +function commitRoot$1(root, expirationTime) { + runWithPriority( + ImmediatePriority, + commitRootImpl.bind(null, root, expirationTime) + ); + // 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$1 !== null) { + var priorityLevel = getCurrentPriorityLevel(); + scheduleCallback(priorityLevel, function() { + flushPassiveEffects$2(); + return null; + }); + } + return null; +} + +function commitRootImpl(root, expirationTime) { + flushPassiveEffects$2(); + flushRenderPhaseStrictModeWarningsInDEV(); + + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Should not already be working."); + } + })(); + var finishedWork = root.current.alternate; + (function() { + if (!(finishedWork !== null)) { + throw ReactError("Should have a work-in-progress root."); + } + })(); + + // 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 + // 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; + } + + if (root === workInProgressRoot) { + // We can reset these now that they are finished. + workInProgressRoot = null; + workInProgress = null; + renderExpirationTime$1 = NoWork; + } else { + } + // 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; + 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 + // resulting list is the set that would belong to the root's parent, if it + // had one; that is, all the effects in the tree including the root. + if (finishedWork.lastEffect !== null) { + finishedWork.lastEffect.nextEffect = finishedWork; + firstEffect = finishedWork.firstEffect; + } else { + firstEffect = finishedWork; + } + } else { + // There is no effect on the root. + firstEffect = finishedWork.firstEffect; + } + + if (firstEffect !== null) { + var prevWorkPhase = workPhase; + workPhase = CommitPhase; + var prevInteractions = null; + if (enableSchedulerTracing) { + prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + } + + // Reset this to null before calling lifecycles + ReactCurrentOwner$4.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$1 = firstEffect; + do { + { + invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var error = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, error); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== 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. + startCommitHostEffectsTimer(); + nextEffect$1 = firstEffect; + do { + { + invokeGuardedCallback(null, commitMutationEffects, null); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var _error = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, _error); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== null); + 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 + // 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$1 = firstEffect; + do { + { + invokeGuardedCallback( + null, + commitLayoutEffects, + null, + root, + expirationTime + ); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var _error2 = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, _error2); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== null); + stopCommitLifeCyclesTimer(); + + nextEffect$1 = null; + + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + workPhase = prevWorkPhase; + } else { + // No effects. + 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(); + stopCommitLifeCyclesTimer(); + } + + stopCommitTimer(); + + if (rootDoesHavePassiveEffects) { + // This commit has passive effects. Stash a reference to them. But don't + // schedule a callback until after flushing layout work. + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects$1 = root; + pendingPassiveEffectsExpirationTime = expirationTime; + } else { + if (enableSchedulerTracing) { + // If there are no passive effects, then we can complete the pending + // interactions. Otherwise, we'll wait until after the passive effects + // are flushed. + finishPendingInteractions(root, expirationTime); + } + } + + // Check if there's remaining work on this root + var remainingExpirationTime = root.firstPendingTime; + if (remainingExpirationTime !== NoWork) { + var currentTime = requestCurrentTime$2(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + remainingExpirationTime + ); + scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + } else { + // If there's no remaining work, we can clear the set of already failed + // error boundaries. + legacyErrorBoundariesThatAlreadyFailed$1 = null; + } + + onCommitRoot(finishedWork.stateNode); + + 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. + if (root === rootWithNestedUpdates) { + nestedUpdateCount$1++; + } else { + nestedUpdateCount$1 = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount$1 = 0; + } + + if (hasUncaughtError) { + hasUncaughtError = false; + var _error3 = firstUncaughtError; + firstUncaughtError = null; + throw _error3; + } + + if (workPhase === LegacyUnbatchedPhase) { + // This is a legacy edge case. We just committed the initial mount of + // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired + // synchronously, but layout updates should be deferred until the end + // of the batch. + return null; + } + + // If layout work was scheduled, flush it now. + flushImmediateQueue(); + return null; +} + +function commitBeforeMutationEffects() { + while (nextEffect$1 !== null) { + if ((nextEffect$1.effectTag & Snapshot) !== NoEffect) { + setCurrentFiber(nextEffect$1); + recordEffect(); + + var current$$1 = nextEffect$1.alternate; + commitBeforeMutationLifeCycles(current$$1, nextEffect$1); + + resetCurrentFiber(); + } + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function commitMutationEffects() { + // TODO: Should probably move the bulk of this function to commitWork. + while (nextEffect$1 !== null) { + setCurrentFiber(nextEffect$1); + + var effectTag = nextEffect$1.effectTag; + + if (effectTag & ContentReset) { + commitResetTextContent(nextEffect$1); + } + + if (effectTag & Ref) { + var current$$1 = nextEffect$1.alternate; + if (current$$1 !== null) { + commitDetachRef(current$$1); + } + } + + // 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); + switch (primaryEffectTag) { + case Placement: { + commitPlacement(nextEffect$1); + // 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$1.effectTag &= ~Placement; + break; + } + case PlacementAndUpdate: { + // Placement + commitPlacement(nextEffect$1); + // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. + nextEffect$1.effectTag &= ~Placement; + + // Update + var _current = nextEffect$1.alternate; + commitWork(_current, nextEffect$1); + break; + } + case Update: { + var _current2 = nextEffect$1.alternate; + commitWork(_current2, nextEffect$1); + break; + } + case Deletion: { + commitDeletion(nextEffect$1); + break; + } + } + + // TODO: Only record a mutation effect if primaryEffectTag is non-zero. + recordEffect(); + + resetCurrentFiber(); + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function commitLayoutEffects(root, committedExpirationTime) { + // TODO: Should probably move the bulk of this function to commitWork. + while (nextEffect$1 !== null) { + setCurrentFiber(nextEffect$1); + + var effectTag = nextEffect$1.effectTag; + + if (effectTag & (Update | Callback)) { + recordEffect(); + var current$$1 = nextEffect$1.alternate; + commitLifeCycles(root, current$$1, nextEffect$1, committedExpirationTime); + } + + if (effectTag & Ref) { + recordEffect(); + commitAttachRef(nextEffect$1); + } + + if (effectTag & Passive) { + rootDoesHavePassiveEffects = true; + } + + resetCurrentFiber(); + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function flushPassiveEffects$2() { + if (rootWithPendingPassiveEffects$1 === null) { + return false; + } + var root = rootWithPendingPassiveEffects$1; + var expirationTime = pendingPassiveEffectsExpirationTime; + rootWithPendingPassiveEffects$1 = null; + pendingPassiveEffectsExpirationTime = NoWork; + + var prevInteractions = null; + if (enableSchedulerTracing) { + prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + } + + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Cannot flush passive effects while already rendering."); + } + })(); + var prevWorkPhase = workPhase; + workPhase = CommitPhase; + + // 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("Should be working on an effect."); + } + })(); + var error = clearCaughtError(); + captureCommitPhaseError$2(effect, error); + } + resetCurrentFiber(); + } + effect = effect.nextEffect; + } + + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + finishPendingInteractions(root, expirationTime); + } + + workPhase = prevWorkPhase; + flushImmediateQueue(); + + // If additional passive effects were scheduled, increment a counter. If this + // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = + rootWithPendingPassiveEffects$1 === null ? 0 : nestedPassiveUpdateCount + 1; + + return true; +} + +function isAlreadyFailedLegacyErrorBoundary$2(instance) { + return ( + legacyErrorBoundariesThatAlreadyFailed$1 !== null && + legacyErrorBoundariesThatAlreadyFailed$1.has(instance) + ); +} + +function markLegacyErrorBoundaryAsFailed$2(instance) { + if (legacyErrorBoundariesThatAlreadyFailed$1 === null) { + legacyErrorBoundariesThatAlreadyFailed$1 = new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed$1.add(instance); + } +} + +function prepareToThrowUncaughtError(error) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error; + } +} +var onUncaughtError$2 = prepareToThrowUncaughtError; + +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); + enqueueUpdate(rootFiber, update); + var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + } +} + +function captureCommitPhaseError$2(sourceFiber, error) { + if (sourceFiber.tag === HostRoot) { + // Error was thrown at the root. There is no parent, so the root + // itself should capture it. + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + return; + } + + var fiber = sourceFiber.return; + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + if ( + typeof ctor.getDerivedStateFromError === "function" || + (typeof instance.componentDidCatch === "function" && + !isAlreadyFailedLegacyErrorBoundary$2(instance)) + ) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createClassErrorUpdate( + fiber, + errorInfo, + // TODO: This is always sync + Sync + ); + enqueueUpdate(fiber, update); + var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + } + return; + } + } + fiber = fiber.return; + } +} + +function pingSuspendedRoot$2(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. + pingCache.delete(thenable); + } + + if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) { + // Received a ping at the same priority level at which we're currently + // rendering. Restart from the root. Don't need to schedule a ping because + // we're already working on this tree. + prepareFreshStack(root, renderExpirationTime$1); + return; + } + + var lastPendingTime = root.lastPendingTime; + if (lastPendingTime < suspendedTime) { + // The root is no longer suspended at this time. + return; + } + + var pingTime = root.pingTime; + if (pingTime !== NoWork && pingTime < suspendedTime) { + // There's already a lower priority ping scheduled. + return; + } + + // Mark the time at which this ping was scheduled. + root.pingTime = suspendedTime; + + var currentTime = requestCurrentTime$2(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + suspendedTime + ); + scheduleCallbackForRoot(root, priorityLevel, suspendedTime); +} + +function retryTimedOutBoundary$2(boundaryFiber) { + // The boundary fiber (a Suspense component) previously timed out and 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$2(); + var retryTime = computeExpirationForFiber$2(currentTime, boundaryFiber); + // TODO: Special case idle priority? + var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { + scheduleCallbackForRoot(root, priorityLevel, retryTime); + } +} + +function resolveRetryThenable$2(boundaryFiber, thenable) { + var retryCache = void 0; + if (enableSuspenseServerRenderer) { + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + break; + case DehydratedSuspenseComponent: + retryCache = boundaryFiber.memoizedState; + break; + default: + (function() { + { + throw ReactError( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } + })(); + } + } else { + retryCache = boundaryFiber.stateNode; + } + + if (retryCache !== null) { + // The thenable resolved, so we no longer need to memoize, because it will + // never be thrown again. + retryCache.delete(thenable); + } + + retryTimedOutBoundary$2(boundaryFiber); +} + +function computeMsUntilTimeout(mostRecentEventTime) { + if (disableYielding) { + // Timeout immediately when yielding is disabled. + return 0; + } + + var eventTimeMs = inferTimeFromExpirationTime$1(mostRecentEventTime); + var currentTimeMs = now(); + var timeElapsed = currentTimeMs - eventTimeMs; + + // TODO: Account for the Just Noticeable Difference + var timeoutMs = 150; + var msUntilTimeout = timeoutMs - timeElapsed; + // This is the value that is passed to `setTimeout`. + return msUntilTimeout < 0 ? 0 : msUntilTimeout; +} + +function checkForNestedUpdates() { + if (nestedUpdateCount$1 > NESTED_UPDATE_LIMIT$1) { + nestedUpdateCount$1 = 0; + rootWithNestedUpdates = null; + (function() { + { + throw ReactError( + "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." + ); + } + })(); + } + + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT$1) { + nestedPassiveUpdateCount = 0; + warning$1( + false, + "Maximum update depth exceeded. This can happen when a component " + + "calls setState inside useEffect, but useEffect either doesn't " + + "have a dependency array, or one of the dependencies changes on " + + "every render." + ); + } + } +} + +function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + ReactStrictModeWarnings.flushLegacyContextWarning(); + + if (warnAboutDeprecatedLifecycles) { + ReactStrictModeWarnings.flushPendingDeprecationWarnings(); + } + } +} + +function stopFinishedWorkLoopTimer() { + var didCompleteRoot = true; + stopWorkLoopTimer(interruptedBy$1, didCompleteRoot); + interruptedBy$1 = null; +} + +function stopInterruptedWorkLoopTimer() { + // TODO: Track which fiber caused the interruption. + var didCompleteRoot = false; + stopWorkLoopTimer(interruptedBy$1, didCompleteRoot); + interruptedBy$1 = null; +} + +function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { + if ( + enableUserTimingAPI && + workInProgressRoot !== null && + updateExpirationTime > renderExpirationTime$1 + ) { + interruptedBy$1 = fiberThatReceivedUpdate; + } +} + +var didWarnStateUpdateForUnmountedComponent$1 = null; +function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { + { + var tag = fiber.tag; + if ( + tag !== HostRoot && + tag !== ClassComponent && + tag !== FunctionComponent && + tag !== ForwardRef && + tag !== MemoComponent && + tag !== SimpleMemoComponent + ) { + // 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 + // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent$1 !== null) { + if (didWarnStateUpdateForUnmountedComponent$1.has(componentName)) { + return; + } + didWarnStateUpdateForUnmountedComponent$1.add(componentName); + } else { + didWarnStateUpdateForUnmountedComponent$1 = new Set([componentName]); + } + warningWithoutStack$1( + false, + "Can't perform a React state update on an unmounted component. This " + + "is a no-op, but it indicates a memory leak in your application. To " + + "fix, cancel all subscriptions and asynchronous tasks in %s.%s", + tag === ClassComponent + ? "the componentWillUnmount method" + : "a useEffect cleanup function", + getStackByFiberInDevAndProd(fiber) + ); + } +} + +var beginWork$1 = void 0; +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(current$$1, unitOfWork, expirationTime); + } catch (originalError) { + if ( + originalError !== null && + typeof originalError === "object" && + typeof originalError.then === "function" + ) { + // Don't replay promises. Treat everything else like an error. + throw originalError; + } + + // Keep this code in sync with renderRoot; any changes here must have + // corresponding changes there. + resetContextDependences(); + resetHooks(); + + // Unwind the failed stack frame + 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. + invokeGuardedCallback( + null, + beginWork, + null, + current$$1, + unitOfWork, + expirationTime + ); + + if (hasCaughtError()) { + 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. + throw originalError; + } + } + }; +} else { + beginWork$1 = beginWork; +} + +var didWarnAboutUpdateInRender = false; +var didWarnAboutUpdateInGetChildContext = false; +function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { + { + if (fiber.tag === ClassComponent) { + switch (phase) { + case "getChildContext": + 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 " + + "within `render`). Render methods should be a pure function of " + + "props and state." + ); + didWarnAboutUpdateInRender = true; + break; + } + } + } +} + +function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { + { + if ( + workPhase === NotWorking && + ReactShouldWarnActingUpdates$1.current === false + ) { + warningWithoutStack$1( + false, + "An update to %s inside a test was not wrapped in act(...).\n\n" + + "When testing, code that causes React state updates should be " + + "wrapped into act(...):\n\n" + + "act(() => {\n" + + " /* fire events that update state */\n" + + "});\n" + + "/* assert on the output */\n\n" + + "This ensures that you're testing the behavior the user would see " + + "in the browser." + + " Learn more at https://fb.me/react-wrap-tests-with-act" + + "%s", + getComponentName(fiber.type), + getStackByFiberInDevAndProd(fiber) + ); + } + } +} + +var warnIfNotCurrentlyActingUpdatesInDev$2 = warnIfNotCurrentlyActingUpdatesInDEV; + +function computeThreadID$1(root, expirationTime) { + // Interaction threads are unique per root and expiration time. + return expirationTime * 1000 + root.interactionThreadID; +} + +function schedulePendingInteraction(root, expirationTime) { + // This is called when work is scheduled on a root. It sets up a pending + // interaction, which is completed once the work commits. + if (!enableSchedulerTracing) { + return; + } + + var interactions = tracing.__interactionsRef.current; + if (interactions.size > 0) { + var pendingInteractionMap = root.pendingInteractionMap; + var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { + interactions.forEach(function(interaction) { + if (!pendingInteractions.has(interaction)) { + // Update the pending async work count for previously unscheduled interaction. + interaction.__count++; + } + + pendingInteractions.add(interaction); + }); + } else { + pendingInteractionMap.set(expirationTime, new Set(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$1(root, expirationTime); + subscriber.onWorkScheduled(interactions, threadID); + } + } +} + +function startWorkOnPendingInteraction(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 + // 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, + scheduledExpirationTime + ) { + if (scheduledExpirationTime >= expirationTime) { + scheduledInteractions.forEach(function(interaction) { + 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 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$1(root, expirationTime); + try { + subscriber.onWorkStarted(interactions, threadID); + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } + } + } +} + +function finishPendingInteractions(root, committedExpirationTime) { + if (!enableSchedulerTracing) { + return; + } + + var earliestRemainingTimeAfterCommit = root.firstPendingTime; + + var subscriber = void 0; + + try { + subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { + var threadID = computeThreadID$1(root, committedExpirationTime); + subscriber.onWorkStopped(root.memoizedInteractions, threadID); + } + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } finally { + // Clear completed interactions from the pending Map. + // Unless the render was suspended or cascading work was scheduled, + // In which case– leave pending interactions until the subsequent render. + var pendingInteractionMap = root.pendingInteractionMap; + pendingInteractionMap.forEach(function( + scheduledInteractions, + scheduledExpirationTime + ) { + // Only decrement the pending interaction count if we're done. + // If there's still work at the current priority, + // That indicates that we are waiting for suspense data. + if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { + pendingInteractionMap.delete(scheduledExpirationTime); + + scheduledInteractions.forEach(function(interaction) { + interaction.__count--; + + if (subscriber !== null && interaction.__count === 0) { + try { + subscriber.onInteractionScheduledWorkCompleted(interaction); + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } + } + }); + } + }); + } +} + +var requestCurrentTime$$1 = enableNewScheduler + ? requestCurrentTime$2 + : requestCurrentTime$1; +var computeExpirationForFiber$$1 = enableNewScheduler + ? computeExpirationForFiber$2 + : computeExpirationForFiber$1; +var captureCommitPhaseError$$1 = enableNewScheduler + ? captureCommitPhaseError$2 + : captureCommitPhaseError$1; +var onUncaughtError$$1 = enableNewScheduler + ? onUncaughtError$2 + : onUncaughtError$1; +var markRenderEventTime$$1 = enableNewScheduler + ? markRenderEventTime$2 + : markRenderEventTime$1; +var renderDidSuspend$$1 = enableNewScheduler + ? renderDidSuspend$2 + : renderDidSuspend$1; +var renderDidError$$1 = enableNewScheduler + ? renderDidError$2 + : renderDidError$1; +var pingSuspendedRoot$$1 = enableNewScheduler + ? pingSuspendedRoot$2 + : pingSuspendedRoot$1; +var retryTimedOutBoundary$$1 = enableNewScheduler + ? retryTimedOutBoundary$2 + : retryTimedOutBoundary$1; +var resolveRetryThenable$$1 = enableNewScheduler + ? resolveRetryThenable$2 + : resolveRetryThenable$1; +var markLegacyErrorBoundaryAsFailed$$1 = enableNewScheduler + ? markLegacyErrorBoundaryAsFailed$2 + : markLegacyErrorBoundaryAsFailed$1; +var isAlreadyFailedLegacyErrorBoundary$$1 = enableNewScheduler + ? isAlreadyFailedLegacyErrorBoundary$2 + : isAlreadyFailedLegacyErrorBoundary$1; +var scheduleWork$$1 = enableNewScheduler ? scheduleWork$2 : scheduleWork$1; + +var batchedUpdates$1 = enableNewScheduler ? batchedUpdates$3 : batchedUpdates$2; + +var interactiveUpdates$1 = enableNewScheduler + ? interactiveUpdates$3 + : interactiveUpdates$2; +var flushInteractiveUpdates$1 = enableNewScheduler + ? flushInteractiveUpdates$3 + : flushInteractiveUpdates$2; + +var flushPassiveEffects$$1 = enableNewScheduler + ? flushPassiveEffects$2 + : flushPassiveEffects$1; +var warnIfNotCurrentlyActingUpdatesInDev$$1 = enableNewScheduler + ? warnIfNotCurrentlyActingUpdatesInDev$2 + : warnIfNotCurrentlyActingUpdatesInDev$1; + // 0 is PROD, 1 is DEV. // Might add PROFILE later. @@ -18347,9 +21204,9 @@ function scheduleRootUpdate(current$$1, element, expirationTime, callback) { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); + scheduleWork$$1(current$$1, expirationTime); return expirationTime; } @@ -18390,13 +21247,20 @@ function findHostInstance(component) { var fiber = get$1(component); if (fiber === undefined) { if (typeof component.render === "function") { - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } else { - invariant( - false, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - ); + (function() { + { + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } + })(); } } var hostFiber = findCurrentHostFiber(fiber); @@ -18411,13 +21275,20 @@ function findHostInstanceWithWarning(component, methodName) { var fiber = get$1(component); if (fiber === undefined) { if (typeof component.render === "function") { - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } else { - invariant( - false, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - ); + (function() { + { + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } + })(); } } var hostFiber = findCurrentHostFiber(fiber); @@ -18470,8 +21341,8 @@ function createContainer(containerInfo, isConcurrent, hydrate) { function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, current$$1); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, current$$1); return updateContainerAtExpirationTime( element, container, @@ -18494,7 +21365,18 @@ function getPublicRootInstance(container) { } } +var shouldSuspendImpl = function(fiber) { + return false; +}; + +function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); +} + +var overrideHookState = null; var overrideProps = null; +var scheduleUpdate = null; +var setSuspenseHandler = null; { var copyWithSetImpl = function(obj, path, idx, value) { @@ -18512,14 +21394,50 @@ var overrideProps = null; return copyWithSetImpl(obj, path, 0, value); }; + // 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) { + flushPassiveEffects$$1(); + + var newState = copyWithSet(currentHook.memoizedState, path, value); + currentHook.memoizedState = newState; + 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); + + scheduleWork$$1(fiber, Sync); + } + }; + // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - flushPassiveEffects(); + flushPassiveEffects$$1(); fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } - scheduleWork(fiber, Sync); + scheduleWork$$1(fiber, Sync); + }; + + scheduleUpdate = function(fiber) { + flushPassiveEffects$$1(); + scheduleWork$$1(fiber, Sync); + }; + + setSuspenseHandler = function(newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; }; } @@ -18529,7 +21447,10 @@ function injectIntoDevTools(devToolsConfig) { return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: overrideHookState, overrideProps: overrideProps, + setSuspenseHandler: setSuspenseHandler, + scheduleUpdate: scheduleUpdate, currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); @@ -18573,7 +21494,7 @@ function createPortal( // TODO: this is special because it gets imported during build. -var ReactVersion = "16.8.3"; +var ReactVersion = "16.8.6"; // Modules provided by RN: var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { @@ -18611,10 +21532,33 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * prop](docs/view.html#onlayout) instead. */ measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }, /** @@ -18633,10 +21577,33 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * has been completed in native. */ measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }, /** @@ -18652,12 +21619,56 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { onSuccess, onFail /* currently unused */ ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + 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; + } + + UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } }, /** @@ -18667,17 +21678,6 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * Manipulation](docs/direct-manipulation.html)). */ setNativeProps: function(nativeProps) { - { - if (warnAboutDeprecatedSetNativeProps) { - warningWithoutStack$1( - false, - "Warning: Calling ref.setNativeProps(nativeProps) " + - "is deprecated and will be removed in a future release. " + - "Use the setNativeProps export from the react-native package instead." + - "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" - ); - } - } // 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. @@ -18699,6 +21699,26 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { return; } + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + { + if (warnAboutDeprecatedSetNativeProps) { + warningWithoutStack$1( + false, + "Warning: Calling ref.setNativeProps(nativeProps) " + + "is deprecated and will be removed in a future release. " + + "Use the setNativeProps export from the react-native package instead." + + "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" + ); + } + } + var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; var viewConfig = @@ -18743,13 +21763,18 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { // true without actually implementing them (setting them to undefined // isn't allowed by ReactClass) var NativeMethodsMixin_DEV = NativeMethodsMixin; - invariant( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps, - "Do not override existing functions." - ); + (function() { + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw ReactError("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() { @@ -18876,11 +21901,34 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * [`onLayout` prop](docs/view.html#onlayout) instead. */ - ReactNativeComponent.prototype.measure = function measure(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + ReactNativeComponent.prototype.measure = function measure$$1(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) { + FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }; /** @@ -18897,13 +21945,36 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * These values are not available until after natives rendering completes. */ - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( + ReactNativeComponent.prototype.measureInWindow = function measureInWindow$$1( callback ) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }; /** @@ -18913,17 +21984,61 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. */ - ReactNativeComponent.prototype.measureLayout = function measureLayout( + ReactNativeComponent.prototype.measureLayout = function measureLayout$$1( relativeToNativeNode, onSuccess, onFail /* currently unused */ ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + 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; + } + + UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } }; /** @@ -18936,18 +22051,6 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { ReactNativeComponent.prototype.setNativeProps = function setNativeProps( nativeProps ) { - { - if (warnAboutDeprecatedSetNativeProps) { - warningWithoutStack$1( - false, - "Warning: Calling ref.setNativeProps(nativeProps) " + - "is deprecated and will be removed in a future release. " + - "Use the setNativeProps export from the react-native package instead." + - "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" - ); - } - } - // 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. @@ -18969,6 +22072,26 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { return; } + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + { + if (warnAboutDeprecatedSetNativeProps) { + warningWithoutStack$1( + false, + "Warning: Calling ref.setNativeProps(nativeProps) " + + "is deprecated and will be removed in a future release. " + + "Use the setNativeProps export from the react-native package instead." + + "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" + ); + } + } + var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; var viewConfig = @@ -19109,36 +22232,6 @@ var getInspectorDataForViewTag = void 0; }; } -// Module provided by RN: -function setNativeProps(handle, nativeProps) { - if (handle._nativeTag == null) { - !(handle._nativeTag != null) - ? warningWithoutStack$1( - false, - "setNativeProps was called with a ref that isn't a " + - "native component. Use React.forwardRef to get access to the underlying native component" - ) - : void 0; - return; - } - - { - warnForStyleProps(nativeProps, handle.viewConfig.validAttributes); - } - - var updatePayload = create(nativeProps, handle.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) { - UIManager.updateView( - handle._nativeTag, - handle.viewConfig.uiViewClassName, - updatePayload - ); - } -} - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function findNodeHandle(componentOrHandle) { @@ -19206,8 +22299,14 @@ var ReactFabric = { findNodeHandle: findNodeHandle, - setNativeProps: setNativeProps, + setNativeProps: function(handle, nativeProps) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + }, render: function(element, containerTag, callback) { var root = roots.get(containerTag); diff --git a/Libraries/Renderer/oss/ReactFabric-prod.js b/Libraries/Renderer/oss/ReactFabric-prod.js index f77404ffb91..5e48e88a8a0 100644 --- a/Libraries/Renderer/oss/ReactFabric-prod.js +++ b/Libraries/Renderer/oss/ReactFabric-prod.js @@ -18,30 +18,93 @@ var ReactNativeViewConfigRegistry = require("ReactNativeViewConfigRegistry"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), - FabricUIManager = require("FabricUIManager"); -var scheduler = require("scheduler"), - ExceptionsManager = require("ExceptionsManager"); -function invariant(condition, format, a, b, c, d, e, f) { - if (!condition) { - condition = void 0; - if (void 0 === format) - condition = Error( - "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." - ); - else { - var args = [a, b, c, d, e, f], - argIndex = 0; - condition = Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - condition.name = "Invariant Violation"; - } - condition.framesToPop = 1; - throw condition; - } + FabricUIManager = require("FabricUIManager"), + Scheduler = require("scheduler"); +var ExceptionsManager = require("ExceptionsManager"); +function ReactError(message) { + message = Error(message); + message.name = "Invariant Violation"; + return message; } +var eventPluginOrder = null, + namesToPlugins = {}; +function recomputePluginOrdering() { + if (eventPluginOrder) + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], + pluginIndex = eventPluginOrder.indexOf(pluginName); + if (!(-1 < pluginIndex)) + throw ReactError( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + if (!plugins[pluginIndex]) { + if (!pluginModule.extractEvents) + throw ReactError( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + plugins[pluginIndex] = pluginModule; + pluginIndex = pluginModule.eventTypes; + for (var eventName in pluginIndex) { + var JSCompiler_inline_result = void 0; + var dispatchConfig = pluginIndex[eventName], + pluginModule$jscomp$0 = pluginModule, + eventName$jscomp$0 = eventName; + if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." + ); + eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (JSCompiler_inline_result in phasedRegistrationNames) + phasedRegistrationNames.hasOwnProperty( + JSCompiler_inline_result + ) && + publishRegistrationName( + phasedRegistrationNames[JSCompiler_inline_result], + pluginModule$jscomp$0, + eventName$jscomp$0 + ); + JSCompiler_inline_result = !0; + } else + dispatchConfig.registrationName + ? (publishRegistrationName( + dispatchConfig.registrationName, + pluginModule$jscomp$0, + eventName$jscomp$0 + ), + (JSCompiler_inline_result = !0)) + : (JSCompiler_inline_result = !1); + if (!JSCompiler_inline_result) + throw ReactError( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + } + } +} +function publishRegistrationName(registrationName, pluginModule) { + if (registrationNameModules[registrationName]) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + registrationNameModules[registrationName] = pluginModule; +} +var plugins = [], + eventNameDispatchConfigs = {}, + registrationNameModules = {}; function invokeGuardedCallbackImpl(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { @@ -83,88 +146,13 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - invariant( - !1, + throw ReactError( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ), - (error = void 0); + ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } } -var eventPluginOrder = null, - namesToPlugins = {}; -function recomputePluginOrdering() { - if (eventPluginOrder) - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName], - pluginIndex = eventPluginOrder.indexOf(pluginName); - invariant( - -1 < pluginIndex, - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", - pluginName - ); - if (!plugins[pluginIndex]) { - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - pluginIndex = pluginModule.eventTypes; - for (var eventName in pluginIndex) { - var JSCompiler_inline_result = void 0; - var dispatchConfig = pluginIndex[eventName], - pluginModule$jscomp$0 = pluginModule, - eventName$jscomp$0 = eventName; - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0), - "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", - eventName$jscomp$0 - ); - eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (JSCompiler_inline_result in phasedRegistrationNames) - phasedRegistrationNames.hasOwnProperty( - JSCompiler_inline_result - ) && - publishRegistrationName( - phasedRegistrationNames[JSCompiler_inline_result], - pluginModule$jscomp$0, - eventName$jscomp$0 - ); - JSCompiler_inline_result = !0; - } else - dispatchConfig.registrationName - ? (publishRegistrationName( - dispatchConfig.registrationName, - pluginModule$jscomp$0, - eventName$jscomp$0 - ), - (JSCompiler_inline_result = !0)) - : (JSCompiler_inline_result = !1); - invariant( - JSCompiler_inline_result, - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } - } -} -function publishRegistrationName(registrationName, pluginModule) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; -} -var plugins = [], - eventNameDispatchConfigs = {}, - registrationNameModules = {}, - getFiberCurrentPropsFromNode = null, +var getFiberCurrentPropsFromNode = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { @@ -176,10 +164,8 @@ function executeDispatch(event, listener, inst) { function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + if (Array.isArray(dispatchListener)) + throw ReactError("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -190,10 +176,10 @@ function executeDirectDispatch(event) { return dispatchListener; } function accumulateInto(current, next) { - invariant( - null != next, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); if (null == current) return next; if (Array.isArray(current)) { if (Array.isArray(next)) return current.push.apply(current, next), current; @@ -227,10 +213,10 @@ function executeDispatchesAndReleaseTopLevel(e) { } var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ); + if (eventPluginOrder) + throw ReactError( + "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,15 +226,19 @@ var injection = { for (pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { var pluginModule = injectedNamesToPlugins[pluginName]; - (namesToPlugins.hasOwnProperty(pluginName) && - namesToPlugins[pluginName] === pluginModule) || - (invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", - pluginName - ), - (namesToPlugins[pluginName] = pluginModule), - (isOrderingDirty = !0)); + if ( + !namesToPlugins.hasOwnProperty(pluginName) || + namesToPlugins[pluginName] !== pluginModule + ) { + if (namesToPlugins[pluginName]) + throw ReactError( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = !0; + } } isOrderingDirty && recomputePluginOrdering(); } @@ -284,12 +274,14 @@ function getListener(inst, registrationName) { inst = !1; } if (inst) return null; - invariant( - !listener || "function" === typeof listener, - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + if (listener && "function" !== typeof listener) + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); return listener; } function getParent(inst) { @@ -450,10 +442,10 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { return new this(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { - invariant( - event instanceof this, - "Trying to release an event instance into a pool of a different type." - ); + if (!(event instanceof this)) + throw ReactError( + "Trying to release an event instance into a pool of a different type." + ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); } @@ -488,7 +480,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - invariant(null != _ref, "Touch object is missing identifier."); + if (null == _ref) throw ReactError("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -601,10 +593,10 @@ var ResponderTouchHistoryStore = { touchHistory: touchHistory }; function accumulate(current, next) { - invariant( - null != next, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); return null == current ? next : Array.isArray(current) @@ -969,11 +961,10 @@ var eventTypes$1 = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType], directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + if (!bubbleDispatchConfig && !directDispatchConfig) + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -1005,7 +996,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - invariant(inst, "All native instances should have a tag."); + if (!inst) throw ReactError("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1037,6 +1028,15 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113, REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116, + REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 60117, + REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 60118, + REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 60119, MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1081,6 +1081,15 @@ function getComponentName(type) { case REACT_LAZY_TYPE: if ((type = 1 === type._status ? type._result : null)) return getComponentName(type); + break; + case REACT_EVENT_COMPONENT_TYPE: + type = type.displayName; + if (void 0 !== type) return type; + break; + case REACT_EVENT_TARGET_TYPE: + if (type.type === REACT_EVENT_TARGET_TOUCH_HIT) return "TouchHitTarget"; + type = type.displayName; + if (void 0 !== type) return type; } return null; } @@ -1095,80 +1104,83 @@ function isFiberMountedImpl(fiber) { return 3 === node.tag ? 2 : 3; } function assertIsMounted(fiber) { - invariant( - 2 === isFiberMountedImpl(fiber), - "Unable to find node on an unmounted component." - ); + if (2 !== isFiberMountedImpl(fiber)) + throw ReactError("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; - if (!alternate) - return ( - (alternate = isFiberMountedImpl(fiber)), - invariant( - 3 !== alternate, - "Unable to find node on an unmounted component." - ), - 1 === alternate ? null : fiber - ); + if (!alternate) { + alternate = isFiberMountedImpl(fiber); + if (3 === alternate) + throw ReactError("Unable to find node on an unmounted component."); + return 1 === alternate ? null : fiber; + } for (var a = fiber, b = alternate; ; ) { - var parentA = a.return, - parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) break; - if (parentA.child === parentB.child) { - for (var child = parentA.child; child; ) { - if (child === a) return assertIsMounted(parentA), fiber; - if (child === b) return assertIsMounted(parentA), alternate; - child = child.sibling; + var parentA = a.return; + if (null === parentA) break; + var parentB = parentA.alternate; + if (null === parentB) { + b = parentA.return; + if (null !== b) { + a = b; + continue; } - invariant(!1, "Unable to find node on an unmounted component."); + break; + } + if (parentA.child === parentB.child) { + for (parentB = parentA.child; parentB; ) { + if (parentB === a) return assertIsMounted(parentA), fiber; + if (parentB === b) return assertIsMounted(parentA), alternate; + parentB = parentB.sibling; + } + throw ReactError("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { - child = !1; - for (var _child = parentA.child; _child; ) { + for (var didFindChild = !1, _child = parentA.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentA; b = parentB; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentA; a = parentB; break; } _child = _child.sibling; } - if (!child) { + if (!didFindChild) { for (_child = parentB.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentB; b = parentA; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentB; a = parentA; break; } _child = _child.sibling; } - invariant( - child, - "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 ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ); + if (a.alternate !== b) + throw ReactError( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - invariant(3 === a.tag, "Unable to find node on an unmounted component."); + if (3 !== a.tag) + throw ReactError("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1416,37 +1428,13 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ))))); return updatePayload; } -var now$1 = - "object" === typeof performance && "function" === typeof performance.now - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }, - scheduledCallback = null, - frameDeadline = 0; -function setTimeoutCallback() { - frameDeadline = now$1() + 5; - var callback = scheduledCallback; - scheduledCallback = null; - null !== callback && callback(); -} -function scheduleDeferredCallback$1(callback) { - scheduledCallback = callback; - return setTimeout(setTimeoutCallback, 1); -} var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { - if ((target = getInstanceFromNode(target))) { - invariant( - !1, + if (getInstanceFromNode(target)) + throw ReactError( "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(target.stateNode); - null(target.stateNode, target.type, props); - } } function _batchedUpdatesImpl(fn, bookkeeping) { return fn(bookkeeping); @@ -1491,24 +1479,22 @@ function dispatchEvent(target, topLevelType, nativeEvent) { null !== events && (eventQueue = accumulateInto(eventQueue, events)); events = eventQueue; eventQueue = null; - if ( - events && - (forEachAccumulated(events, executeDispatchesAndReleaseTopLevel), - invariant( - !eventQueue, - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ), - hasRethrowError) - ) - throw ((events = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - events); + if (events) { + forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); + if (eventQueue) + throw ReactError( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + if (hasRethrowError) + throw ((events = rethrowError), + (hasRethrowError = !1), + (rethrowError = null), + events); + } }); } function shim$1() { - invariant( - !1, + throw ReactError( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } @@ -1516,12 +1502,18 @@ var nextReactTag = 2; FabricUIManager.registerEventHandler && FabricUIManager.registerEventHandler(dispatchEvent); var ReactFabricHostComponent = (function() { - function ReactFabricHostComponent(tag, viewConfig, props) { + function ReactFabricHostComponent( + tag, + viewConfig, + 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() { TextInputState.blurTextInput(this._nativeTag); @@ -1530,14 +1522,14 @@ var ReactFabricHostComponent = (function() { TextInputState.focusTextInput(this._nativeTag); }; ReactFabricHostComponent.prototype.measure = function(callback) { - UIManager.measure( - this._nativeTag, + FabricUIManager.measure( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; ReactFabricHostComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - this._nativeTag, + FabricUIManager.measureInWindow( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; @@ -1546,27 +1538,16 @@ var ReactFabricHostComponent = (function() { onSuccess, onFail ) { - UIManager.measureLayout( - this._nativeTag, - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; - ReactFabricHostComponent.prototype.setNativeProps = function(nativeProps) { - nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - this.viewConfig.validAttributes - ); - null != nativeProps && - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - nativeProps + "number" !== typeof relativeToNativeNode && + relativeToNativeNode instanceof ReactFabricHostComponent && + FabricUIManager.measureLayout( + this._internalInstanceHandle.stateNode.node, + relativeToNativeNode._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; + ReactFabricHostComponent.prototype.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1575,10 +1556,10 @@ function createTextInstance( hostContext, internalInstanceHandle ) { - invariant( - hostContext.isInAParentText, - "Text strings must be rendered within a component." - ); + if (!hostContext.isInAParentText) + throw ReactError( + "Text strings must be rendered within a component." + ); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1606,18 +1587,6 @@ function cloneHiddenInstance(instance) { canonical: instance.canonical }; } -function cloneUnhiddenInstance(instance, type, props) { - var viewConfig = instance.canonical.viewConfig; - type = instance.node; - var prevProps = Object.assign({}, props, { - style: [props.style, { display: "none" }] - }); - props = diffProperties(null, prevProps, props, viewConfig.validAttributes); - return { - node: FabricUIManager.cloneNodeWithNewProps(type, props), - canonical: instance.canonical - }; -} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function getStackByFiberInDevAndProd(workInProgress) { var info = ""; @@ -1702,10 +1671,10 @@ function popTopLevelContextObject(fiber) { pop(contextStackCursor, fiber); } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); + if (contextStackCursor.current !== emptyContextObject) + throw ReactError( + "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); } @@ -1715,12 +1684,13 @@ function processChildContext(fiber, type, parentContext) { if ("function" !== typeof instance.getChildContext) return parentContext; instance = instance.getChildContext(); for (var contextKey in instance) - invariant( - contextKey in fiber, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + if (!(contextKey in fiber)) + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); return Object.assign({}, parentContext, instance); } function pushContextProvider(workInProgress) { @@ -1739,10 +1709,10 @@ function pushContextProvider(workInProgress) { } function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "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 ReactError( + "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)), (instance.__reactInternalMemoizedMergedChildContext = type), @@ -1776,6 +1746,7 @@ function injectInternals(internals) { } catch (err) {} return !0; } +var Scheduler_now = Scheduler.unstable_now; function FiberNode(tag, pendingProps, key, mode) { this.tag = tag; this.key = key; @@ -1899,11 +1870,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - invariant( - !1, - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", - null == type ? type : typeof type, - "" + throw ReactError( + "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); @@ -1945,6 +1915,21 @@ function createFiberFromPortal(portal, mode, expirationTime) { }; return mode; } +function FiberRootNode(containerInfo, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pingCache = this.pendingChildren = null; + this.pendingCommitExpirationTime = 0; + this.finishedWork = null; + this.timeoutHandle = -1; + this.pendingContext = this.context = null; + this.hydrate = hydrate; + this.firstBatch = null; + this.latestPingedTime = this.latestSuspendedTime = this.earliestSuspendedTime = this.latestPendingTime = this.earliestPendingTime = 0; + this.didError = !1; + this.expirationTime = this.nextExpirationTimeToWorkOn = 0; + this.nextScheduledRoot = null; +} function markPendingPriorityLevel(root, expirationTime) { root.didError = !1; var earliestPendingTime = root.earliestPendingTime; @@ -1956,36 +1941,6 @@ function markPendingPriorityLevel(root, expirationTime) { (root.latestPendingTime = expirationTime); findNextExpirationTimeToWorkOn(expirationTime, root); } -function markCommittedPriorityLevels(root, earliestRemainingTime) { - root.didError = !1; - if (0 === earliestRemainingTime) - (root.earliestPendingTime = 0), - (root.latestPendingTime = 0), - (root.earliestSuspendedTime = 0), - (root.latestSuspendedTime = 0), - (root.latestPingedTime = 0); - else { - earliestRemainingTime < root.latestPingedTime && - (root.latestPingedTime = 0); - var latestPendingTime = root.latestPendingTime; - 0 !== latestPendingTime && - (latestPendingTime > earliestRemainingTime - ? (root.earliestPendingTime = root.latestPendingTime = 0) - : root.earliestPendingTime > earliestRemainingTime && - (root.earliestPendingTime = root.latestPendingTime)); - latestPendingTime = root.earliestSuspendedTime; - 0 === latestPendingTime - ? markPendingPriorityLevel(root, earliestRemainingTime) - : earliestRemainingTime < root.latestSuspendedTime - ? ((root.earliestSuspendedTime = 0), - (root.latestSuspendedTime = 0), - (root.latestPingedTime = 0), - markPendingPriorityLevel(root, earliestRemainingTime)) - : earliestRemainingTime > latestPendingTime && - markPendingPriorityLevel(root, earliestRemainingTime); - } - findNextExpirationTimeToWorkOn(0, root); -} function markSuspendedPriorityLevel(root, suspendedTime) { root.didError = !1; root.latestPingedTime >= suspendedTime && (root.latestPingedTime = 0); @@ -2008,14 +1963,6 @@ function markSuspendedPriorityLevel(root, suspendedTime) { (root.latestSuspendedTime = suspendedTime); findNextExpirationTimeToWorkOn(suspendedTime, root); } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestPendingTime = root.earliestPendingTime; - root = root.earliestSuspendedTime; - earliestPendingTime > renderExpirationTime && - (renderExpirationTime = earliestPendingTime); - root > renderExpirationTime && (renderExpirationTime = root); - return renderExpirationTime; -} function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { var earliestSuspendedTime = root.earliestSuspendedTime, latestSuspendedTime = root.latestSuspendedTime, @@ -2130,37 +2077,37 @@ var classComponentUpdater = { }, enqueueSetState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueReplaceState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ReplaceState; update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueForceUpdate: function(inst, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ForceUpdate; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); } }; function checkShouldComponentUpdate( @@ -2285,17 +2232,19 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { element = element._owner; var inst = void 0; - element && - (invariant( - 1 === element.tag, - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ), - (inst = element.stateNode)); - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.", - returnFiber - ); + if (element) { + if (1 !== element.tag) + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + inst = element.stateNode; + } + if (!inst) + throw ReactError( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." + ); var stringRef = "" + returnFiber; if ( null !== current$$1 && @@ -2312,27 +2261,27 @@ function coerceRef(returnFiber, current$$1, element) { current$$1._stringRef = stringRef; return current$$1; } - invariant( - "string" === typeof returnFiber, - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) 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.", - returnFiber - ); + if ("string" !== typeof returnFiber) + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + if (!element._owner) + throw ReactError( + "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) { - "textarea" !== returnFiber.type && - invariant( - !1, - "Objects are not valid as a React child (found: %s).%s", - "[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - "" + if ("textarea" !== returnFiber.type) + throw ReactError( + "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) { @@ -2731,15 +2680,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) { var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - "function" === typeof iteratorFn, - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ); + if ("function" !== typeof iteratorFn) + throw ReactError( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); newChildrenIterable = iteratorFn.call(newChildrenIterable); - invariant( - null != newChildrenIterable, - "An iterable object provided no iterator." - ); + if (null == newChildrenIterable) + throw ReactError("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -2831,7 +2778,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) + if (isUnkeyedTopLevelFragment.key === isObject) { if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -2856,14 +2803,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren( - returnFiber, - isUnkeyedTopLevelFragment - ); - break; } - else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); + break; + } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -2899,7 +2842,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) + if (currentFirstChild.key === isUnkeyedTopLevelFragment) { if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -2919,11 +2862,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren(returnFiber, currentFirstChild); - break; } - else deleteChild(returnFiber, currentFirstChild); + deleteRemainingChildren(returnFiber, currentFirstChild); + break; + } else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -2977,12 +2919,11 @@ function ChildReconciler(shouldTrackSideEffects) { switch (returnFiber.tag) { case 1: case 0: - (expirationTime = returnFiber.type), - invariant( - !1, - "%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.", - expirationTime.displayName || expirationTime.name || "Component" - ); + throw ((returnFiber = returnFiber.type), + ReactError( + (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); }; @@ -2994,10 +2935,10 @@ var reconcileChildFibers = ChildReconciler(!0), contextFiberStackCursor = { current: NO_CONTEXT }, rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ); + if (c === NO_CONTEXT) + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); return c; } function pushHostContainer(fiber, nextRootInstance) { @@ -3034,15 +2975,7 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -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 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3057,9 +2990,8 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - invariant( - !1, - "Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)" + throw ReactError( + "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) { @@ -3107,10 +3039,10 @@ function renderWithHooks( remainingExpirationTime = 0; componentUpdateQueue = null; sideEffectTag = 0; - invariant( - !current, - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ); + if (current) + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); return workInProgress; } function resetHooks() { @@ -3144,10 +3076,8 @@ function updateWorkInProgressHook() { (currentHook = nextCurrentHook), (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { - invariant( - null !== nextCurrentHook, - "Rendered more hooks than during the previous render." - ); + if (null === nextCurrentHook) + throw ReactError("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3170,10 +3100,11 @@ function basicStateReducer(state, action) { function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; - invariant( - null !== queue, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + if (null === queue) + throw ReactError( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { var _dispatch = queue.dispatch; if (null !== renderPhaseUpdates) { @@ -3188,8 +3119,7 @@ function updateReducer(reducer) { is(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } } @@ -3215,10 +3145,12 @@ function updateReducer(reducer) { (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && (remainingExpirationTime = updateExpirationTime)) - : (newState = + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (newState = _update.eagerReducer === reducer ? _update.eagerState - : reducer(newState, _update.action)); + : reducer(newState, _update.action))); baseUpdate = _update; _update = _update.next; } while (null !== _update && _update !== _dispatch); @@ -3228,8 +3160,7 @@ function updateReducer(reducer) { hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; } return [hook.memoizedState, queue.dispatch]; } @@ -3265,7 +3196,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; } } @@ -3292,10 +3223,10 @@ function imperativeHandleEffect(create, ref) { } function mountDebugValue() {} function dispatchAction(fiber, queue, action) { - invariant( - 25 > numberOfReRenders, - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ); + if (!(25 > numberOfReRenders)) + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); var alternate = fiber.alternate; if ( fiber === currentlyRenderingFiber$1 || @@ -3320,9 +3251,9 @@ function dispatchAction(fiber, queue, action) { queue.next = fiber; } else { - flushPassiveEffects(); - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, fiber); + flushPassiveEffects$$1(); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: currentTime, action: action, @@ -3341,10 +3272,10 @@ function dispatchAction(fiber, queue, action) { if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && - ((alternate = queue.eagerReducer), null !== alternate) + ((alternate = queue.lastRenderedReducer), null !== alternate) ) try { - var currentState = queue.eagerState, + var currentState = queue.lastRenderedState, _eagerState = alternate(currentState, action); _update2.eagerReducer = alternate; _update2.eagerState = _eagerState; @@ -3352,7 +3283,7 @@ function dispatchAction(fiber, queue, action) { } catch (error) { } finally { } - scheduleWork(fiber, currentTime); + scheduleWork$$1(fiber, currentTime); } } var ContextOnlyDispatcher = { @@ -3379,19 +3310,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(); @@ -3407,8 +3338,8 @@ var ContextOnlyDispatcher = { reducer = hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialArg + lastRenderedReducer: reducer, + lastRenderedState: initialArg }; reducer = reducer.dispatch = dispatchAction.bind( null, @@ -3429,8 +3360,8 @@ var ContextOnlyDispatcher = { initialState = hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }; initialState = initialState.dispatch = dispatchAction.bind( null, @@ -3458,19 +3389,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(); @@ -4046,7 +3977,10 @@ function updateSuspenseComponent( nextState = null; var nextDidTimeout = !1; } else - (nextState = { timedOutAt: null !== nextState ? nextState.timedOutAt : 0 }), + (nextState = { + fallbackExpirationTime: + null !== nextState ? nextState.fallbackExpirationTime : 0 + }), (nextDidTimeout = !0), (workInProgress.effectTag &= -65); if (null === current$$1) @@ -4141,10 +4075,8 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.contextDependencies = current$$1.contextDependencies); if (workInProgress.childExpirationTime < renderExpirationTime) return null; - invariant( - null === current$$1 || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + if (null !== current$$1 && workInProgress.child !== current$$1.child) + throw ReactError("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4309,59 +4241,57 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ((current$$1.alternate = null), (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); - hasContext = workInProgress.pendingProps; - current$$1 = readLazyComponentType(context); - workInProgress.type = current$$1; - context = workInProgress.tag = resolveLazyComponentTag(current$$1); - hasContext = resolveDefaultProps(current$$1, hasContext); - getDerivedStateFromProps = void 0; - switch (context) { + current$$1 = workInProgress.pendingProps; + context = readLazyComponentType(context); + workInProgress.type = context; + hasContext = workInProgress.tag = resolveLazyComponentTag(context); + current$$1 = resolveDefaultProps(context, current$$1); + switch (hasContext) { case 0: - getDerivedStateFromProps = updateFunctionComponent( + workInProgress = updateFunctionComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 1: - getDerivedStateFromProps = updateClassComponent( + workInProgress = updateClassComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 11: - getDerivedStateFromProps = updateForwardRef( + workInProgress = updateForwardRef( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 14: - getDerivedStateFromProps = updateMemoComponent( + workInProgress = updateMemoComponent( null, workInProgress, - current$$1, - resolveDefaultProps(current$$1.type, hasContext), + context, + resolveDefaultProps(context.type, current$$1), updateExpirationTime, renderExpirationTime ); break; default: - invariant( - !1, - "Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s", - current$$1, - "" + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + context + + ". Lazy element type must resolve to a class or function." ); } - return getDerivedStateFromProps; + return workInProgress; case 0: return ( (updateExpirationTime = workInProgress.type), @@ -4395,38 +4325,36 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); case 3: - return ( - pushHostRootContext(workInProgress), - (updateExpirationTime = workInProgress.updateQueue), - invariant( - null !== updateExpirationTime, + pushHostRootContext(workInProgress); + updateExpirationTime = workInProgress.updateQueue; + if (null === updateExpirationTime) + throw ReactError( "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." - ), - (context = workInProgress.memoizedState), - (context = null !== context ? context.element : null), - processUpdateQueue( - workInProgress, - updateExpirationTime, - workInProgress.pendingProps, - null, - renderExpirationTime - ), - (updateExpirationTime = workInProgress.memoizedState.element), - updateExpirationTime === context - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current$$1, - workInProgress, - renderExpirationTime - )) - : (reconcileChildren( - current$$1, - workInProgress, - updateExpirationTime, - renderExpirationTime - ), - (workInProgress = workInProgress.child)), - workInProgress + ); + context = workInProgress.memoizedState; + context = null !== context ? context.element : null; + processUpdateQueue( + workInProgress, + updateExpirationTime, + workInProgress.pendingProps, + null, + renderExpirationTime ); + updateExpirationTime = workInProgress.memoizedState.element; + updateExpirationTime === context + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current$$1, + workInProgress, + renderExpirationTime + )) + : (reconcileChildren( + current$$1, + workInProgress, + updateExpirationTime, + renderExpirationTime + ), + (workInProgress = workInProgress.child)); + return workInProgress; case 5: return ( pushHostContext(workInProgress), @@ -4439,8 +4367,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - (workInProgress = workInProgress.child), - workInProgress + workInProgress.child ); case 6: return ( @@ -4718,8 +4645,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); } - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -4755,17 +4681,17 @@ function readContext(context, observedBits) { if ("number" !== typeof observedBits || 1073741823 === observedBits) (lastContextWithAllBitsObserved = context), (observedBits = 1073741823); observedBits = { context: context, observedBits: observedBits, next: null }; - null === lastContextDependency - ? (invariant( - null !== currentlyRenderingFiber, + if (null === lastContextDependency) { + if (null === currentlyRenderingFiber) + throw ReactError( "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.contextDependencies = { - first: observedBits, - expirationTime: 0 - })) - : (lastContextDependency = lastContextDependency.next = observedBits); + ); + lastContextDependency = observedBits; + currentlyRenderingFiber.contextDependencies = { + first: observedBits, + expirationTime: 0 + }; + } else lastContextDependency = lastContextDependency.next = observedBits; } return context._currentValue2; } @@ -4918,7 +4844,9 @@ function processUpdateQueue( ((newFirstUpdate = update), (newBaseState = resultState)), newExpirationTime < updateExpirationTime && (newExpirationTime = updateExpirationTime)) - : ((resultState = getStateFromUpdate( + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (resultState = getStateFromUpdate( workInProgress, queue, update, @@ -4991,11 +4919,11 @@ function commitUpdateEffects(effect, instance) { if (null !== _callback3) { effect.callback = null; var context = instance; - invariant( - "function" === typeof _callback3, - "Invalid argument passed as callback. Expected a function. Instead received: %s", - _callback3 - ); + if ("function" !== typeof _callback3) + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + _callback3 + ); _callback3.call(context); } effect = effect.nextEffect; @@ -5019,39 +4947,41 @@ appendAllChildren = function( isHidden ) { for (var node = workInProgress.child; null !== node; ) { - a: if (5 === node.tag) { + if (5 === node.tag) { var instance = node.stateNode; - if (needsVisibilityToggle) { - var props = node.memoizedProps, - type = node.type; - instance = isHidden - ? cloneHiddenInstance(instance, type, props, node) - : cloneUnhiddenInstance(instance, type, props, node); - node.stateNode = instance; - } + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance( + instance, + node.type, + node.memoizedProps, + node + )); FabricUIManager.appendChild(parent.node, instance.node); } else if (6 === node.tag) { instance = node.stateNode; - if (needsVisibilityToggle) { - instance = node.memoizedProps; - props = requiredContext(rootInstanceStackCursor.current); - type = requiredContext(contextStackCursor$1.current); - if (isHidden) throw Error("Not yet implemented."); - instance = createTextInstance(instance, props, type, workInProgress); - node.stateNode = instance; - } + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); FabricUIManager.appendChild(parent.node, instance.node); } else if (4 !== node.tag) { if ( 13 === node.tag && - ((props = node.alternate), - null !== props && - ((instance = null !== node.memoizedState), - (null !== props.memoizedState) !== instance)) + 0 !== (node.effectTag & 4) && + (instance = null !== node.memoizedState) ) { - props = instance ? node.child : node; - null !== props && appendAllChildren(parent, props, !0, instance); - break a; + var primaryChildParent = node.child; + if ( + null !== primaryChildParent && + (null !== primaryChildParent.child && + ((primaryChildParent.child.return = primaryChildParent), + appendAllChildren(parent, primaryChildParent, !0, instance)), + (instance = primaryChildParent.sibling), + null !== instance) + ) { + instance.return = node; + node = instance; + continue; + } } if (null !== node.child) { node.child.return = node; @@ -5075,40 +5005,46 @@ function appendAllChildrenToContainer( isHidden ) { for (var node = workInProgress.child; null !== node; ) { - a: if (5 === node.tag) { + if (5 === node.tag) { var instance = node.stateNode; - if (needsVisibilityToggle) { - var props = node.memoizedProps, - type = node.type; - instance = isHidden - ? cloneHiddenInstance(instance, type, props, node) - : cloneUnhiddenInstance(instance, type, props, node); - node.stateNode = instance; - } + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance( + instance, + node.type, + node.memoizedProps, + node + )); FabricUIManager.appendChildToSet(containerChildSet, instance.node); } else if (6 === node.tag) { instance = node.stateNode; - if (needsVisibilityToggle) { - instance = node.memoizedProps; - props = requiredContext(rootInstanceStackCursor.current); - type = requiredContext(contextStackCursor$1.current); - if (isHidden) throw Error("Not yet implemented."); - instance = createTextInstance(instance, props, type, workInProgress); - node.stateNode = instance; - } + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); FabricUIManager.appendChildToSet(containerChildSet, instance.node); } else if (4 !== node.tag) { if ( 13 === node.tag && - ((props = node.alternate), - null !== props && - ((instance = null !== node.memoizedState), - (null !== props.memoizedState) !== instance)) + 0 !== (node.effectTag & 4) && + (instance = null !== node.memoizedState) ) { - props = instance ? node.child : node; - null !== props && - appendAllChildrenToContainer(containerChildSet, props, !0, instance); - break a; + var primaryChildParent = node.child; + if ( + null !== primaryChildParent && + (null !== primaryChildParent.child && + ((primaryChildParent.child.return = primaryChildParent), + appendAllChildrenToContainer( + containerChildSet, + primaryChildParent, + !0, + instance + )), + (instance = primaryChildParent.sibling), + null !== instance) + ) { + instance.return = node; + node = instance; + continue; + } } if (null !== node.child) { node.child.return = node; @@ -5211,6 +5147,7 @@ function logCapturedError(capturedError) { : Error("Unspecified error at:" + componentStack); ExceptionsManager.handleException(error, !1); } +var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5247,7 +5184,7 @@ function safelyDetachRef(current$$1) { try { ref(null); } catch (refError) { - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } else ref.current = null; } @@ -5257,12 +5194,12 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { 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); @@ -5274,26 +5211,47 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); + return; + case 12: + return; + case 13: + commitSuspenseComponent(finishedWork); return; } switch (finishedWork.tag) { case 1: - break; case 5: - break; case 6: + case 20: break; case 3: case 4: break; default: - invariant( - !1, + throw ReactError( "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; + null !== newState && + 0 === newState.fallbackExpirationTime && + (newState.fallbackExpirationTime = requestCurrentTime$$1() - 500); + newState = finishedWork.updateQueue; + if (null !== newState) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + newState.forEach(function(thenable) { + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + retryCache.has(thenable) || + (retryCache.add(thenable), thenable.then(retry, retry)); + }); + } +} var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime = createUpdate(expirationTime); @@ -5301,7 +5259,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime.payload = { element: null }; var error = errorInfo.value; expirationTime.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return expirationTime; @@ -5343,17 +5301,15 @@ function unwindWork(workInProgress) { workInProgress) : null; case 3: - return ( - popHostContainer(workInProgress), - popTopLevelContextObject(workInProgress), - (effectTag = workInProgress.effectTag), - invariant( - 0 === (effectTag & 64), + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + effectTag = workInProgress.effectTag; + if (0 !== (effectTag & 64)) + throw ReactError( "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 - ); + ); + workInProgress.effectTag = (effectTag & -2049) | 64; + return workInProgress; case 5: return popHostContext(workInProgress), null; case 13: @@ -5370,17 +5326,27 @@ function unwindWork(workInProgress) { return popHostContainer(workInProgress), null; case 10: return popProvider(workInProgress), null; + case 19: + case 20: + return null; default: return null; } } -var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback, + cancelCallback$1 = Scheduler.unstable_cancelCallback, + shouldYield$1 = Scheduler.unstable_shouldYield, + now$1 = Scheduler.unstable_now, + getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel, + NormalPriority$1 = Scheduler.unstable_NormalPriority, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, isWorking = !1, nextUnitOfWork = null, nextRoot = null, nextRenderExpirationTime = 0, - nextLatestAbsoluteTimeoutMs = -1, + mostRecentEventTime = 1073741823, + nextRenderDidSuspend = !1, nextRenderDidError = !1, nextEffect = null, isCommitting$1 = !1, @@ -5421,254 +5387,10 @@ function resetStack() { } nextRoot = null; nextRenderExpirationTime = 0; - nextLatestAbsoluteTimeoutMs = -1; - nextRenderDidError = !1; + mostRecentEventTime = 1073741823; + nextRenderDidError = nextRenderDidSuspend = !1; nextUnitOfWork = null; } -function commitAllHostEffects() { - for (; null !== nextEffect; ) { - var effectTag = nextEffect.effectTag; - if (effectTag & 128) { - var current$$1 = nextEffect.alternate; - null !== current$$1 && - ((current$$1 = current$$1.ref), - null !== current$$1 && - ("function" === typeof current$$1 - ? current$$1(null) - : (current$$1.current = null))); - } - switch (effectTag & 14) { - case 2: - nextEffect.effectTag &= -3; - break; - case 6: - nextEffect.effectTag &= -3; - commitWork(nextEffect.alternate, nextEffect); - break; - case 4: - commitWork(nextEffect.alternate, nextEffect); - break; - case 8: - effectTag = nextEffect; - a: for (var node = (current$$1 = effectTag); ; ) { - var current$$1$jscomp$0 = node; - "function" === typeof onCommitFiberUnmount && - onCommitFiberUnmount(current$$1$jscomp$0); - switch (current$$1$jscomp$0.tag) { - case 0: - case 11: - case 14: - case 15: - var updateQueue = current$$1$jscomp$0.updateQueue; - if ( - null !== updateQueue && - ((updateQueue = updateQueue.lastEffect), null !== updateQueue) - ) { - var effect = (updateQueue = updateQueue.next); - do { - var destroy = effect.destroy; - if (void 0 !== destroy) { - var current$$1$jscomp$1 = current$$1$jscomp$0; - try { - destroy(); - } catch (error) { - captureCommitPhaseError(current$$1$jscomp$1, error); - } - } - effect = effect.next; - } while (effect !== updateQueue); - } - break; - case 1: - safelyDetachRef(current$$1$jscomp$0); - updateQueue = current$$1$jscomp$0.stateNode; - if ("function" === typeof updateQueue.componentWillUnmount) - try { - (updateQueue.props = current$$1$jscomp$0.memoizedProps), - (updateQueue.state = current$$1$jscomp$0.memoizedState), - updateQueue.componentWillUnmount(); - } catch (unmountError) { - captureCommitPhaseError(current$$1$jscomp$0, unmountError); - } - break; - case 5: - safelyDetachRef(current$$1$jscomp$0); - break; - case 4: - FabricUIManager.createChildSet( - current$$1$jscomp$0.stateNode.containerInfo - ); - } - if (null !== node.child) - (node.child.return = node), (node = node.child); - else { - if (node === current$$1) break; - for (; null === node.sibling; ) { - if (null === node.return || node.return === current$$1) break a; - node = node.return; - } - node.sibling.return = node.return; - node = node.sibling; - } - } - effectTag.return = null; - effectTag.child = null; - effectTag.memoizedState = null; - effectTag.updateQueue = null; - effectTag = effectTag.alternate; - null !== effectTag && - ((effectTag.return = null), - (effectTag.child = null), - (effectTag.memoizedState = null), - (effectTag.updateQueue = null)); - } - nextEffect = nextEffect.nextEffect; - } -} -function commitBeforeMutationLifecycles() { - for (; null !== nextEffect; ) { - if (nextEffect.effectTag & 256) - a: { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); - break a; - 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 a; - case 3: - case 5: - case 6: - case 4: - case 17: - break a; - default: - invariant( - !1, - "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; - } -} -function commitAllLifeCycles(finishedRoot, committedExpirationTime$jscomp$0) { - for (; null !== nextEffect; ) { - var effectTag = nextEffect.effectTag; - if (effectTag & 36) { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect, - committedExpirationTime = committedExpirationTime$jscomp$0; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountLayout, MountLayout, finishedWork); - break; - case 1: - var instance = finishedWork.stateNode; - if (finishedWork.effectTag & 4) - if (null === current$$1) instance.componentDidMount(); - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current$$1.memoizedProps - : resolveDefaultProps( - finishedWork.type, - current$$1.memoizedProps - ); - instance.componentDidUpdate( - prevProps, - current$$1.memoizedState, - instance.__reactInternalSnapshotBeforeUpdate - ); - } - current$$1 = finishedWork.updateQueue; - null !== current$$1 && - commitUpdateQueue( - finishedWork, - current$$1, - instance, - committedExpirationTime - ); - break; - case 3: - instance = finishedWork.updateQueue; - if (null !== instance) { - current$$1 = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 5: - current$$1 = finishedWork.child.stateNode.canonical; - break; - case 1: - current$$1 = finishedWork.child.stateNode; - } - commitUpdateQueue( - finishedWork, - instance, - current$$1, - committedExpirationTime - ); - } - break; - case 5: - null === current$$1 && - finishedWork.effectTag & 4 && - invariant( - !1, - "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." - ); - break; - case 6: - break; - case 4: - break; - case 12: - break; - case 13: - break; - case 17: - break; - default: - invariant( - !1, - "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 & 128 && - ((finishedWork = nextEffect.ref), null !== finishedWork) - ) { - committedExpirationTime = nextEffect.stateNode; - switch (nextEffect.tag) { - case 5: - committedExpirationTime = committedExpirationTime.canonical; - } - "function" === typeof finishedWork - ? finishedWork(committedExpirationTime) - : (finishedWork.current = committedExpirationTime); - } - effectTag & 512 && (rootWithPendingPassiveEffects = finishedRoot); - nextEffect = nextEffect.nextEffect; - } -} function commitPassiveEffects(root, firstEffect) { passiveEffectCallback = passiveEffectCallbackHandle = rootWithPendingPassiveEffects = null; var previousIsRendering = isRendering; @@ -5679,133 +5401,32 @@ function commitPassiveEffects(root, firstEffect) { error = void 0; try { var finishedWork = firstEffect; - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork); - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork); + commitHookEffectList(0, 64, finishedWork); } catch (e) { (didError = !0), (error = e); } - didError && captureCommitPhaseError(firstEffect, error); + didError && captureCommitPhaseError$1(firstEffect, error); } firstEffect = firstEffect.nextEffect; } while (null !== firstEffect); isRendering = previousIsRendering; previousIsRendering = root.expirationTime; 0 !== previousIsRendering && requestWork(root, previousIsRendering); - isBatchingUpdates || isRendering || performWork(1073741823, !1); + isBatchingUpdates || isRendering || performWork(1073741823); } -function flushPassiveEffects() { - if (null !== passiveEffectCallbackHandle) { - var callbackID = passiveEffectCallbackHandle; - scheduledCallback = null; - clearTimeout(callbackID); - } +function isAlreadyFailedLegacyErrorBoundary$1(instance) { + return ( + null !== legacyErrorBoundariesThatAlreadyFailed && + legacyErrorBoundariesThatAlreadyFailed.has(instance) + ); +} +function flushPassiveEffects$1() { + var didFlushEffects = null !== passiveEffectCallback; + null !== passiveEffectCallbackHandle && + cancelCallback$1(passiveEffectCallbackHandle); null !== passiveEffectCallback && passiveEffectCallback(); -} -function commitRoot(root, finishedWork) { - isCommitting$1 = isWorking = !0; - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." - ); - var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - 0 !== committedExpirationTime, - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - root.pendingCommitExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - markCommittedPriorityLevels( - root, - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit - ); - ReactCurrentOwner$2.current = null; - updateExpirationTimeBeforeCommit = void 0; - 1 < finishedWork.effectTag - ? null !== finishedWork.lastEffect - ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - var error = void 0; - try { - commitBeforeMutationLifecycles(); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - error = void 0; - try { - commitAllHostEffects(); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - root.current = finishedWork; - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - error = void 0; - try { - commitAllLifeCycles(root, committedExpirationTime); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - if ( - null !== updateExpirationTimeBeforeCommit && - null !== rootWithPendingPassiveEffects - ) { - var callback = commitPassiveEffects.bind( - null, - root, - updateExpirationTimeBeforeCommit - ); - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return scheduleDeferredCallback$1(callback); - } - ); - passiveEffectCallback = callback; - } - isWorking = isCommitting$1 = !1; - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode); - committedExpirationTime = finishedWork.expirationTime; - finishedWork = finishedWork.childExpirationTime; - finishedWork = - finishedWork > committedExpirationTime - ? finishedWork - : committedExpirationTime; - 0 === finishedWork && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommit(root, finishedWork); + return didFlushEffects; } function completeUnitOfWork(workInProgress) { for (;;) { @@ -5858,16 +5479,15 @@ function completeUnitOfWork(workInProgress) { current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (instance) { var currentHostContext = requiredContext( - contextStackCursor$1.current - ), - internalInstanceHandle = current$$1; + contextStackCursor$1.current + ); current = nextReactTag; nextReactTag += 2; var viewConfig = ReactNativeViewConfigRegistry.get(type); - invariant( - "RCTView" !== type || !currentHostContext.isInAParentText, - "Nesting of within is not currently supported." - ); + if ("RCTView" === type && currentHostContext.isInAParentText) + throw ReactError( + "Nesting of within is not currently supported." + ); type = diffProperties( null, emptyObject, @@ -5879,46 +5499,47 @@ function completeUnitOfWork(workInProgress) { viewConfig.uiViewClassName, renderExpirationTime, type, - internalInstanceHandle + current$$1 ); instance = new ReactFabricHostComponent( current, viewConfig, - instance + instance, + current$$1 ); instance = { node: renderExpirationTime, canonical: instance }; appendAllChildren(instance, current$$1, !1, !1); current$$1.stateNode = instance; null !== current$$1.ref && (current$$1.effectTag |= 128); - } else - invariant( - null !== current$$1.stateNode, + } else if (null === current$$1.stateNode) + throw ReactError( "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: - current && null != current$$1.stateNode - ? updateHostText$1( - current, - current$$1, - current.memoizedProps, - instance - ) - : ("string" !== typeof instance && - invariant( - null !== current$$1.stateNode, - "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 = requiredContext( - contextStackCursor$1.current - )), - (current$$1.stateNode = createTextInstance( - instance, - current, - renderExpirationTime, - current$$1 - ))); + if (current && null != current$$1.stateNode) + updateHostText$1( + current, + current$$1, + current.memoizedProps, + instance + ); + else { + if ("string" !== typeof instance && null === current$$1.stateNode) + throw ReactError( + "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 = requiredContext( + contextStackCursor$1.current + ); + current$$1.stateNode = createTextInstance( + instance, + current, + renderExpirationTime, + current$$1 + ); + } break; case 11: break; @@ -5930,21 +5551,29 @@ function completeUnitOfWork(workInProgress) { break a; } instance = null !== instance; - renderExpirationTime = - null !== current && null !== current.memoizedState; + renderExpirationTime = !1; null !== current && - !instance && - renderExpirationTime && - ((current = current.child.sibling), - null !== current && - ((viewConfig = current$$1.firstEffect), - null !== viewConfig - ? ((current$$1.firstEffect = current), - (current.nextEffect = viewConfig)) - : ((current$$1.firstEffect = current$$1.lastEffect = current), - (current.nextEffect = null)), - (current.effectTag = 8))); - if (instance || renderExpirationTime) current$$1.effectTag |= 4; + ((viewConfig = current.memoizedState), + (renderExpirationTime = null !== viewConfig), + instance || + null === viewConfig || + ((viewConfig = viewConfig.fallbackExpirationTime), + viewConfig < mostRecentEventTime && + (mostRecentEventTime = viewConfig), + (current = current.child.sibling), + null !== current && + ((viewConfig = current$$1.firstEffect), + null !== viewConfig + ? ((current$$1.firstEffect = current), + (current.nextEffect = viewConfig)) + : ((current$$1.firstEffect = current$$1.lastEffect = current), + (current.nextEffect = null)), + (current.effectTag = 8)))); + instance && + !renderExpirationTime && + 0 !== (current$$1.mode & 1) && + (nextRenderDidSuspend = !0); + instance && (current$$1.effectTag |= 4); break; case 7: break; @@ -5968,9 +5597,12 @@ function completeUnitOfWork(workInProgress) { break; case 18: break; + case 19: + break; + case 20: + break; default: - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -6031,11 +5663,11 @@ function performUnitOfWork(workInProgress) { return next; } function renderRoot(root$jscomp$0, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); - flushPassiveEffects(); + if (isWorking) + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + flushPassiveEffects$1(); isWorking = !0; var previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = ContextOnlyDispatcher; @@ -6058,7 +5690,7 @@ function renderRoot(root$jscomp$0, isYieldy) { do { try { if (isYieldy) - for (; null !== nextUnitOfWork && !(frameDeadline <= now$1()); ) + for (; null !== nextUnitOfWork && !shouldYield$1(); ) nextUnitOfWork = performUnitOfWork(nextUnitOfWork); else for (; null !== nextUnitOfWork; ) @@ -6069,15 +5701,16 @@ function renderRoot(root$jscomp$0, isYieldy) { resetHooks(), null === nextUnitOfWork) ) - (didFatal = !0), onUncaughtError(thrownValue); + (didFatal = !0), onUncaughtError$1(thrownValue); else { - invariant( - null !== nextUnitOfWork, - "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." - ); + if (null === nextUnitOfWork) + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); var sourceFiber = nextUnitOfWork, returnFiber = sourceFiber.return; - if (null === returnFiber) (didFatal = !0), onUncaughtError(thrownValue); + if (null === returnFiber) + (didFatal = !0), onUncaughtError$1(thrownValue); else { a: { var root = root$jscomp$0, @@ -6094,38 +5727,13 @@ function renderRoot(root$jscomp$0, isYieldy) { ) { var thenable = value; value = returnFiber$jscomp$0; - var earliestTimeoutMs = -1, - startTimeMs = -1; do { - if (13 === value.tag) { - var current$$1 = value.alternate; - if ( - null !== current$$1 && - ((current$$1 = current$$1.memoizedState), - null !== current$$1) - ) { - startTimeMs = 10 * (1073741822 - current$$1.timedOutAt); - break; - } - current$$1 = value.pendingProps.maxDuration; - if ("number" === typeof current$$1) - if (0 >= current$$1) earliestTimeoutMs = 0; - else if ( - -1 === earliestTimeoutMs || - current$$1 < earliestTimeoutMs - ) - earliestTimeoutMs = current$$1; - } - value = value.return; - } while (null !== value); - value = returnFiber$jscomp$0; - do { - if ((current$$1 = 13 === value.tag)) - current$$1 = - void 0 === value.memoizedProps.fallback - ? !1 - : null === value.memoizedState; - if (current$$1) { + if ( + 13 === value.tag && + (void 0 === value.memoizedProps.fallback + ? 0 + : null === value.memoizedState) + ) { returnFiber$jscomp$0 = value.updateQueue; null === returnFiber$jscomp$0 ? ((returnFiber$jscomp$0 = new Set()), @@ -6144,41 +5752,25 @@ function renderRoot(root$jscomp$0, isYieldy) { sourceFiber$jscomp$0.expirationTime = 1073741823; break a; } - sourceFiber$jscomp$0 = root; - returnFiber$jscomp$0 = returnFiber; - var pingCache = sourceFiber$jscomp$0.pingCache; + sourceFiber$jscomp$0 = returnFiber; + var pingCache = root.pingCache; null === pingCache - ? ((pingCache = sourceFiber$jscomp$0.pingCache = new PossiblyWeakMap()), - (current$$1 = new Set()), - pingCache.set(thenable, current$$1)) - : ((current$$1 = pingCache.get(thenable)), - void 0 === current$$1 && - ((current$$1 = new Set()), - pingCache.set(thenable, current$$1))); - current$$1.has(returnFiber$jscomp$0) || - (current$$1.add(returnFiber$jscomp$0), - (sourceFiber$jscomp$0 = pingSuspendedRoot.bind( + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (returnFiber$jscomp$0 = new Set()), + pingCache.set(thenable, returnFiber$jscomp$0)) + : ((returnFiber$jscomp$0 = pingCache.get(thenable)), + void 0 === returnFiber$jscomp$0 && + ((returnFiber$jscomp$0 = new Set()), + pingCache.set(thenable, returnFiber$jscomp$0))); + returnFiber$jscomp$0.has(sourceFiber$jscomp$0) || + (returnFiber$jscomp$0.add(sourceFiber$jscomp$0), + (root = pingSuspendedRoot$$1.bind( null, - sourceFiber$jscomp$0, + root, thenable, - returnFiber$jscomp$0 + sourceFiber$jscomp$0 )), - thenable.then(sourceFiber$jscomp$0, sourceFiber$jscomp$0)); - -1 === earliestTimeoutMs - ? (root = 1073741823) - : (-1 === startTimeMs && - (startTimeMs = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root, - returnFiber - )) - - 5e3), - (root = startTimeMs + earliestTimeoutMs)); - 0 <= root && - nextLatestAbsoluteTimeoutMs < root && - (nextLatestAbsoluteTimeoutMs = root); + thenable.then(root, root)); value.effectTag |= 2048; value.expirationTime = returnFiber; break a; @@ -6205,25 +5797,24 @@ function renderRoot(root$jscomp$0, isYieldy) { break a; case 1: if ( - ((earliestTimeoutMs = value), - (startTimeMs = root.type), - (sourceFiber$jscomp$0 = root.stateNode), + ((sourceFiber$jscomp$0 = value), + (thenable = root.type), + (returnFiber$jscomp$0 = root.stateNode), 0 === (root.effectTag & 64) && ("function" === - typeof startTimeMs.getDerivedStateFromError || - (null !== sourceFiber$jscomp$0 && + typeof thenable.getDerivedStateFromError || + (null !== returnFiber$jscomp$0 && "function" === - typeof sourceFiber$jscomp$0.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - sourceFiber$jscomp$0 - ))))) + typeof returnFiber$jscomp$0.componentDidCatch && + !isAlreadyFailedLegacyErrorBoundary$$1( + returnFiber$jscomp$0 + )))) ) { root.effectTag |= 2048; root.expirationTime = returnFiber; returnFiber = createClassErrorUpdate( root, - earliestTimeoutMs, + sourceFiber$jscomp$0, returnFiber ); enqueueCapturedUpdate(root, returnFiber); @@ -6248,10 +5839,10 @@ function renderRoot(root$jscomp$0, isYieldy) { else if (null !== nextUnitOfWork) root$jscomp$0.finishedWork = null; else { previousDispatcher = root$jscomp$0.current.alternate; - invariant( - null !== previousDispatcher, - "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousDispatcher) + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); nextRoot = null; if (nextRenderDidError) { didFatal = root$jscomp$0.latestPendingTime; @@ -6286,19 +5877,11 @@ function renderRoot(root$jscomp$0, isYieldy) { return; } } - isYieldy && -1 !== nextLatestAbsoluteTimeoutMs + isYieldy && nextRenderDidSuspend && 1073741823 !== mostRecentEventTime ? (markSuspendedPriorityLevel(root$jscomp$0, expirationTime), (isYieldy = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root$jscomp$0, - expirationTime - ))), - isYieldy < nextLatestAbsoluteTimeoutMs && - (nextLatestAbsoluteTimeoutMs = isYieldy), - (isYieldy = 10 * (1073741822 - requestCurrentTime())), - (isYieldy = nextLatestAbsoluteTimeoutMs - isYieldy), + 10 * (1073741822 - mostRecentEventTime) - 5e3 + originalStartTimeMs), + (isYieldy = 150 - (now$1() - isYieldy)), onSuspend( root$jscomp$0, previousDispatcher, @@ -6310,7 +5893,7 @@ function renderRoot(root$jscomp$0, isYieldy) { (root$jscomp$0.finishedWork = previousDispatcher)); } } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { for (var fiber = sourceFiber.return; null !== fiber; ) { switch (fiber.tag) { case 1: @@ -6318,13 +5901,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( "function" === typeof fiber.type.getDerivedStateFromError || ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } break; @@ -6332,7 +5914,7 @@ function captureCommitPhaseError(sourceFiber, value) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createRootErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } fiber = fiber.return; @@ -6341,66 +5923,27 @@ function captureCommitPhaseError(sourceFiber, value) { ((fiber = createCapturedValue(value, sourceFiber)), (fiber = createRootErrorUpdate(sourceFiber, fiber, 1073741823)), enqueueUpdate(sourceFiber, fiber), - scheduleWork(sourceFiber, 1073741823)); + scheduleWork$1(sourceFiber, 1073741823)); } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(), - expirationTime = void 0; - if (0 === (fiber.mode & 1)) expirationTime = 1073741823; - else if (isWorking && !isCommitting$1) - expirationTime = nextRenderExpirationTime; - else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = 1073741823; - break; - case scheduler.unstable_UserBlockingPriority: - expirationTime = - 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1); - break; - case scheduler.unstable_NormalPriority: - expirationTime = - 1073741822 - 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = 1; - break; - default: - invariant( - !1, - "Unknown priority level. This error is likely caused by a bug in React. Please file an issue." - ); - } - null !== nextRoot && - expirationTime === nextRenderExpirationTime && - --expirationTime; - } - priorityLevel === scheduler.unstable_UserBlockingPriority && +function computeExpirationForFiber$1(currentTime, fiber) { + isWorking + ? (currentTime = isCommitting$1 ? 1073741823 : nextRenderExpirationTime) + : fiber.mode & 1 + ? ((currentTime = isBatchingInteractiveUpdates + ? 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1) + : 1073741822 - + 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1)), + null !== nextRoot && + currentTime === nextRenderExpirationTime && + --currentTime) + : (currentTime = 1073741823); + isBatchingInteractiveUpdates && (0 === lowestPriorityPendingInteractiveExpirationTime || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) && - (lowestPriorityPendingInteractiveExpirationTime = expirationTime); - return expirationTime; + currentTime < lowestPriorityPendingInteractiveExpirationTime) && + (lowestPriorityPendingInteractiveExpirationTime = currentTime); + return currentTime; } -function pingSuspendedRoot(root, thenable, pingTime) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(thenable); - if (null !== nextRoot && nextRenderExpirationTime === pingTime) - nextRoot = null; - else if ( - ((thenable = root.earliestSuspendedTime), - (pingCache = root.latestSuspendedTime), - 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) - ) { - root.didError = !1; - thenable = root.latestPingedTime; - if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; - findNextExpirationTimeToWorkOn(pingTime, root); - pingTime = root.expirationTime; - 0 !== pingTime && requestWork(root, pingTime); - } -} -function scheduleWork(fiber, expirationTime) { +function scheduleWorkToRoot(fiber, expirationTime) { fiber.expirationTime < expirationTime && (fiber.expirationTime = expirationTime); var alternate = fiber.alternate; @@ -6424,8 +5967,12 @@ function scheduleWork(fiber, expirationTime) { } node = node.return; } - fiber = root; - null !== fiber && + return root; +} +function scheduleWork$1(fiber, expirationTime) { + fiber = scheduleWorkToRoot(fiber, expirationTime); + if ( + null !== fiber && (!isWorking && 0 !== nextRenderExpirationTime && expirationTime > nextRenderExpirationTime && @@ -6433,12 +5980,12 @@ function scheduleWork(fiber, expirationTime) { markPendingPriorityLevel(fiber, expirationTime), (isWorking && !isCommitting$1 && nextRoot === fiber) || requestWork(fiber, fiber.expirationTime), - nestedUpdateCount > NESTED_UPDATE_LIMIT && - ((nestedUpdateCount = 0), - invariant( - !1, - "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." - ))); + nestedUpdateCount > NESTED_UPDATE_LIMIT) + ) + throw ((nestedUpdateCount = 0), + ReactError( + "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." + )); } var firstScheduledRoot = null, lastScheduledRoot = null, @@ -6452,6 +5999,7 @@ var firstScheduledRoot = null, unhandledError = null, isBatchingUpdates = !1, isUnbatchingUpdates = !1, + isBatchingInteractiveUpdates = !1, completedBatches = null, originalStartTimeMs = now$1(), currentRendererTime = 1073741822 - ((originalStartTimeMs / 10) | 0), @@ -6466,13 +6014,14 @@ function recomputeCurrentRendererTime() { function scheduleCallbackWithExpirationTime(root, expirationTime) { if (0 !== callbackExpirationTime) { if (expirationTime < callbackExpirationTime) return; - null !== callbackID && - ((root = callbackID), (scheduledCallback = null), clearTimeout(root)); + null !== callbackID && cancelCallback$1(callbackID); } callbackExpirationTime = expirationTime; root = now$1() - originalStartTimeMs; - callbackID = scheduleDeferredCallback$1(performAsyncWork, { - timeout: 10 * (1073741822 - expirationTime) - root + expirationTime = 10 * (1073741822 - expirationTime) - root; + root = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(root, performAsyncWork, { + timeout: expirationTime }); } function onSuspend( @@ -6483,7 +6032,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - 0 !== msUntilTimeout || frameDeadline <= now$1() + 0 !== msUntilTimeout || shouldYield$1() ? 0 < msUntilTimeout && (root.timeoutHandle = scheduleTimeout( onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), @@ -6497,20 +6046,16 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { root.finishedWork = finishedWork; recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." - ); + if (isRendering) + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); nextFlushedRoot = root; nextFlushedExpirationTime = suspendedExpirationTime; performWorkOnRoot(root, suspendedExpirationTime, !1); - performWork(1073741823, !1); + performWork(1073741823); } -function onCommit(root, expirationTime) { - root.expirationTime = expirationTime; - root.finishedWork = null; -} -function requestCurrentTime() { +function requestCurrentTime$1() { if (isRendering) return currentSchedulerTime; findHighestPriorityRoot(); if (0 === nextFlushedExpirationTime || 1 === nextFlushedExpirationTime) @@ -6535,7 +6080,7 @@ function requestWork(root, expirationTime) { (nextFlushedExpirationTime = 1073741823), performWorkOnRoot(root, 1073741823, !1)) : 1073741823 === expirationTime - ? performWork(1073741823, !1) + ? performWork(1073741823) : scheduleCallbackWithExpirationTime(root, expirationTime)); } function findHighestPriorityRoot() { @@ -6549,10 +6094,10 @@ function findHighestPriorityRoot() { ) { var remainingExpirationTime = root.expirationTime; if (0 === remainingExpirationTime) { - invariant( - null !== previousScheduledRoot && null !== lastScheduledRoot, - "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousScheduledRoot || null === lastScheduledRoot) + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); if (root === root.nextScheduledRoot) { firstScheduledRoot = lastScheduledRoot = root.nextScheduledRoot = null; break; @@ -6595,58 +6140,57 @@ function performAsyncWork(didTimeout) { didTimeout = didTimeout.nextScheduledRoot; } while (didTimeout !== firstScheduledRoot); } - performWork(0, !0); -} -function performWork(minExpirationTime, isYieldy) { findHighestPriorityRoot(); - if (isYieldy) - for ( + recomputeCurrentRendererTime(); + for ( + currentSchedulerTime = currentRendererTime; + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime); + + ) + performWorkOnRoot( + nextFlushedRoot, + nextFlushedExpirationTime, + currentRendererTime > nextFlushedExpirationTime + ), + findHighestPriorityRoot(), recomputeCurrentRendererTime(), - currentSchedulerTime = currentRendererTime; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime && - !( - frameDeadline <= now$1() && - currentRendererTime > nextFlushedExpirationTime - ); - - ) - performWorkOnRoot( - nextFlushedRoot, - nextFlushedExpirationTime, - currentRendererTime > nextFlushedExpirationTime - ), - findHighestPriorityRoot(), - recomputeCurrentRendererTime(), - (currentSchedulerTime = currentRendererTime); - else - for ( - ; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime; - - ) - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), - findHighestPriorityRoot(); - isYieldy && ((callbackExpirationTime = 0), (callbackID = null)); + (currentSchedulerTime = currentRendererTime); + callbackExpirationTime = 0; + callbackID = null; 0 !== nextFlushedExpirationTime && scheduleCallbackWithExpirationTime( nextFlushedRoot, nextFlushedExpirationTime ); + finishRendering(); +} +function performWork(minExpirationTime) { + for ( + findHighestPriorityRoot(); + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + minExpirationTime <= nextFlushedExpirationTime; + + ) + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), + findHighestPriorityRoot(); + 0 !== nextFlushedExpirationTime && + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + finishRendering(); +} +function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; - if (null !== completedBatches) - for ( - minExpirationTime = completedBatches, - completedBatches = null, - isYieldy = 0; - isYieldy < minExpirationTime.length; - isYieldy++ - ) { - var batch = minExpirationTime[isYieldy]; + if (null !== completedBatches) { + var batches = completedBatches; + completedBatches = null; + for (var i = 0; i < batches.length; i++) { + var batch = batches[i]; try { batch._onComplete(); } catch (error) { @@ -6654,17 +6198,18 @@ function performWork(minExpirationTime, isYieldy) { ((hasUnhandledError = !0), (unhandledError = error)); } } + } if (hasUnhandledError) - throw ((minExpirationTime = unhandledError), + throw ((batches = unhandledError), (unhandledError = null), (hasUnhandledError = !1), - minExpirationTime); + batches); } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); + if (isRendering) + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); isRendering = !0; if (isYieldy) { var _finishedWork = root.finishedWork; @@ -6677,7 +6222,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { renderRoot(root, isYieldy), (_finishedWork = root.finishedWork), null !== _finishedWork && - (frameDeadline <= now$1() + (shouldYield$1() ? (root.finishedWork = _finishedWork) : completeRoot$1(root, _finishedWork, expirationTime))); } else @@ -6694,7 +6239,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { completeRoot$1(root, _finishedWork, expirationTime)); isRendering = !1; } -function completeRoot$1(root, finishedWork, expirationTime) { +function completeRoot$1(root, finishedWork$jscomp$0, expirationTime) { var firstBatch = root.firstBatch; if ( null !== firstBatch && @@ -6704,7 +6249,7 @@ function completeRoot$1(root, finishedWork, expirationTime) { : completedBatches.push(firstBatch), firstBatch._defer) ) { - root.finishedWork = finishedWork; + root.finishedWork = finishedWork$jscomp$0; root.expirationTime = 0; return; } @@ -6712,46 +6257,455 @@ function completeRoot$1(root, finishedWork, expirationTime) { root === lastCommittedRootDuringThisBatch ? nestedUpdateCount++ : ((lastCommittedRootDuringThisBatch = root), (nestedUpdateCount = 0)); - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); + isCommitting$1 = isWorking = !0; + if (root.current === finishedWork$jscomp$0) + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); + expirationTime = root.pendingCommitExpirationTime; + if (0 === expirationTime) + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.pendingCommitExpirationTime = 0; + firstBatch = finishedWork$jscomp$0.expirationTime; + var childExpirationTimeBeforeCommit = + finishedWork$jscomp$0.childExpirationTime; + firstBatch = + childExpirationTimeBeforeCommit > firstBatch + ? childExpirationTimeBeforeCommit + : firstBatch; + root.didError = !1; + 0 === firstBatch + ? ((root.earliestPendingTime = 0), + (root.latestPendingTime = 0), + (root.earliestSuspendedTime = 0), + (root.latestSuspendedTime = 0), + (root.latestPingedTime = 0)) + : (firstBatch < root.latestPingedTime && (root.latestPingedTime = 0), + (childExpirationTimeBeforeCommit = root.latestPendingTime), + 0 !== childExpirationTimeBeforeCommit && + (childExpirationTimeBeforeCommit > firstBatch + ? (root.earliestPendingTime = root.latestPendingTime = 0) + : root.earliestPendingTime > firstBatch && + (root.earliestPendingTime = root.latestPendingTime)), + (childExpirationTimeBeforeCommit = root.earliestSuspendedTime), + 0 === childExpirationTimeBeforeCommit + ? markPendingPriorityLevel(root, firstBatch) + : firstBatch < root.latestSuspendedTime + ? ((root.earliestSuspendedTime = 0), + (root.latestSuspendedTime = 0), + (root.latestPingedTime = 0), + markPendingPriorityLevel(root, firstBatch)) + : firstBatch > childExpirationTimeBeforeCommit && + markPendingPriorityLevel(root, firstBatch)); + findNextExpirationTimeToWorkOn(0, root); + ReactCurrentOwner$2.current = null; + 1 < finishedWork$jscomp$0.effectTag + ? null !== finishedWork$jscomp$0.lastEffect + ? ((finishedWork$jscomp$0.lastEffect.nextEffect = finishedWork$jscomp$0), + (firstBatch = finishedWork$jscomp$0.firstEffect)) + : (firstBatch = finishedWork$jscomp$0) + : (firstBatch = finishedWork$jscomp$0.firstEffect); + for (nextEffect = firstBatch; null !== nextEffect; ) { + childExpirationTimeBeforeCommit = !1; + var error$jscomp$0 = void 0; + try { + for (; null !== nextEffect; ) { + if (nextEffect.effectTag & 256) { + var current$$1 = nextEffect.alternate, + finishedWork = nextEffect; + 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, + instance = finishedWork.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + case 20: + break; + default: + throw ReactError( + "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; + } + } catch (e) { + (childExpirationTimeBeforeCommit = !0), (error$jscomp$0 = e); } - ); + if (childExpirationTimeBeforeCommit) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + for (nextEffect = firstBatch; null !== nextEffect; ) { + current$$1 = !1; + prevProps = void 0; + try { + for (; 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; + null !== currentRef && + ("function" === typeof currentRef + ? currentRef(null) + : (currentRef.current = null)); + } + } + switch (effectTag & 14) { + case 2: + nextEffect.effectTag &= -3; + break; + case 6: + nextEffect.effectTag &= -3; + commitWork(nextEffect.alternate, nextEffect); + break; + case 4: + commitWork(nextEffect.alternate, nextEffect); + break; + case 8: + prevState = nextEffect; + a: for (snapshot = instance = prevState; ; ) { + childExpirationTimeBeforeCommit = snapshot; + "function" === typeof onCommitFiberUnmount && + onCommitFiberUnmount(childExpirationTimeBeforeCommit); + switch (childExpirationTimeBeforeCommit.tag) { + case 0: + case 11: + case 14: + case 15: + var updateQueue = childExpirationTimeBeforeCommit.updateQueue; + if (null !== updateQueue) { + var lastEffect = updateQueue.lastEffect; + if (null !== lastEffect) { + var firstEffect = lastEffect.next; + error$jscomp$0 = firstEffect; + do { + var destroy = error$jscomp$0.destroy; + if (void 0 !== destroy) { + finishedWork = childExpirationTimeBeforeCommit; + try { + destroy(); + } catch (error) { + captureCommitPhaseError$$1(finishedWork, error); + } + } + error$jscomp$0 = error$jscomp$0.next; + } while (error$jscomp$0 !== firstEffect); + } + } + break; + case 1: + safelyDetachRef(childExpirationTimeBeforeCommit); + var instance$jscomp$0 = + childExpirationTimeBeforeCommit.stateNode; + if ( + "function" === typeof instance$jscomp$0.componentWillUnmount + ) + try { + (instance$jscomp$0.props = + childExpirationTimeBeforeCommit.memoizedProps), + (instance$jscomp$0.state = + childExpirationTimeBeforeCommit.memoizedState), + instance$jscomp$0.componentWillUnmount(); + } catch (unmountError) { + captureCommitPhaseError$$1( + childExpirationTimeBeforeCommit, + unmountError + ); + } + break; + case 5: + safelyDetachRef(childExpirationTimeBeforeCommit); + break; + case 4: + FabricUIManager.createChildSet( + childExpirationTimeBeforeCommit.stateNode.containerInfo + ); + } + if (null !== snapshot.child) + (snapshot.child.return = snapshot), (snapshot = snapshot.child); + else { + if (snapshot === instance) break; + for (; null === snapshot.sibling; ) { + if (null === snapshot.return || snapshot.return === instance) + break a; + snapshot = snapshot.return; + } + snapshot.sibling.return = snapshot.return; + snapshot = snapshot.sibling; + } + } + prevState.return = null; + prevState.child = null; + prevState.memoizedState = null; + prevState.updateQueue = null; + var alternate = prevState.alternate; + null !== alternate && + ((alternate.return = null), + (alternate.child = null), + (alternate.memoizedState = null), + (alternate.updateQueue = null)); + } + nextEffect = nextEffect.nextEffect; + } + } catch (e) { + (current$$1 = !0), (prevProps = e); + } + if (current$$1) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, prevProps); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + root.current = finishedWork$jscomp$0; + for (nextEffect = firstBatch; null !== nextEffect; ) { + effectTag = !1; + current$$1$jscomp$0 = void 0; + try { + for ( + currentRef = root, updateQueue = expirationTime; + null !== nextEffect; + + ) { + var effectTag$jscomp$0 = nextEffect.effectTag; + if (effectTag$jscomp$0 & 36) { + var current$$1$jscomp$1 = nextEffect.alternate; + lastEffect = nextEffect; + firstEffect = updateQueue; + switch (lastEffect.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(16, 32, lastEffect); + break; + case 1: + var instance$jscomp$1 = lastEffect.stateNode; + if (lastEffect.effectTag & 4) + if (null === current$$1$jscomp$1) + instance$jscomp$1.componentDidMount(); + else { + var prevProps$jscomp$0 = + lastEffect.elementType === lastEffect.type + ? current$$1$jscomp$1.memoizedProps + : resolveDefaultProps( + lastEffect.type, + current$$1$jscomp$1.memoizedProps + ); + instance$jscomp$1.componentDidUpdate( + prevProps$jscomp$0, + current$$1$jscomp$1.memoizedState, + instance$jscomp$1.__reactInternalSnapshotBeforeUpdate + ); + } + var updateQueue$jscomp$0 = lastEffect.updateQueue; + null !== updateQueue$jscomp$0 && + commitUpdateQueue( + lastEffect, + updateQueue$jscomp$0, + instance$jscomp$1, + firstEffect + ); + break; + case 3: + var _updateQueue = lastEffect.updateQueue; + if (null !== _updateQueue) { + destroy = null; + if (null !== lastEffect.child) + switch (lastEffect.child.tag) { + case 5: + destroy = lastEffect.child.stateNode.canonical; + break; + case 1: + destroy = lastEffect.child.stateNode; + } + commitUpdateQueue( + lastEffect, + _updateQueue, + destroy, + firstEffect + ); + } + break; + case 5: + if (null === current$$1$jscomp$1 && lastEffect.effectTag & 4) + throw ReactError( + "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." + ); + break; + case 6: + break; + case 4: + break; + case 12: + break; + case 13: + case 17: + case 20: + break; + default: + throw ReactError( + "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) { + lastEffect = void 0; + var ref = nextEffect.ref; + if (null !== ref) { + var instance$jscomp$2 = nextEffect.stateNode; + switch (nextEffect.tag) { + case 5: + lastEffect = instance$jscomp$2.canonical; + break; + default: + lastEffect = instance$jscomp$2; + } + "function" === typeof ref + ? ref(lastEffect) + : (ref.current = lastEffect); + } + } + effectTag$jscomp$0 & 512 && + (rootWithPendingPassiveEffects = currentRef); + nextEffect = nextEffect.nextEffect; + } + } catch (e) { + (effectTag = !0), (current$$1$jscomp$0 = e); + } + if (effectTag) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, current$$1$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + null !== firstBatch && + null !== rootWithPendingPassiveEffects && + ((effectTag$jscomp$0 = commitPassiveEffects.bind(null, root, firstBatch)), + (passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + effectTag$jscomp$0 + )), + (passiveEffectCallback = effectTag$jscomp$0)); + isWorking = isCommitting$1 = !1; + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork$jscomp$0.stateNode); + effectTag$jscomp$0 = finishedWork$jscomp$0.expirationTime; + finishedWork$jscomp$0 = finishedWork$jscomp$0.childExpirationTime; + finishedWork$jscomp$0 = + finishedWork$jscomp$0 > effectTag$jscomp$0 + ? finishedWork$jscomp$0 + : effectTag$jscomp$0; + 0 === finishedWork$jscomp$0 && + (legacyErrorBoundariesThatAlreadyFailed = null); + root.expirationTime = finishedWork$jscomp$0; + root.finishedWork = null; } -function onUncaughtError(error) { - invariant( - null !== nextFlushedRoot, - "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." - ); +function onUncaughtError$1(error) { + if (null === nextFlushedRoot) + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); nextFlushedRoot.expirationTime = 0; hasUnhandledError || ((hasUnhandledError = !0), (unhandledError = error)); } +Scheduler_now(); +var requestCurrentTime$$1 = requestCurrentTime$1, + computeExpirationForFiber$$1 = computeExpirationForFiber$1, + captureCommitPhaseError$$1 = captureCommitPhaseError$1, + onUncaughtError$$1 = onUncaughtError$1; +function pingSuspendedRoot$$1(root, thenable, pingTime) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(thenable); + if (null !== nextRoot && nextRenderExpirationTime === pingTime) + nextRoot = null; + else if ( + ((thenable = root.earliestSuspendedTime), + (pingCache = root.latestSuspendedTime), + 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) + ) { + root.didError = !1; + thenable = root.latestPingedTime; + if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; + findNextExpirationTimeToWorkOn(pingTime, root); + pingTime = root.expirationTime; + 0 !== pingTime && requestWork(root, pingTime); + } +} +function resolveRetryThenable$$1(boundaryFiber, thenable) { + var retryCache = boundaryFiber.stateNode; + null !== retryCache && retryCache.delete(thenable); + thenable = requestCurrentTime$1(); + thenable = computeExpirationForFiber$1(thenable, boundaryFiber); + boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); + null !== boundaryFiber && + (markPendingPriorityLevel(boundaryFiber, thenable), + (thenable = boundaryFiber.expirationTime), + 0 !== thenable && requestWork(boundaryFiber, thenable)); +} +var isAlreadyFailedLegacyErrorBoundary$$1 = isAlreadyFailedLegacyErrorBoundary$1, + scheduleWork$$1 = scheduleWork$1, + flushPassiveEffects$$1 = flushPassiveEffects$1; function findHostInstance(component) { var fiber = component._reactInternalFiber; - void 0 === fiber && - ("function" === typeof component.render - ? invariant(!1, "Unable to find node on an unmounted component.") - : invariant( - !1, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - )); + if (void 0 === fiber) { + if ("function" === typeof component.render) + throw ReactError("Unable to find node on an unmounted component."); + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } component = findCurrentHostFiber(fiber); return null === component ? null : component.stateNode; } function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, - currentTime = requestCurrentTime(); - current$$1 = computeExpirationForFiber(currentTime, current$$1); + currentTime = requestCurrentTime$$1(); + current$$1 = computeExpirationForFiber$$1(currentTime, current$$1); currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { - invariant( - 2 === isFiberMountedImpl(parentComponent) && 1 === parentComponent.tag, - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); + if ( + 2 !== isFiberMountedImpl(parentComponent) || + 1 !== parentComponent.tag + ) + throw ReactError( + "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 { switch (parentContext.tag) { @@ -6768,11 +6722,9 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - invariant( - !1, + throw ReactError( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); - parentContext = void 0; } if (1 === parentComponent.tag) { var Component = parentComponent.type; @@ -6795,9 +6747,9 @@ function updateContainer(element, container, parentComponent, callback) { callback.payload = { element: element }; container = void 0 === container ? null : container; null !== container && (callback.callback = container); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(currentTime, callback); - scheduleWork(currentTime, current$$1); + scheduleWork$$1(currentTime, current$$1); return current$$1; } function createPortal(children, containerInfo, implementation) { @@ -6832,7 +6784,9 @@ function _inherits(subClass, superClass) { } var getInspectorDataForViewTag = void 0; getInspectorDataForViewTag = function() { - invariant(!1, "getInspectorDataForViewTag() is not available in production"); + throw ReactError( + "getInspectorDataForViewTag() is not available in production" + ); }; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -6855,13 +6809,13 @@ _batchedUpdatesImpl = function(fn, a) { } finally { (isBatchingUpdates = previousIsBatchingUpdates) || isRendering || - performWork(1073741823, !1); + performWork(1073741823); } }; _flushInteractiveUpdatesImpl = function() { isRendering || 0 === lowestPriorityPendingInteractiveExpirationTime || - (performWork(lowestPriorityPendingInteractiveExpirationTime, !1), + (performWork(lowestPriorityPendingInteractiveExpirationTime), (lowestPriorityPendingInteractiveExpirationTime = 0)); }; var roots = new Map(), @@ -6889,35 +6843,67 @@ var roots = new Map(), TextInputState.focusTextInput(findNodeHandle(this)); }; ReactNativeComponent.prototype.measure = function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }; ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -6940,48 +6926,14 @@ var roots = new Map(), })(React.Component); })(findNodeHandle, findHostInstance), findNodeHandle: findNodeHandle, - setNativeProps: function(handle, nativeProps) { - null != handle._nativeTag && - ((nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - handle.viewConfig.validAttributes - )), - null != nativeProps && - UIManager.updateView( - handle._nativeTag, - handle.viewConfig.uiViewClassName, - nativeProps - )); - }, + setNativeProps: function() {}, render: function(element, containerTag, callback) { var root = roots.get(containerTag); if (!root) { - root = createFiber(3, null, null, 0); - var root$jscomp$0 = { - current: root, - containerInfo: containerTag, - pendingChildren: null, - pingCache: null, - earliestPendingTime: 0, - latestPendingTime: 0, - earliestSuspendedTime: 0, - latestSuspendedTime: 0, - latestPingedTime: 0, - didError: !1, - pendingCommitExpirationTime: 0, - finishedWork: null, - timeoutHandle: -1, - context: null, - pendingContext: null, - hydrate: !1, - nextExpirationTimeToWorkOn: 0, - expirationTime: 0, - firstBatch: null, - nextScheduledRoot: null - }; - root = root.stateNode = root$jscomp$0; + root = new FiberRootNode(containerTag, !1); + var uninitializedFiber = createFiber(3, null, null, 0); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; roots.set(containerTag, root); } updateContainer(element, root, null, callback); @@ -7015,31 +6967,63 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }, setNativeProps: function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7072,7 +7056,10 @@ var roots = new Map(), var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: null, overrideProps: null, + setSuspenseHandler: null, + scheduleUpdate: null, currentDispatcherRef: ReactSharedInternals.ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { fiber = findCurrentHostFiber(fiber); @@ -7089,7 +7076,7 @@ var roots = new Map(), findFiberByHostInstance: getInstanceFromInstance, getInspectorDataForViewTag: getInspectorDataForViewTag, bundleType: 0, - version: "16.8.3", + version: "16.8.6", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/oss/ReactFabric-profiling.js b/Libraries/Renderer/oss/ReactFabric-profiling.js index ab75b165f51..91e31d61e55 100644 --- a/Libraries/Renderer/oss/ReactFabric-profiling.js +++ b/Libraries/Renderer/oss/ReactFabric-profiling.js @@ -19,30 +19,93 @@ var ReactNativeViewConfigRegistry = require("ReactNativeViewConfigRegistry"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), FabricUIManager = require("FabricUIManager"), + Scheduler = require("scheduler"), tracing = require("scheduler/tracing"), - scheduler = require("scheduler"), ExceptionsManager = require("ExceptionsManager"); -function invariant(condition, format, a, b, c, d, e, f) { - if (!condition) { - condition = void 0; - if (void 0 === format) - condition = Error( - "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." - ); - else { - var args = [a, b, c, d, e, f], - argIndex = 0; - condition = Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - condition.name = "Invariant Violation"; - } - condition.framesToPop = 1; - throw condition; - } +function ReactError(message) { + message = Error(message); + message.name = "Invariant Violation"; + return message; } +var eventPluginOrder = null, + namesToPlugins = {}; +function recomputePluginOrdering() { + if (eventPluginOrder) + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], + pluginIndex = eventPluginOrder.indexOf(pluginName); + if (!(-1 < pluginIndex)) + throw ReactError( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + if (!plugins[pluginIndex]) { + if (!pluginModule.extractEvents) + throw ReactError( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + plugins[pluginIndex] = pluginModule; + pluginIndex = pluginModule.eventTypes; + for (var eventName in pluginIndex) { + var JSCompiler_inline_result = void 0; + var dispatchConfig = pluginIndex[eventName], + pluginModule$jscomp$0 = pluginModule, + eventName$jscomp$0 = eventName; + if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." + ); + eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (JSCompiler_inline_result in phasedRegistrationNames) + phasedRegistrationNames.hasOwnProperty( + JSCompiler_inline_result + ) && + publishRegistrationName( + phasedRegistrationNames[JSCompiler_inline_result], + pluginModule$jscomp$0, + eventName$jscomp$0 + ); + JSCompiler_inline_result = !0; + } else + dispatchConfig.registrationName + ? (publishRegistrationName( + dispatchConfig.registrationName, + pluginModule$jscomp$0, + eventName$jscomp$0 + ), + (JSCompiler_inline_result = !0)) + : (JSCompiler_inline_result = !1); + if (!JSCompiler_inline_result) + throw ReactError( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + } + } +} +function publishRegistrationName(registrationName, pluginModule) { + if (registrationNameModules[registrationName]) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + registrationNameModules[registrationName] = pluginModule; +} +var plugins = [], + eventNameDispatchConfigs = {}, + registrationNameModules = {}; function invokeGuardedCallbackImpl(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { @@ -84,88 +147,13 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - invariant( - !1, + throw ReactError( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ), - (error = void 0); + ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } } -var eventPluginOrder = null, - namesToPlugins = {}; -function recomputePluginOrdering() { - if (eventPluginOrder) - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName], - pluginIndex = eventPluginOrder.indexOf(pluginName); - invariant( - -1 < pluginIndex, - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", - pluginName - ); - if (!plugins[pluginIndex]) { - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - pluginIndex = pluginModule.eventTypes; - for (var eventName in pluginIndex) { - var JSCompiler_inline_result = void 0; - var dispatchConfig = pluginIndex[eventName], - pluginModule$jscomp$0 = pluginModule, - eventName$jscomp$0 = eventName; - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0), - "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", - eventName$jscomp$0 - ); - eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (JSCompiler_inline_result in phasedRegistrationNames) - phasedRegistrationNames.hasOwnProperty( - JSCompiler_inline_result - ) && - publishRegistrationName( - phasedRegistrationNames[JSCompiler_inline_result], - pluginModule$jscomp$0, - eventName$jscomp$0 - ); - JSCompiler_inline_result = !0; - } else - dispatchConfig.registrationName - ? (publishRegistrationName( - dispatchConfig.registrationName, - pluginModule$jscomp$0, - eventName$jscomp$0 - ), - (JSCompiler_inline_result = !0)) - : (JSCompiler_inline_result = !1); - invariant( - JSCompiler_inline_result, - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } - } -} -function publishRegistrationName(registrationName, pluginModule) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; -} -var plugins = [], - eventNameDispatchConfigs = {}, - registrationNameModules = {}, - getFiberCurrentPropsFromNode = null, +var getFiberCurrentPropsFromNode = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { @@ -177,10 +165,8 @@ function executeDispatch(event, listener, inst) { function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + if (Array.isArray(dispatchListener)) + throw ReactError("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -191,10 +177,10 @@ function executeDirectDispatch(event) { return dispatchListener; } function accumulateInto(current, next) { - invariant( - null != next, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); if (null == current) return next; if (Array.isArray(current)) { if (Array.isArray(next)) return current.push.apply(current, next), current; @@ -228,10 +214,10 @@ function executeDispatchesAndReleaseTopLevel(e) { } var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ); + if (eventPluginOrder) + throw ReactError( + "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,15 +227,19 @@ var injection = { for (pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { var pluginModule = injectedNamesToPlugins[pluginName]; - (namesToPlugins.hasOwnProperty(pluginName) && - namesToPlugins[pluginName] === pluginModule) || - (invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", - pluginName - ), - (namesToPlugins[pluginName] = pluginModule), - (isOrderingDirty = !0)); + if ( + !namesToPlugins.hasOwnProperty(pluginName) || + namesToPlugins[pluginName] !== pluginModule + ) { + if (namesToPlugins[pluginName]) + throw ReactError( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = !0; + } } isOrderingDirty && recomputePluginOrdering(); } @@ -285,12 +275,14 @@ function getListener(inst, registrationName) { inst = !1; } if (inst) return null; - invariant( - !listener || "function" === typeof listener, - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + if (listener && "function" !== typeof listener) + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); return listener; } function getParent(inst) { @@ -451,10 +443,10 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { return new this(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { - invariant( - event instanceof this, - "Trying to release an event instance into a pool of a different type." - ); + if (!(event instanceof this)) + throw ReactError( + "Trying to release an event instance into a pool of a different type." + ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); } @@ -489,7 +481,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - invariant(null != _ref, "Touch object is missing identifier."); + if (null == _ref) throw ReactError("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -602,10 +594,10 @@ var ResponderTouchHistoryStore = { touchHistory: touchHistory }; function accumulate(current, next) { - invariant( - null != next, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); return null == current ? next : Array.isArray(current) @@ -970,11 +962,10 @@ var eventTypes$1 = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType], directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + if (!bubbleDispatchConfig && !directDispatchConfig) + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -1006,7 +997,7 @@ getFiberCurrentPropsFromNode = function(inst) { getInstanceFromNode = getInstanceFromInstance; getNodeFromInstance = function(inst) { inst = inst.stateNode.canonical._nativeTag; - invariant(inst, "All native instances should have a tag."); + if (!inst) throw ReactError("All native instances should have a tag."); return inst; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1038,6 +1029,15 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113, REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116, + REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 60117, + REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 60118, + REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 60119, MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1082,6 +1082,15 @@ function getComponentName(type) { case REACT_LAZY_TYPE: if ((type = 1 === type._status ? type._result : null)) return getComponentName(type); + break; + case REACT_EVENT_COMPONENT_TYPE: + type = type.displayName; + if (void 0 !== type) return type; + break; + case REACT_EVENT_TARGET_TYPE: + if (type.type === REACT_EVENT_TARGET_TOUCH_HIT) return "TouchHitTarget"; + type = type.displayName; + if (void 0 !== type) return type; } return null; } @@ -1096,80 +1105,83 @@ function isFiberMountedImpl(fiber) { return 3 === node.tag ? 2 : 3; } function assertIsMounted(fiber) { - invariant( - 2 === isFiberMountedImpl(fiber), - "Unable to find node on an unmounted component." - ); + if (2 !== isFiberMountedImpl(fiber)) + throw ReactError("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; - if (!alternate) - return ( - (alternate = isFiberMountedImpl(fiber)), - invariant( - 3 !== alternate, - "Unable to find node on an unmounted component." - ), - 1 === alternate ? null : fiber - ); + if (!alternate) { + alternate = isFiberMountedImpl(fiber); + if (3 === alternate) + throw ReactError("Unable to find node on an unmounted component."); + return 1 === alternate ? null : fiber; + } for (var a = fiber, b = alternate; ; ) { - var parentA = a.return, - parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) break; - if (parentA.child === parentB.child) { - for (var child = parentA.child; child; ) { - if (child === a) return assertIsMounted(parentA), fiber; - if (child === b) return assertIsMounted(parentA), alternate; - child = child.sibling; + var parentA = a.return; + if (null === parentA) break; + var parentB = parentA.alternate; + if (null === parentB) { + b = parentA.return; + if (null !== b) { + a = b; + continue; } - invariant(!1, "Unable to find node on an unmounted component."); + break; + } + if (parentA.child === parentB.child) { + for (parentB = parentA.child; parentB; ) { + if (parentB === a) return assertIsMounted(parentA), fiber; + if (parentB === b) return assertIsMounted(parentA), alternate; + parentB = parentB.sibling; + } + throw ReactError("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { - child = !1; - for (var _child = parentA.child; _child; ) { + for (var didFindChild = !1, _child = parentA.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentA; b = parentB; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentA; a = parentB; break; } _child = _child.sibling; } - if (!child) { + if (!didFindChild) { for (_child = parentB.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentB; b = parentA; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentB; a = parentA; break; } _child = _child.sibling; } - invariant( - child, - "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 ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ); + if (a.alternate !== b) + throw ReactError( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - invariant(3 === a.tag, "Unable to find node on an unmounted component."); + if (3 !== a.tag) + throw ReactError("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1417,37 +1429,13 @@ function diffProperties(updatePayload, prevProps, nextProps, validAttributes) { ))))); return updatePayload; } -var now$1 = - "object" === typeof performance && "function" === typeof performance.now - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }, - scheduledCallback = null, - frameDeadline = 0; -function setTimeoutCallback() { - frameDeadline = now$1() + 5; - var callback = scheduledCallback; - scheduledCallback = null; - null !== callback && callback(); -} -function scheduleDeferredCallback$1(callback) { - scheduledCallback = callback; - return setTimeout(setTimeoutCallback, 1); -} var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { - if ((target = getInstanceFromNode(target))) { - invariant( - !1, + if (getInstanceFromNode(target)) + throw ReactError( "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(target.stateNode); - null(target.stateNode, target.type, props); - } } function _batchedUpdatesImpl(fn, bookkeeping) { return fn(bookkeeping); @@ -1492,24 +1480,22 @@ function dispatchEvent(target, topLevelType, nativeEvent) { null !== events && (eventQueue = accumulateInto(eventQueue, events)); events = eventQueue; eventQueue = null; - if ( - events && - (forEachAccumulated(events, executeDispatchesAndReleaseTopLevel), - invariant( - !eventQueue, - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ), - hasRethrowError) - ) - throw ((events = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - events); + if (events) { + forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); + if (eventQueue) + throw ReactError( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + if (hasRethrowError) + throw ((events = rethrowError), + (hasRethrowError = !1), + (rethrowError = null), + events); + } }); } function shim$1() { - invariant( - !1, + throw ReactError( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } @@ -1517,12 +1503,18 @@ var nextReactTag = 2; FabricUIManager.registerEventHandler && FabricUIManager.registerEventHandler(dispatchEvent); var ReactFabricHostComponent = (function() { - function ReactFabricHostComponent(tag, viewConfig, props) { + function ReactFabricHostComponent( + tag, + viewConfig, + 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() { TextInputState.blurTextInput(this._nativeTag); @@ -1531,14 +1523,14 @@ var ReactFabricHostComponent = (function() { TextInputState.focusTextInput(this._nativeTag); }; ReactFabricHostComponent.prototype.measure = function(callback) { - UIManager.measure( - this._nativeTag, + FabricUIManager.measure( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; ReactFabricHostComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - this._nativeTag, + FabricUIManager.measureInWindow( + this._internalInstanceHandle.stateNode.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; @@ -1547,27 +1539,16 @@ var ReactFabricHostComponent = (function() { onSuccess, onFail ) { - UIManager.measureLayout( - this._nativeTag, - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); - }; - ReactFabricHostComponent.prototype.setNativeProps = function(nativeProps) { - nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - this.viewConfig.validAttributes - ); - null != nativeProps && - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - nativeProps + "number" !== typeof relativeToNativeNode && + relativeToNativeNode instanceof ReactFabricHostComponent && + FabricUIManager.measureLayout( + this._internalInstanceHandle.stateNode.node, + relativeToNativeNode._internalInstanceHandle.stateNode.node, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); }; + ReactFabricHostComponent.prototype.setNativeProps = function() {}; return ReactFabricHostComponent; })(); function createTextInstance( @@ -1576,10 +1557,10 @@ function createTextInstance( hostContext, internalInstanceHandle ) { - invariant( - hostContext.isInAParentText, - "Text strings must be rendered within a component." - ); + if (!hostContext.isInAParentText) + throw ReactError( + "Text strings must be rendered within a component." + ); hostContext = nextReactTag; nextReactTag += 2; return { @@ -1607,18 +1588,6 @@ function cloneHiddenInstance(instance) { canonical: instance.canonical }; } -function cloneUnhiddenInstance(instance, type, props) { - var viewConfig = instance.canonical.viewConfig; - type = instance.node; - var prevProps = Object.assign({}, props, { - style: [props.style, { display: "none" }] - }); - props = diffProperties(null, prevProps, props, viewConfig.validAttributes); - return { - node: FabricUIManager.cloneNodeWithNewProps(type, props), - canonical: instance.canonical - }; -} var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function getStackByFiberInDevAndProd(workInProgress) { var info = ""; @@ -1703,10 +1672,10 @@ function popTopLevelContextObject(fiber) { pop(contextStackCursor, fiber); } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); + if (contextStackCursor.current !== emptyContextObject) + throw ReactError( + "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); } @@ -1716,12 +1685,13 @@ function processChildContext(fiber, type, parentContext) { if ("function" !== typeof instance.getChildContext) return parentContext; instance = instance.getChildContext(); for (var contextKey in instance) - invariant( - contextKey in fiber, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + if (!(contextKey in fiber)) + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); return Object.assign({}, parentContext, instance); } function pushContextProvider(workInProgress) { @@ -1740,10 +1710,10 @@ function pushContextProvider(workInProgress) { } function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "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 ReactError( + "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)), (instance.__reactInternalMemoizedMergedChildContext = type), @@ -1778,6 +1748,7 @@ function injectInternals(internals) { } catch (err) {} return !0; } +var Scheduler_now = Scheduler.unstable_now; function FiberNode(tag, pendingProps, key, mode) { this.tag = tag; this.key = key; @@ -1908,11 +1879,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - invariant( - !1, - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", - null == type ? type : typeof type, - "" + throw ReactError( + "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); @@ -1954,6 +1924,24 @@ function createFiberFromPortal(portal, mode, expirationTime) { }; return mode; } +function FiberRootNode(containerInfo, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pingCache = this.pendingChildren = null; + this.pendingCommitExpirationTime = 0; + this.finishedWork = null; + this.timeoutHandle = -1; + this.pendingContext = this.context = null; + this.hydrate = hydrate; + this.firstBatch = null; + this.latestPingedTime = this.latestSuspendedTime = this.earliestSuspendedTime = this.latestPendingTime = this.earliestPendingTime = 0; + this.didError = !1; + this.expirationTime = this.nextExpirationTimeToWorkOn = 0; + this.nextScheduledRoot = null; + this.interactionThreadID = tracing.unstable_getThreadID(); + this.memoizedInteractions = new Set(); + this.pendingInteractionMap = new Map(); +} function markPendingPriorityLevel(root, expirationTime) { root.didError = !1; var earliestPendingTime = root.earliestPendingTime; @@ -2028,14 +2016,6 @@ function markSuspendedPriorityLevel(root, suspendedTime) { (root.latestSuspendedTime = suspendedTime); findNextExpirationTimeToWorkOn(suspendedTime, root); } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestPendingTime = root.earliestPendingTime; - root = root.earliestSuspendedTime; - earliestPendingTime > renderExpirationTime && - (renderExpirationTime = earliestPendingTime); - root > renderExpirationTime && (renderExpirationTime = root); - return renderExpirationTime; -} function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { var earliestSuspendedTime = root.earliestSuspendedTime, latestSuspendedTime = root.latestSuspendedTime, @@ -2150,37 +2130,37 @@ var classComponentUpdater = { }, enqueueSetState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueReplaceState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ReplaceState; update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueForceUpdate: function(inst, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ForceUpdate; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); } }; function checkShouldComponentUpdate( @@ -2305,17 +2285,19 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { element = element._owner; var inst = void 0; - element && - (invariant( - 1 === element.tag, - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ), - (inst = element.stateNode)); - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.", - returnFiber - ); + if (element) { + if (1 !== element.tag) + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + inst = element.stateNode; + } + if (!inst) + throw ReactError( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." + ); var stringRef = "" + returnFiber; if ( null !== current$$1 && @@ -2332,27 +2314,27 @@ function coerceRef(returnFiber, current$$1, element) { current$$1._stringRef = stringRef; return current$$1; } - invariant( - "string" === typeof returnFiber, - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) 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.", - returnFiber - ); + if ("string" !== typeof returnFiber) + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + if (!element._owner) + throw ReactError( + "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) { - "textarea" !== returnFiber.type && - invariant( - !1, - "Objects are not valid as a React child (found: %s).%s", - "[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - "" + if ("textarea" !== returnFiber.type) + throw ReactError( + "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) { @@ -2751,15 +2733,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) { var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - "function" === typeof iteratorFn, - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ); + if ("function" !== typeof iteratorFn) + throw ReactError( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); newChildrenIterable = iteratorFn.call(newChildrenIterable); - invariant( - null != newChildrenIterable, - "An iterable object provided no iterator." - ); + if (null == newChildrenIterable) + throw ReactError("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -2851,7 +2831,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) + if (isUnkeyedTopLevelFragment.key === isObject) { if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -2876,14 +2856,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren( - returnFiber, - isUnkeyedTopLevelFragment - ); - break; } - else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); + break; + } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -2919,7 +2895,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) + if (currentFirstChild.key === isUnkeyedTopLevelFragment) { if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -2939,11 +2915,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren(returnFiber, currentFirstChild); - break; } - else deleteChild(returnFiber, currentFirstChild); + deleteRemainingChildren(returnFiber, currentFirstChild); + break; + } else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -2997,12 +2972,11 @@ function ChildReconciler(shouldTrackSideEffects) { switch (returnFiber.tag) { case 1: case 0: - (expirationTime = returnFiber.type), - invariant( - !1, - "%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.", - expirationTime.displayName || expirationTime.name || "Component" - ); + throw ((returnFiber = returnFiber.type), + ReactError( + (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); }; @@ -3014,10 +2988,10 @@ var reconcileChildFibers = ChildReconciler(!0), contextFiberStackCursor = { current: NO_CONTEXT }, rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ); + if (c === NO_CONTEXT) + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); return c; } function pushHostContainer(fiber, nextRootInstance) { @@ -3054,15 +3028,7 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -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 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3077,9 +3043,8 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - invariant( - !1, - "Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)" + throw ReactError( + "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) { @@ -3127,10 +3092,10 @@ function renderWithHooks( remainingExpirationTime = 0; componentUpdateQueue = null; sideEffectTag = 0; - invariant( - !current, - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ); + if (current) + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); return workInProgress; } function resetHooks() { @@ -3164,10 +3129,8 @@ function updateWorkInProgressHook() { (currentHook = nextCurrentHook), (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { - invariant( - null !== nextCurrentHook, - "Rendered more hooks than during the previous render." - ); + if (null === nextCurrentHook) + throw ReactError("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3190,10 +3153,11 @@ function basicStateReducer(state, action) { function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; - invariant( - null !== queue, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + if (null === queue) + throw ReactError( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { var _dispatch = queue.dispatch; if (null !== renderPhaseUpdates) { @@ -3208,8 +3172,7 @@ function updateReducer(reducer) { is(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } } @@ -3235,10 +3198,12 @@ function updateReducer(reducer) { (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && (remainingExpirationTime = updateExpirationTime)) - : (newState = + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (newState = _update.eagerReducer === reducer ? _update.eagerState - : reducer(newState, _update.action)); + : reducer(newState, _update.action))); baseUpdate = _update; _update = _update.next; } while (null !== _update && _update !== _dispatch); @@ -3248,8 +3213,7 @@ function updateReducer(reducer) { hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; } return [hook.memoizedState, queue.dispatch]; } @@ -3285,7 +3249,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; } } @@ -3312,10 +3276,10 @@ function imperativeHandleEffect(create, ref) { } function mountDebugValue() {} function dispatchAction(fiber, queue, action) { - invariant( - 25 > numberOfReRenders, - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ); + if (!(25 > numberOfReRenders)) + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); var alternate = fiber.alternate; if ( fiber === currentlyRenderingFiber$1 || @@ -3340,9 +3304,9 @@ function dispatchAction(fiber, queue, action) { queue.next = fiber; } else { - flushPassiveEffects(); - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, fiber); + flushPassiveEffects$$1(); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: currentTime, action: action, @@ -3361,10 +3325,10 @@ function dispatchAction(fiber, queue, action) { if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && - ((alternate = queue.eagerReducer), null !== alternate) + ((alternate = queue.lastRenderedReducer), null !== alternate) ) try { - var currentState = queue.eagerState, + var currentState = queue.lastRenderedState, _eagerState = alternate(currentState, action); _update2.eagerReducer = alternate; _update2.eagerState = _eagerState; @@ -3372,7 +3336,7 @@ function dispatchAction(fiber, queue, action) { } catch (error) { } finally { } - scheduleWork(fiber, currentTime); + scheduleWork$$1(fiber, currentTime); } } var ContextOnlyDispatcher = { @@ -3399,19 +3363,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(); @@ -3427,8 +3391,8 @@ var ContextOnlyDispatcher = { reducer = hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialArg + lastRenderedReducer: reducer, + lastRenderedState: initialArg }; reducer = reducer.dispatch = dispatchAction.bind( null, @@ -3449,8 +3413,8 @@ var ContextOnlyDispatcher = { initialState = hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }; initialState = initialState.dispatch = dispatchAction.bind( null, @@ -3478,19 +3442,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(); @@ -3515,11 +3479,12 @@ var ContextOnlyDispatcher = { }, useDebugValue: mountDebugValue }, + now$2 = Scheduler.unstable_now, commitTime = 0, profilerStartTime = -1; function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (0 <= profilerStartTime) { - var elapsedTime = now$1() - profilerStartTime; + var elapsedTime = now$2() - profilerStartTime; fiber.actualDuration += elapsedTime; overrideBaseTime && (fiber.selfBaseDuration = elapsedTime); profilerStartTime = -1; @@ -4080,7 +4045,10 @@ function updateSuspenseComponent( nextState = null; var nextDidTimeout = !1; } else - (nextState = { timedOutAt: null !== nextState ? nextState.timedOutAt : 0 }), + (nextState = { + fallbackExpirationTime: + null !== nextState ? nextState.fallbackExpirationTime : 0 + }), (nextDidTimeout = !0), (workInProgress.effectTag &= -65); if (null === current$$1) @@ -4210,10 +4178,8 @@ function bailoutOnAlreadyFinishedWork( (workInProgress.contextDependencies = current$$1.contextDependencies); profilerStartTime = -1; if (workInProgress.childExpirationTime < renderExpirationTime) return null; - invariant( - null === current$$1 || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + if (null !== current$$1 && workInProgress.child !== current$$1.child) + throw ReactError("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4381,59 +4347,57 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ((current$$1.alternate = null), (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); - hasContext = workInProgress.pendingProps; - current$$1 = readLazyComponentType(context); - workInProgress.type = current$$1; - context = workInProgress.tag = resolveLazyComponentTag(current$$1); - hasContext = resolveDefaultProps(current$$1, hasContext); - getDerivedStateFromProps = void 0; - switch (context) { + current$$1 = workInProgress.pendingProps; + context = readLazyComponentType(context); + workInProgress.type = context; + hasContext = workInProgress.tag = resolveLazyComponentTag(context); + current$$1 = resolveDefaultProps(context, current$$1); + switch (hasContext) { case 0: - getDerivedStateFromProps = updateFunctionComponent( + workInProgress = updateFunctionComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 1: - getDerivedStateFromProps = updateClassComponent( + workInProgress = updateClassComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 11: - getDerivedStateFromProps = updateForwardRef( + workInProgress = updateForwardRef( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 14: - getDerivedStateFromProps = updateMemoComponent( + workInProgress = updateMemoComponent( null, workInProgress, - current$$1, - resolveDefaultProps(current$$1.type, hasContext), + context, + resolveDefaultProps(context.type, current$$1), updateExpirationTime, renderExpirationTime ); break; default: - invariant( - !1, - "Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s", - current$$1, - "" + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + context + + ". Lazy element type must resolve to a class or function." ); } - return getDerivedStateFromProps; + return workInProgress; case 0: return ( (updateExpirationTime = workInProgress.type), @@ -4467,38 +4431,36 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); case 3: - return ( - pushHostRootContext(workInProgress), - (updateExpirationTime = workInProgress.updateQueue), - invariant( - null !== updateExpirationTime, + pushHostRootContext(workInProgress); + updateExpirationTime = workInProgress.updateQueue; + if (null === updateExpirationTime) + throw ReactError( "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." - ), - (context = workInProgress.memoizedState), - (context = null !== context ? context.element : null), - processUpdateQueue( - workInProgress, - updateExpirationTime, - workInProgress.pendingProps, - null, - renderExpirationTime - ), - (updateExpirationTime = workInProgress.memoizedState.element), - updateExpirationTime === context - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current$$1, - workInProgress, - renderExpirationTime - )) - : (reconcileChildren( - current$$1, - workInProgress, - updateExpirationTime, - renderExpirationTime - ), - (workInProgress = workInProgress.child)), - workInProgress + ); + context = workInProgress.memoizedState; + context = null !== context ? context.element : null; + processUpdateQueue( + workInProgress, + updateExpirationTime, + workInProgress.pendingProps, + null, + renderExpirationTime ); + updateExpirationTime = workInProgress.memoizedState.element; + updateExpirationTime === context + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current$$1, + workInProgress, + renderExpirationTime + )) + : (reconcileChildren( + current$$1, + workInProgress, + updateExpirationTime, + renderExpirationTime + ), + (workInProgress = workInProgress.child)); + return workInProgress; case 5: return ( pushHostContext(workInProgress), @@ -4511,8 +4473,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - (workInProgress = workInProgress.child), - workInProgress + workInProgress.child ); case 6: return ( @@ -4791,8 +4752,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); } - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -4828,17 +4788,17 @@ function readContext(context, observedBits) { if ("number" !== typeof observedBits || 1073741823 === observedBits) (lastContextWithAllBitsObserved = context), (observedBits = 1073741823); observedBits = { context: context, observedBits: observedBits, next: null }; - null === lastContextDependency - ? (invariant( - null !== currentlyRenderingFiber, + if (null === lastContextDependency) { + if (null === currentlyRenderingFiber) + throw ReactError( "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.contextDependencies = { - first: observedBits, - expirationTime: 0 - })) - : (lastContextDependency = lastContextDependency.next = observedBits); + ); + lastContextDependency = observedBits; + currentlyRenderingFiber.contextDependencies = { + first: observedBits, + expirationTime: 0 + }; + } else lastContextDependency = lastContextDependency.next = observedBits; } return context._currentValue2; } @@ -4991,7 +4951,9 @@ function processUpdateQueue( ((newFirstUpdate = update), (newBaseState = resultState)), newExpirationTime < updateExpirationTime && (newExpirationTime = updateExpirationTime)) - : ((resultState = getStateFromUpdate( + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (resultState = getStateFromUpdate( workInProgress, queue, update, @@ -5064,11 +5026,11 @@ function commitUpdateEffects(effect, instance) { if (null !== _callback3) { effect.callback = null; var context = instance; - invariant( - "function" === typeof _callback3, - "Invalid argument passed as callback. Expected a function. Instead received: %s", - _callback3 - ); + if ("function" !== typeof _callback3) + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + _callback3 + ); _callback3.call(context); } effect = effect.nextEffect; @@ -5092,39 +5054,41 @@ appendAllChildren = function( isHidden ) { for (var node = workInProgress.child; null !== node; ) { - a: if (5 === node.tag) { + if (5 === node.tag) { var instance = node.stateNode; - if (needsVisibilityToggle) { - var props = node.memoizedProps, - type = node.type; - instance = isHidden - ? cloneHiddenInstance(instance, type, props, node) - : cloneUnhiddenInstance(instance, type, props, node); - node.stateNode = instance; - } + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance( + instance, + node.type, + node.memoizedProps, + node + )); FabricUIManager.appendChild(parent.node, instance.node); } else if (6 === node.tag) { instance = node.stateNode; - if (needsVisibilityToggle) { - instance = node.memoizedProps; - props = requiredContext(rootInstanceStackCursor.current); - type = requiredContext(contextStackCursor$1.current); - if (isHidden) throw Error("Not yet implemented."); - instance = createTextInstance(instance, props, type, workInProgress); - node.stateNode = instance; - } + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); FabricUIManager.appendChild(parent.node, instance.node); } else if (4 !== node.tag) { if ( 13 === node.tag && - ((props = node.alternate), - null !== props && - ((instance = null !== node.memoizedState), - (null !== props.memoizedState) !== instance)) + 0 !== (node.effectTag & 4) && + (instance = null !== node.memoizedState) ) { - props = instance ? node.child : node; - null !== props && appendAllChildren(parent, props, !0, instance); - break a; + var primaryChildParent = node.child; + if ( + null !== primaryChildParent && + (null !== primaryChildParent.child && + ((primaryChildParent.child.return = primaryChildParent), + appendAllChildren(parent, primaryChildParent, !0, instance)), + (instance = primaryChildParent.sibling), + null !== instance) + ) { + instance.return = node; + node = instance; + continue; + } } if (null !== node.child) { node.child.return = node; @@ -5148,40 +5112,46 @@ function appendAllChildrenToContainer( isHidden ) { for (var node = workInProgress.child; null !== node; ) { - a: if (5 === node.tag) { + if (5 === node.tag) { var instance = node.stateNode; - if (needsVisibilityToggle) { - var props = node.memoizedProps, - type = node.type; - instance = isHidden - ? cloneHiddenInstance(instance, type, props, node) - : cloneUnhiddenInstance(instance, type, props, node); - node.stateNode = instance; - } + needsVisibilityToggle && + isHidden && + (instance = cloneHiddenInstance( + instance, + node.type, + node.memoizedProps, + node + )); FabricUIManager.appendChildToSet(containerChildSet, instance.node); } else if (6 === node.tag) { instance = node.stateNode; - if (needsVisibilityToggle) { - instance = node.memoizedProps; - props = requiredContext(rootInstanceStackCursor.current); - type = requiredContext(contextStackCursor$1.current); - if (isHidden) throw Error("Not yet implemented."); - instance = createTextInstance(instance, props, type, workInProgress); - node.stateNode = instance; - } + if (needsVisibilityToggle && isHidden) + throw Error("Not yet implemented."); FabricUIManager.appendChildToSet(containerChildSet, instance.node); } else if (4 !== node.tag) { if ( 13 === node.tag && - ((props = node.alternate), - null !== props && - ((instance = null !== node.memoizedState), - (null !== props.memoizedState) !== instance)) + 0 !== (node.effectTag & 4) && + (instance = null !== node.memoizedState) ) { - props = instance ? node.child : node; - null !== props && - appendAllChildrenToContainer(containerChildSet, props, !0, instance); - break a; + var primaryChildParent = node.child; + if ( + null !== primaryChildParent && + (null !== primaryChildParent.child && + ((primaryChildParent.child.return = primaryChildParent), + appendAllChildrenToContainer( + containerChildSet, + primaryChildParent, + !0, + instance + )), + (instance = primaryChildParent.sibling), + null !== instance) + ) { + instance.return = node; + node = instance; + continue; + } } if (null !== node.child) { node.child.return = node; @@ -5284,6 +5254,7 @@ function logCapturedError(capturedError) { : Error("Unspecified error at:" + componentStack); ExceptionsManager.handleException(error, !1); } +var PossiblyWeakSet$1 = "function" === typeof WeakSet ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source, stack = errorInfo.stack; @@ -5320,22 +5291,56 @@ function safelyDetachRef(current$$1) { try { ref(null); } catch (refError) { - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } 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: + case 20: + break; + default: + throw ReactError( + "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); @@ -5347,26 +5352,48 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); + return; + case 12: + return; + case 13: + commitSuspenseComponent(finishedWork); return; } switch (finishedWork.tag) { case 1: - break; case 5: - break; case 6: + case 20: break; case 3: case 4: break; default: - invariant( - !1, + throw ReactError( "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; + null !== newState && + 0 === newState.fallbackExpirationTime && + (newState.fallbackExpirationTime = requestCurrentTime$$1() - 500); + newState = finishedWork.updateQueue; + if (null !== newState) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + newState.forEach(function(thenable) { + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + retry = tracing.unstable_wrap(retry); + retryCache.has(thenable) || + (retryCache.add(thenable), thenable.then(retry, retry)); + }); + } +} var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime = createUpdate(expirationTime); @@ -5374,7 +5401,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime.payload = { element: null }; var error = errorInfo.value; expirationTime.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return expirationTime; @@ -5422,34 +5449,13 @@ function throwException( ) { var thenable = value; value = returnFiber; - var earliestTimeoutMs = -1, - startTimeMs = -1; do { - if (13 === value.tag) { - var current$$1 = value.alternate; - if ( - null !== current$$1 && - ((current$$1 = current$$1.memoizedState), null !== current$$1) - ) { - startTimeMs = 10 * (1073741822 - current$$1.timedOutAt); - break; - } - current$$1 = value.pendingProps.maxDuration; - if ("number" === typeof current$$1) - if (0 >= current$$1) earliestTimeoutMs = 0; - else if (-1 === earliestTimeoutMs || current$$1 < earliestTimeoutMs) - earliestTimeoutMs = current$$1; - } - value = value.return; - } while (null !== value); - value = returnFiber; - do { - if ((current$$1 = 13 === value.tag)) - current$$1 = - void 0 === value.memoizedProps.fallback - ? !1 - : null === value.memoizedState; - if (current$$1) { + if ( + 13 === value.tag && + (void 0 === value.memoizedProps.fallback + ? 0 + : null === value.memoizedState) + ) { returnFiber = value.updateQueue; null === returnFiber ? ((returnFiber = new Set()), @@ -5469,40 +5475,26 @@ function throwException( return; } sourceFiber = root; - returnFiber = renderExpirationTime; + root = renderExpirationTime; var pingCache = sourceFiber.pingCache; null === pingCache ? ((pingCache = sourceFiber.pingCache = new PossiblyWeakMap()), - (current$$1 = new Set()), - pingCache.set(thenable, current$$1)) - : ((current$$1 = pingCache.get(thenable)), - void 0 === current$$1 && - ((current$$1 = new Set()), pingCache.set(thenable, current$$1))); - current$$1.has(returnFiber) || - (current$$1.add(returnFiber), - (sourceFiber = pingSuspendedRoot.bind( + (returnFiber = new Set()), + pingCache.set(thenable, returnFiber)) + : ((returnFiber = pingCache.get(thenable)), + void 0 === returnFiber && + ((returnFiber = new Set()), + pingCache.set(thenable, returnFiber))); + returnFiber.has(root) || + (returnFiber.add(root), + (sourceFiber = pingSuspendedRoot$$1.bind( null, sourceFiber, thenable, - returnFiber + root )), (sourceFiber = tracing.unstable_wrap(sourceFiber)), thenable.then(sourceFiber, sourceFiber)); - -1 === earliestTimeoutMs - ? (root = 1073741823) - : (-1 === startTimeMs && - (startTimeMs = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root, - renderExpirationTime - )) - - 5e3), - (root = startTimeMs + earliestTimeoutMs)); - 0 <= root && - nextLatestAbsoluteTimeoutMs < root && - (nextLatestAbsoluteTimeoutMs = root); value.effectTag |= 2048; value.expirationTime = renderExpirationTime; return; @@ -5517,44 +5509,43 @@ function throwException( } nextRenderDidError = !0; value = createCapturedValue(value, sourceFiber); - root = returnFiber; + sourceFiber = returnFiber; do { - switch (root.tag) { + switch (sourceFiber.tag) { case 3: - root.effectTag |= 2048; - root.expirationTime = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.expirationTime = renderExpirationTime; renderExpirationTime = createRootErrorUpdate( - root, + sourceFiber, value, renderExpirationTime ); - enqueueCapturedUpdate(root, renderExpirationTime); + enqueueCapturedUpdate(sourceFiber, renderExpirationTime); return; case 1: if ( - ((earliestTimeoutMs = value), - (startTimeMs = root.type), - (sourceFiber = root.stateNode), - 0 === (root.effectTag & 64) && - ("function" === typeof startTimeMs.getDerivedStateFromError || - (null !== sourceFiber && - "function" === typeof sourceFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(sourceFiber))))) + ((thenable = value), + (root = sourceFiber.type), + (returnFiber = sourceFiber.stateNode), + 0 === (sourceFiber.effectTag & 64) && + ("function" === typeof root.getDerivedStateFromError || + (null !== returnFiber && + "function" === typeof returnFiber.componentDidCatch && + !isAlreadyFailedLegacyErrorBoundary$$1(returnFiber)))) ) { - root.effectTag |= 2048; - root.expirationTime = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.expirationTime = renderExpirationTime; renderExpirationTime = createClassErrorUpdate( - root, - earliestTimeoutMs, + sourceFiber, + thenable, renderExpirationTime ); - enqueueCapturedUpdate(root, renderExpirationTime); + enqueueCapturedUpdate(sourceFiber, renderExpirationTime); return; } } - root = root.return; - } while (null !== root); + sourceFiber = sourceFiber.return; + } while (null !== sourceFiber); } function unwindWork(workInProgress) { switch (workInProgress.tag) { @@ -5566,17 +5557,15 @@ function unwindWork(workInProgress) { workInProgress) : null; case 3: - return ( - popHostContainer(workInProgress), - popTopLevelContextObject(workInProgress), - (effectTag = workInProgress.effectTag), - invariant( - 0 === (effectTag & 64), + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + effectTag = workInProgress.effectTag; + if (0 !== (effectTag & 64)) + throw ReactError( "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 - ); + ); + workInProgress.effectTag = (effectTag & -2049) | 64; + return workInProgress; case 5: return popHostContext(workInProgress), null; case 13: @@ -5593,22 +5582,34 @@ function unwindWork(workInProgress) { return popHostContainer(workInProgress), null; case 10: return popProvider(workInProgress), null; + case 19: + case 20: + return null; default: return null; } } -var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback, + cancelCallback$1 = Scheduler.unstable_cancelCallback, + shouldYield$1 = Scheduler.unstable_shouldYield, + now$1 = Scheduler.unstable_now, + getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel, + NormalPriority$1 = Scheduler.unstable_NormalPriority, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; -invariant( - null != tracing.__interactionsRef && - null != tracing.__interactionsRef.current, - "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 ( + null == tracing.__interactionsRef || + null == tracing.__interactionsRef.current +) + throw ReactError( + "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 isWorking = !1, nextUnitOfWork = null, nextRoot = null, nextRenderExpirationTime = 0, - nextLatestAbsoluteTimeoutMs = -1, + mostRecentEventTime = 1073741823, + nextRenderDidSuspend = !1, nextRenderDidError = !1, nextEffect = null, isCommitting$1 = !1, @@ -5649,8 +5650,8 @@ function resetStack() { } nextRoot = null; nextRenderExpirationTime = 0; - nextLatestAbsoluteTimeoutMs = -1; - nextRenderDidError = !1; + mostRecentEventTime = 1073741823; + nextRenderDidError = nextRenderDidSuspend = !1; nextUnitOfWork = null; } function commitAllHostEffects() { @@ -5700,7 +5701,7 @@ function commitAllHostEffects() { try { destroy(); } catch (error) { - captureCommitPhaseError(current$$1$jscomp$1, error); + captureCommitPhaseError$$1(current$$1$jscomp$1, error); } } effect = effect.next; @@ -5716,7 +5717,7 @@ function commitAllHostEffects() { (updateQueue.state = current$$1$jscomp$0.memoizedState), updateQueue.componentWillUnmount(); } catch (unmountError) { - captureCommitPhaseError(current$$1$jscomp$0, unmountError); + captureCommitPhaseError$$1(current$$1$jscomp$0, unmountError); } break; case 5: @@ -5753,48 +5754,6 @@ function commitAllHostEffects() { nextEffect = nextEffect.nextEffect; } } -function commitBeforeMutationLifecycles() { - for (; null !== nextEffect; ) { - if (nextEffect.effectTag & 256) - a: { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); - break a; - 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 a; - case 3: - case 5: - case 6: - case 4: - case 17: - break a; - default: - invariant( - !1, - "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; - } -} function commitAllLifeCycles( finishedRoot$jscomp$0, committedExpirationTime$jscomp$0 @@ -5810,7 +5769,7 @@ function commitAllLifeCycles( case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, finishedWork); + commitHookEffectList(16, 32, finishedWork); break; case 1: finishedRoot = finishedWork.stateNode; @@ -5860,10 +5819,8 @@ function commitAllLifeCycles( } break; case 5: - null === current$$1 && - finishedWork.effectTag & 4 && - invariant( - !1, + if (null === current$$1 && finishedWork.effectTag & 4) + throw ReactError( "The current renderer does not support mutation. This error is likely caused by a bug in React. Please file an issue." ); break; @@ -5884,12 +5841,11 @@ function commitAllLifeCycles( ); break; case 13: - break; case 17: + case 20: break; default: - invariant( - !1, + throw ReactError( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." ); } @@ -5921,39 +5877,44 @@ function commitPassiveEffects(root, firstEffect) { error = void 0; try { var finishedWork = firstEffect; - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork); - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork); + commitHookEffectList(0, 64, finishedWork); } catch (e) { (didError = !0), (error = e); } - didError && captureCommitPhaseError(firstEffect, error); + didError && captureCommitPhaseError$1(firstEffect, error); } firstEffect = firstEffect.nextEffect; } while (null !== firstEffect); isRendering = previousIsRendering; previousIsRendering = root.expirationTime; 0 !== previousIsRendering && requestWork(root, previousIsRendering); - isBatchingUpdates || isRendering || performWork(1073741823, !1); + isBatchingUpdates || isRendering || performWork(1073741823); } -function flushPassiveEffects() { - if (null !== passiveEffectCallbackHandle) { - var callbackID = passiveEffectCallbackHandle; - scheduledCallback = null; - clearTimeout(callbackID); - } +function isAlreadyFailedLegacyErrorBoundary$1(instance) { + return ( + null !== legacyErrorBoundariesThatAlreadyFailed && + legacyErrorBoundariesThatAlreadyFailed.has(instance) + ); +} +function flushPassiveEffects$1() { + var didFlushEffects = null !== passiveEffectCallback; + null !== passiveEffectCallbackHandle && + cancelCallback$1(passiveEffectCallbackHandle); null !== passiveEffectCallback && passiveEffectCallback(); + return didFlushEffects; } function commitRoot(root, finishedWork) { isCommitting$1 = isWorking = !0; - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." - ); + if (root.current === finishedWork) + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - 0 !== committedExpirationTime, - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); + if (0 === committedExpirationTime) + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); root.pendingCommitExpirationTime = 0; var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; @@ -5978,19 +5939,23 @@ function commitRoot(root, finishedWork) { var didError = !1, error$jscomp$0 = void 0; try { - commitBeforeMutationLifecycles(); + for (; null !== nextEffect; ) + nextEffect.effectTag & 256 && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect), + (nextEffect = nextEffect.nextEffect); } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } - commitTime = now$1(); + commitTime = now$2(); for (nextEffect = childExpirationTimeBeforeCommit; null !== nextEffect; ) { didError = !1; error$jscomp$0 = void 0; @@ -5999,13 +5964,14 @@ function commitRoot(root, finishedWork) { } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } root.current = finishedWork; for (nextEffect = childExpirationTimeBeforeCommit; null !== nextEffect; ) { @@ -6016,32 +5982,30 @@ function commitRoot(root, finishedWork) { } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } - if ( - null !== childExpirationTimeBeforeCommit && - null !== rootWithPendingPassiveEffects - ) { - var callback = commitPassiveEffects.bind( + null !== childExpirationTimeBeforeCommit && + null !== rootWithPendingPassiveEffects && + ((childExpirationTimeBeforeCommit = commitPassiveEffects.bind( null, root, childExpirationTimeBeforeCommit - ); - callback = tracing.unstable_wrap(callback); - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return scheduleDeferredCallback$1(callback); - } - ); - passiveEffectCallback = callback; - } + )), + (childExpirationTimeBeforeCommit = tracing.unstable_wrap( + childExpirationTimeBeforeCommit + )), + (passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + childExpirationTimeBeforeCommit + )), + (passiveEffectCallback = childExpirationTimeBeforeCommit)); isWorking = isCommitting$1 = !1; "function" === typeof onCommitFiberRoot && onCommitFiberRoot(finishedWork.stateNode); @@ -6097,8 +6061,8 @@ function completeUnitOfWork(workInProgress) { nextUnitOfWork = workInProgress; if (workInProgress.mode & 4) { var fiber = workInProgress; - profilerStartTime = now$1(); - 0 > fiber.actualStartTime && (fiber.actualStartTime = now$1()); + profilerStartTime = now$2(); + 0 > fiber.actualStartTime && (fiber.actualStartTime = now$2()); } a: { var current = current$$1; @@ -6144,16 +6108,15 @@ function completeUnitOfWork(workInProgress) { current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (fiber) { var currentHostContext = requiredContext( - contextStackCursor$1.current - ), - internalInstanceHandle = current$$1; + contextStackCursor$1.current + ); current = nextReactTag; nextReactTag += 2; var viewConfig = ReactNativeViewConfigRegistry.get(type); - invariant( - "RCTView" !== type || !currentHostContext.isInAParentText, - "Nesting of within is not currently supported." - ); + if ("RCTView" === type && currentHostContext.isInAParentText) + throw ReactError( + "Nesting of within is not currently supported." + ); type = diffProperties( null, emptyObject, @@ -6165,42 +6128,47 @@ function completeUnitOfWork(workInProgress) { viewConfig.uiViewClassName, renderExpirationTime, type, - internalInstanceHandle + current$$1 + ); + fiber = new ReactFabricHostComponent( + current, + viewConfig, + fiber, + current$$1 ); - fiber = new ReactFabricHostComponent(current, viewConfig, fiber); fiber = { node: renderExpirationTime, canonical: fiber }; appendAllChildren(fiber, current$$1, !1, !1); current$$1.stateNode = fiber; null !== current$$1.ref && (current$$1.effectTag |= 128); - } else - invariant( - null !== current$$1.stateNode, + } else if (null === current$$1.stateNode) + throw ReactError( "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: - current && null != current$$1.stateNode - ? updateHostText$1( - current, - current$$1, - current.memoizedProps, - fiber - ) - : ("string" !== typeof fiber && - invariant( - null !== current$$1.stateNode, - "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 = requiredContext( - contextStackCursor$1.current - )), - (current$$1.stateNode = createTextInstance( - fiber, - current, - renderExpirationTime, - current$$1 - ))); + if (current && null != current$$1.stateNode) + updateHostText$1( + current, + current$$1, + current.memoizedProps, + fiber + ); + else { + if ("string" !== typeof fiber && null === current$$1.stateNode) + throw ReactError( + "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 = requiredContext( + contextStackCursor$1.current + ); + current$$1.stateNode = createTextInstance( + fiber, + current, + renderExpirationTime, + current$$1 + ); + } break; case 11: break; @@ -6212,21 +6180,29 @@ function completeUnitOfWork(workInProgress) { break a; } fiber = null !== fiber; - renderExpirationTime = - null !== current && null !== current.memoizedState; + renderExpirationTime = !1; null !== current && - !fiber && - renderExpirationTime && - ((current = current.child.sibling), - null !== current && - ((viewConfig = current$$1.firstEffect), - null !== viewConfig - ? ((current$$1.firstEffect = current), - (current.nextEffect = viewConfig)) - : ((current$$1.firstEffect = current$$1.lastEffect = current), - (current.nextEffect = null)), - (current.effectTag = 8))); - if (fiber || renderExpirationTime) current$$1.effectTag |= 4; + ((viewConfig = current.memoizedState), + (renderExpirationTime = null !== viewConfig), + fiber || + null === viewConfig || + ((viewConfig = viewConfig.fallbackExpirationTime), + viewConfig < mostRecentEventTime && + (mostRecentEventTime = viewConfig), + (current = current.child.sibling), + null !== current && + ((viewConfig = current$$1.firstEffect), + null !== viewConfig + ? ((current$$1.firstEffect = current), + (current.nextEffect = viewConfig)) + : ((current$$1.firstEffect = current$$1.lastEffect = current), + (current.nextEffect = null)), + (current.effectTag = 8)))); + fiber && + !renderExpirationTime && + 0 !== (current$$1.mode & 1) && + (nextRenderDidSuspend = !0); + fiber && (current$$1.effectTag |= 4); break; case 7: break; @@ -6250,9 +6226,12 @@ function completeUnitOfWork(workInProgress) { break; case 18: break; + case 19: + break; + case 20: + break; default: - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -6272,15 +6251,16 @@ function completeUnitOfWork(workInProgress) { viewConfig = null === current$$1.alternate || current$$1.child !== current$$1.alternate.child; - for (type = current$$1.child; null !== type; ) - (internalInstanceHandle = type.expirationTime), - (currentHostContext = type.childExpirationTime), - internalInstanceHandle > fiber && - (fiber = internalInstanceHandle), - currentHostContext > fiber && (fiber = currentHostContext), - viewConfig && (current += type.actualDuration), - (renderExpirationTime += type.treeBaseDuration), - (type = type.sibling); + for (type = current$$1.child; null !== type; ) { + currentHostContext = type.expirationTime; + var childChildExpirationTime = type.childExpirationTime; + currentHostContext > fiber && (fiber = currentHostContext); + childChildExpirationTime > fiber && + (fiber = childChildExpirationTime); + viewConfig && (current += type.actualDuration); + renderExpirationTime += type.treeBaseDuration; + type = type.sibling; + } current$$1.actualDuration = current; current$$1.treeBaseDuration = renderExpirationTime; } else @@ -6330,9 +6310,9 @@ function completeUnitOfWork(workInProgress) { function performUnitOfWork(workInProgress) { var current$$1 = workInProgress.alternate; workInProgress.mode & 4 && - ((profilerStartTime = now$1()), + ((profilerStartTime = now$2()), 0 > workInProgress.actualStartTime && - (workInProgress.actualStartTime = now$1())); + (workInProgress.actualStartTime = now$2())); current$$1 = beginWork(current$$1, workInProgress, nextRenderExpirationTime); workInProgress.memoizedProps = workInProgress.pendingProps; workInProgress.mode & 4 && @@ -6342,11 +6322,11 @@ function performUnitOfWork(workInProgress) { return current$$1; } function renderRoot(root, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); - flushPassiveEffects(); + if (isWorking) + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + flushPassiveEffects$1(); isWorking = !0; var previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = ContextOnlyDispatcher; @@ -6396,7 +6376,7 @@ function renderRoot(root, isYieldy) { do { try { if (isYieldy) - for (; null !== nextUnitOfWork && !(frameDeadline <= now$1()); ) + for (; null !== nextUnitOfWork && !shouldYield$1(); ) nextUnitOfWork = performUnitOfWork(nextUnitOfWork); else for (; null !== nextUnitOfWork; ) @@ -6407,17 +6387,18 @@ function renderRoot(root, isYieldy) { resetHooks(), null === nextUnitOfWork) ) - (threadID = !0), onUncaughtError(thrownValue); + (threadID = !0), onUncaughtError$1(thrownValue); else { nextUnitOfWork.mode & 4 && stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, !0); - invariant( - null !== nextUnitOfWork, - "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." - ); + if (null === nextUnitOfWork) + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); var sourceFiber = nextUnitOfWork, returnFiber = sourceFiber.return; - if (null === returnFiber) (threadID = !0), onUncaughtError(thrownValue); + if (null === returnFiber) + (threadID = !0), onUncaughtError$1(thrownValue); else { throwException( root, @@ -6442,10 +6423,10 @@ function renderRoot(root, isYieldy) { else if (null !== nextUnitOfWork) root.finishedWork = null; else { previousDispatcher = root.current.alternate; - invariant( - null !== previousDispatcher, - "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousDispatcher) + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); nextRoot = null; if (nextRenderDidError) { if (hasLowerPriorityWork(root, expirationTime)) { @@ -6467,16 +6448,11 @@ function renderRoot(root, isYieldy) { return; } } - isYieldy && -1 !== nextLatestAbsoluteTimeoutMs + isYieldy && nextRenderDidSuspend && 1073741823 !== mostRecentEventTime ? (markSuspendedPriorityLevel(root, expirationTime), (isYieldy = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel(root, expirationTime))), - isYieldy < nextLatestAbsoluteTimeoutMs && - (nextLatestAbsoluteTimeoutMs = isYieldy), - (isYieldy = 10 * (1073741822 - requestCurrentTime())), - (isYieldy = nextLatestAbsoluteTimeoutMs - isYieldy), + 10 * (1073741822 - mostRecentEventTime) - 5e3 + originalStartTimeMs), + (isYieldy = 150 - (now$1() - isYieldy)), onSuspend( root, previousDispatcher, @@ -6487,7 +6463,7 @@ function renderRoot(root, isYieldy) { : onComplete(root, previousDispatcher, expirationTime); } } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { for (var fiber = sourceFiber.return; null !== fiber; ) { switch (fiber.tag) { case 1: @@ -6495,13 +6471,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( "function" === typeof fiber.type.getDerivedStateFromError || ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } break; @@ -6509,7 +6484,7 @@ function captureCommitPhaseError(sourceFiber, value) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createRootErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } fiber = fiber.return; @@ -6518,64 +6493,25 @@ function captureCommitPhaseError(sourceFiber, value) { ((fiber = createCapturedValue(value, sourceFiber)), (fiber = createRootErrorUpdate(sourceFiber, fiber, 1073741823)), enqueueUpdate(sourceFiber, fiber), - scheduleWork(sourceFiber, 1073741823)); + scheduleWork$1(sourceFiber, 1073741823)); } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(), - expirationTime = void 0; - if (0 === (fiber.mode & 1)) expirationTime = 1073741823; - else if (isWorking && !isCommitting$1) - expirationTime = nextRenderExpirationTime; - else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = 1073741823; - break; - case scheduler.unstable_UserBlockingPriority: - expirationTime = - 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1); - break; - case scheduler.unstable_NormalPriority: - expirationTime = - 1073741822 - 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = 1; - break; - default: - invariant( - !1, - "Unknown priority level. This error is likely caused by a bug in React. Please file an issue." - ); - } - null !== nextRoot && - expirationTime === nextRenderExpirationTime && - --expirationTime; - } - priorityLevel === scheduler.unstable_UserBlockingPriority && +function computeExpirationForFiber$1(currentTime, fiber) { + isWorking + ? (currentTime = isCommitting$1 ? 1073741823 : nextRenderExpirationTime) + : fiber.mode & 1 + ? ((currentTime = isBatchingInteractiveUpdates + ? 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1) + : 1073741822 - + 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1)), + null !== nextRoot && + currentTime === nextRenderExpirationTime && + --currentTime) + : (currentTime = 1073741823); + isBatchingInteractiveUpdates && (0 === lowestPriorityPendingInteractiveExpirationTime || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) && - (lowestPriorityPendingInteractiveExpirationTime = expirationTime); - return expirationTime; -} -function pingSuspendedRoot(root, thenable, pingTime) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(thenable); - if (null !== nextRoot && nextRenderExpirationTime === pingTime) - nextRoot = null; - else if ( - ((thenable = root.earliestSuspendedTime), - (pingCache = root.latestSuspendedTime), - 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) - ) { - root.didError = !1; - thenable = root.latestPingedTime; - if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; - findNextExpirationTimeToWorkOn(pingTime, root); - pingTime = root.expirationTime; - 0 !== pingTime && requestWork(root, pingTime); - } + currentTime < lowestPriorityPendingInteractiveExpirationTime) && + (lowestPriorityPendingInteractiveExpirationTime = currentTime); + return currentTime; } function scheduleWorkToRoot(fiber, expirationTime) { fiber.expirationTime < expirationTime && @@ -6625,9 +6561,10 @@ function scheduleWorkToRoot(fiber, expirationTime) { } return root; } -function scheduleWork(fiber, expirationTime) { +function scheduleWork$1(fiber, expirationTime) { fiber = scheduleWorkToRoot(fiber, expirationTime); - null !== fiber && + if ( + null !== fiber && (!isWorking && 0 !== nextRenderExpirationTime && expirationTime > nextRenderExpirationTime && @@ -6635,12 +6572,12 @@ function scheduleWork(fiber, expirationTime) { markPendingPriorityLevel(fiber, expirationTime), (isWorking && !isCommitting$1 && nextRoot === fiber) || requestWork(fiber, fiber.expirationTime), - nestedUpdateCount > NESTED_UPDATE_LIMIT && - ((nestedUpdateCount = 0), - invariant( - !1, - "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." - ))); + nestedUpdateCount > NESTED_UPDATE_LIMIT) + ) + throw ((nestedUpdateCount = 0), + ReactError( + "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." + )); } var firstScheduledRoot = null, lastScheduledRoot = null, @@ -6654,6 +6591,7 @@ var firstScheduledRoot = null, unhandledError = null, isBatchingUpdates = !1, isUnbatchingUpdates = !1, + isBatchingInteractiveUpdates = !1, completedBatches = null, originalStartTimeMs = now$1(), currentRendererTime = 1073741822 - ((originalStartTimeMs / 10) | 0), @@ -6668,13 +6606,14 @@ function recomputeCurrentRendererTime() { function scheduleCallbackWithExpirationTime(root, expirationTime) { if (0 !== callbackExpirationTime) { if (expirationTime < callbackExpirationTime) return; - null !== callbackID && - ((root = callbackID), (scheduledCallback = null), clearTimeout(root)); + null !== callbackID && cancelCallback$1(callbackID); } callbackExpirationTime = expirationTime; root = now$1() - originalStartTimeMs; - callbackID = scheduleDeferredCallback$1(performAsyncWork, { - timeout: 10 * (1073741822 - expirationTime) - root + expirationTime = 10 * (1073741822 - expirationTime) - root; + root = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(root, performAsyncWork, { + timeout: expirationTime }); } function onComplete(root, finishedWork, expirationTime) { @@ -6689,7 +6628,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - 0 !== msUntilTimeout || frameDeadline <= now$1() + 0 !== msUntilTimeout || shouldYield$1() ? 0 < msUntilTimeout && (root.timeoutHandle = scheduleTimeout( onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), @@ -6703,20 +6642,20 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { root.finishedWork = finishedWork; recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." - ); + if (isRendering) + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); nextFlushedRoot = root; nextFlushedExpirationTime = suspendedExpirationTime; performWorkOnRoot(root, suspendedExpirationTime, !1); - performWork(1073741823, !1); + performWork(1073741823); } function onCommit(root, expirationTime) { root.expirationTime = expirationTime; root.finishedWork = null; } -function requestCurrentTime() { +function requestCurrentTime$1() { if (isRendering) return currentSchedulerTime; findHighestPriorityRoot(); if (0 === nextFlushedExpirationTime || 1 === nextFlushedExpirationTime) @@ -6741,7 +6680,7 @@ function requestWork(root, expirationTime) { (nextFlushedExpirationTime = 1073741823), performWorkOnRoot(root, 1073741823, !1)) : 1073741823 === expirationTime - ? performWork(1073741823, !1) + ? performWork(1073741823) : scheduleCallbackWithExpirationTime(root, expirationTime)); } function findHighestPriorityRoot() { @@ -6755,10 +6694,10 @@ function findHighestPriorityRoot() { ) { var remainingExpirationTime = root.expirationTime; if (0 === remainingExpirationTime) { - invariant( - null !== previousScheduledRoot && null !== lastScheduledRoot, - "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousScheduledRoot || null === lastScheduledRoot) + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); if (root === root.nextScheduledRoot) { firstScheduledRoot = lastScheduledRoot = root.nextScheduledRoot = null; break; @@ -6801,58 +6740,57 @@ function performAsyncWork(didTimeout) { didTimeout = didTimeout.nextScheduledRoot; } while (didTimeout !== firstScheduledRoot); } - performWork(0, !0); -} -function performWork(minExpirationTime, isYieldy) { findHighestPriorityRoot(); - if (isYieldy) - for ( + recomputeCurrentRendererTime(); + for ( + currentSchedulerTime = currentRendererTime; + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime); + + ) + performWorkOnRoot( + nextFlushedRoot, + nextFlushedExpirationTime, + currentRendererTime > nextFlushedExpirationTime + ), + findHighestPriorityRoot(), recomputeCurrentRendererTime(), - currentSchedulerTime = currentRendererTime; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime && - !( - frameDeadline <= now$1() && - currentRendererTime > nextFlushedExpirationTime - ); - - ) - performWorkOnRoot( - nextFlushedRoot, - nextFlushedExpirationTime, - currentRendererTime > nextFlushedExpirationTime - ), - findHighestPriorityRoot(), - recomputeCurrentRendererTime(), - (currentSchedulerTime = currentRendererTime); - else - for ( - ; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime; - - ) - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), - findHighestPriorityRoot(); - isYieldy && ((callbackExpirationTime = 0), (callbackID = null)); + (currentSchedulerTime = currentRendererTime); + callbackExpirationTime = 0; + callbackID = null; 0 !== nextFlushedExpirationTime && scheduleCallbackWithExpirationTime( nextFlushedRoot, nextFlushedExpirationTime ); + finishRendering(); +} +function performWork(minExpirationTime) { + for ( + findHighestPriorityRoot(); + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + minExpirationTime <= nextFlushedExpirationTime; + + ) + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), + findHighestPriorityRoot(); + 0 !== nextFlushedExpirationTime && + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + finishRendering(); +} +function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; - if (null !== completedBatches) - for ( - minExpirationTime = completedBatches, - completedBatches = null, - isYieldy = 0; - isYieldy < minExpirationTime.length; - isYieldy++ - ) { - var batch = minExpirationTime[isYieldy]; + if (null !== completedBatches) { + var batches = completedBatches; + completedBatches = null; + for (var i = 0; i < batches.length; i++) { + var batch = batches[i]; try { batch._onComplete(); } catch (error) { @@ -6860,17 +6798,18 @@ function performWork(minExpirationTime, isYieldy) { ((hasUnhandledError = !0), (unhandledError = error)); } } + } if (hasUnhandledError) - throw ((minExpirationTime = unhandledError), + throw ((batches = unhandledError), (unhandledError = null), (hasUnhandledError = !1), - minExpirationTime); + batches); } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); + if (isRendering) + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); isRendering = !0; if (isYieldy) { var _finishedWork = root.finishedWork; @@ -6883,7 +6822,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { renderRoot(root, isYieldy), (_finishedWork = root.finishedWork), null !== _finishedWork && - (frameDeadline <= now$1() + (shouldYield$1() ? (root.finishedWork = _finishedWork) : completeRoot$1(root, _finishedWork, expirationTime))); } else @@ -6918,46 +6857,81 @@ function completeRoot$1(root, finishedWork, expirationTime) { root === lastCommittedRootDuringThisBatch ? nestedUpdateCount++ : ((lastCommittedRootDuringThisBatch = root), (nestedUpdateCount = 0)); - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); - } - ); + commitRoot(root, finishedWork); } -function onUncaughtError(error) { - invariant( - null !== nextFlushedRoot, - "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." - ); +function onUncaughtError$1(error) { + if (null === nextFlushedRoot) + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); nextFlushedRoot.expirationTime = 0; hasUnhandledError || ((hasUnhandledError = !0), (unhandledError = error)); } +Scheduler_now(); +var requestCurrentTime$$1 = requestCurrentTime$1, + computeExpirationForFiber$$1 = computeExpirationForFiber$1, + captureCommitPhaseError$$1 = captureCommitPhaseError$1, + onUncaughtError$$1 = onUncaughtError$1; +function pingSuspendedRoot$$1(root, thenable, pingTime) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(thenable); + if (null !== nextRoot && nextRenderExpirationTime === pingTime) + nextRoot = null; + else if ( + ((thenable = root.earliestSuspendedTime), + (pingCache = root.latestSuspendedTime), + 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) + ) { + root.didError = !1; + thenable = root.latestPingedTime; + if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; + findNextExpirationTimeToWorkOn(pingTime, root); + pingTime = root.expirationTime; + 0 !== pingTime && requestWork(root, pingTime); + } +} +function resolveRetryThenable$$1(boundaryFiber, thenable) { + var retryCache = boundaryFiber.stateNode; + null !== retryCache && retryCache.delete(thenable); + thenable = requestCurrentTime$1(); + thenable = computeExpirationForFiber$1(thenable, boundaryFiber); + boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); + null !== boundaryFiber && + (markPendingPriorityLevel(boundaryFiber, thenable), + (thenable = boundaryFiber.expirationTime), + 0 !== thenable && requestWork(boundaryFiber, thenable)); +} +var isAlreadyFailedLegacyErrorBoundary$$1 = isAlreadyFailedLegacyErrorBoundary$1, + scheduleWork$$1 = scheduleWork$1, + flushPassiveEffects$$1 = flushPassiveEffects$1; function findHostInstance(component) { var fiber = component._reactInternalFiber; - void 0 === fiber && - ("function" === typeof component.render - ? invariant(!1, "Unable to find node on an unmounted component.") - : invariant( - !1, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - )); + if (void 0 === fiber) { + if ("function" === typeof component.render) + throw ReactError("Unable to find node on an unmounted component."); + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } component = findCurrentHostFiber(fiber); return null === component ? null : component.stateNode; } function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, - currentTime = requestCurrentTime(); - current$$1 = computeExpirationForFiber(currentTime, current$$1); + currentTime = requestCurrentTime$$1(); + current$$1 = computeExpirationForFiber$$1(currentTime, current$$1); currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { - invariant( - 2 === isFiberMountedImpl(parentComponent) && 1 === parentComponent.tag, - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); + if ( + 2 !== isFiberMountedImpl(parentComponent) || + 1 !== parentComponent.tag + ) + throw ReactError( + "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 { switch (parentContext.tag) { @@ -6974,11 +6948,9 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - invariant( - !1, + throw ReactError( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); - parentContext = void 0; } if (1 === parentComponent.tag) { var Component = parentComponent.type; @@ -7001,9 +6973,9 @@ function updateContainer(element, container, parentComponent, callback) { callback.payload = { element: element }; container = void 0 === container ? null : container; null !== container && (callback.callback = container); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(currentTime, callback); - scheduleWork(currentTime, current$$1); + scheduleWork$$1(currentTime, current$$1); return current$$1; } function createPortal(children, containerInfo, implementation) { @@ -7038,7 +7010,9 @@ function _inherits(subClass, superClass) { } var getInspectorDataForViewTag = void 0; getInspectorDataForViewTag = function() { - invariant(!1, "getInspectorDataForViewTag() is not available in production"); + throw ReactError( + "getInspectorDataForViewTag() is not available in production" + ); }; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7061,13 +7035,13 @@ _batchedUpdatesImpl = function(fn, a) { } finally { (isBatchingUpdates = previousIsBatchingUpdates) || isRendering || - performWork(1073741823, !1); + performWork(1073741823); } }; _flushInteractiveUpdatesImpl = function() { isRendering || 0 === lowestPriorityPendingInteractiveExpirationTime || - (performWork(lowestPriorityPendingInteractiveExpirationTime, !1), + (performWork(lowestPriorityPendingInteractiveExpirationTime), (lowestPriorityPendingInteractiveExpirationTime = 0)); }; var roots = new Map(), @@ -7095,35 +7069,67 @@ var roots = new Map(), TextInputState.focusTextInput(findNodeHandle(this)); }; ReactNativeComponent.prototype.measure = function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }; ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7146,53 +7152,16 @@ var roots = new Map(), })(React.Component); })(findNodeHandle, findHostInstance), findNodeHandle: findNodeHandle, - setNativeProps: function(handle, nativeProps) { - null != handle._nativeTag && - ((nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - handle.viewConfig.validAttributes - )), - null != nativeProps && - UIManager.updateView( - handle._nativeTag, - handle.viewConfig.uiViewClassName, - nativeProps - )); - }, + setNativeProps: function() {}, render: function(element, containerTag, callback) { var root = roots.get(containerTag); if (!root) { - root = 0; - isDevToolsPresent && (root |= 4); - root = createFiber(3, null, null, root); - var root$jscomp$0 = { - current: root, - containerInfo: containerTag, - pendingChildren: null, - earliestPendingTime: 0, - latestPendingTime: 0, - earliestSuspendedTime: 0, - latestSuspendedTime: 0, - latestPingedTime: 0, - pingCache: null, - didError: !1, - pendingCommitExpirationTime: 0, - finishedWork: null, - timeoutHandle: -1, - context: null, - pendingContext: null, - hydrate: !1, - nextExpirationTimeToWorkOn: 0, - expirationTime: 0, - firstBatch: null, - nextScheduledRoot: null, - interactionThreadID: tracing.unstable_getThreadID(), - memoizedInteractions: new Set(), - pendingInteractionMap: new Map() - }; - root = root.stateNode = root$jscomp$0; + root = new FiberRootNode(containerTag, !1); + var uninitializedFiber = 0; + isDevToolsPresent && (uninitializedFiber |= 4); + uninitializedFiber = createFiber(3, null, null, uninitializedFiber); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; roots.set(containerTag, root); } updateContainer(element, root, null, callback); @@ -7226,31 +7195,63 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }, setNativeProps: function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7283,7 +7284,10 @@ var roots = new Map(), var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: null, overrideProps: null, + setSuspenseHandler: null, + scheduleUpdate: null, currentDispatcherRef: ReactSharedInternals.ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { fiber = findCurrentHostFiber(fiber); @@ -7300,7 +7304,7 @@ var roots = new Map(), findFiberByHostInstance: getInstanceFromInstance, getInspectorDataForViewTag: getInspectorDataForViewTag, bundleType: 0, - version: "16.8.3", + version: "16.8.6", rendererPackageName: "react-native-renderer" }); var ReactFabric$2 = { default: ReactFabric }, diff --git a/Libraries/Renderer/oss/ReactNativeRenderer-dev.js b/Libraries/Renderer/oss/ReactNativeRenderer-dev.js index 8afedd6a192..dad23916a51 100644 --- a/Libraries/Renderer/oss/ReactNativeRenderer-dev.js +++ b/Libraries/Renderer/oss/ReactNativeRenderer-dev.js @@ -26,9 +26,20 @@ var deepDiffer = require("deepDiffer"); var flattenStyle = require("flattenStyle"); var TextInputState = require("TextInputState"); var checkPropTypes = require("prop-types/checkPropTypes"); +var Scheduler = require("scheduler"); var tracing = require("scheduler/tracing"); -var scheduler = require("scheduler"); var ExceptionsManager = require("ExceptionsManager"); +var FabricUIManager = require("FabricUIManager"); + +// Do not require this module directly! Use a normal error constructor with +// template literal strings. The messages will be converted to ReactError during +// build, and in production they will be minified. + +function ReactError(message) { + var error = new Error(message); + error.name = "Invariant Violation"; + return error; +} /** * Use invariant() to assert state which your program assumes to be true. @@ -41,39 +52,237 @@ var ExceptionsManager = require("ExceptionsManager"); * will remain to ensure logic does not differ in production. */ -var validateFormat = function() {}; +/** + * Injectable ordering of event plugins. + */ +var eventPluginOrder = null; -{ - validateFormat = function(format) { - if (format === undefined) { - throw new Error("invariant requires an error message argument"); +/** + * Injectable mapping from names to event plugin modules. + */ +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( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + } + })(); + if (plugins[pluginIndex]) { + continue; } - }; + (function() { + if (!pluginModule.extractEvents) { + throw ReactError( + "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( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + })(); + } + } } -function invariant(condition, format, a, b, c, d, e, f) { - validateFormat(format); - - if (!condition) { - var error = void 0; - if (format === undefined) { - error = new Error( - "Minified exception occurred; use the non-minified dev environment " + - "for the full error message and additional helpful warnings." +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + (function() { + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName + + "`." ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - error.name = "Invariant Violation"; } + })(); + eventNameDispatchConfigs[eventName] = dispatchConfig; - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName( + phasedRegistrationName, + pluginModule, + eventName + ); + } + } + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName( + dispatchConfig.registrationName, + pluginModule, + eventName + ); + return true; + } + return false; +} + +/** + * Publishes a registration name that is used to identify dispatched events. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ +function publishRegistrationName(registrationName, pluginModule, eventName) { + (function() { + if (!!registrationNameModules[registrationName]) { + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + } + })(); + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = + pluginModule.eventTypes[eventName].dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + } +} + +/** + * Registers plugins so that they can extract and dispatch events. + * + * @see {EventPluginHub} + */ + +/** + * Ordered list of injected plugins. + */ +var plugins = []; + +/** + * Mapping from event name to dispatch config + */ +var eventNameDispatchConfigs = {}; + +/** + * Mapping from registration name to plugin module + */ +var registrationNameModules = {}; + +/** + * Mapping from registration name to event name + */ +var registrationNameDependencies = {}; + +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ + +// Trust the developer to only use possibleRegistrationNames in true + +/** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ +function injectEventPluginOrder(injectedEventPluginOrder) { + (function() { + if (!!eventPluginOrder) { + throw ReactError( + "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`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @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( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + } + })(); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); } } @@ -141,16 +350,13 @@ 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. - invariant( - typeof document !== "undefined", - "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." - ); + (function() { + if (!(typeof document !== "undefined")) { + throw ReactError( + "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"); // Keeps track of whether the user-provided callback threw an error. We @@ -373,221 +579,13 @@ function clearCaughtError() { caughtError = null; return error; } else { - invariant( - false, - "clearCaughtError was called but no error was captured. This error " + - "is likely caused by a bug in React. Please file an issue." - ); - } -} - -/** - * Injectable ordering of event plugins. - */ -var eventPluginOrder = null; - -/** - * Injectable mapping from names to event plugin modules. - */ -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); - invariant( - pluginIndex > -1, - "EventPluginRegistry: Cannot inject event plugins that do not exist in " + - "the plugin ordering, `%s`.", - pluginName - ); - if (plugins[pluginIndex]) { - continue; - } - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` " + - "method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - var publishedEvents = pluginModule.eventTypes; - for (var eventName in publishedEvents) { - invariant( - publishEventForPlugin( - publishedEvents[eventName], - pluginModule, - eventName - ), - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } -} - -/** - * Publishes an event so that it can be dispatched by the supplied plugin. - * - * @param {object} dispatchConfig Dispatch configuration for the event. - * @param {object} PluginModule Plugin publishing the event. - * @return {boolean} True if the event was successfully published. - * @private - */ -function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName), - "EventPluginHub: More than one plugin attempted to publish the same " + - "event name, `%s`.", - eventName - ); - eventNameDispatchConfigs[eventName] = dispatchConfig; - - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (var phaseName in phasedRegistrationNames) { - if (phasedRegistrationNames.hasOwnProperty(phaseName)) { - var phasedRegistrationName = phasedRegistrationNames[phaseName]; - publishRegistrationName( - phasedRegistrationName, - pluginModule, - eventName + (function() { + { + throw ReactError( + "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); } - } - return true; - } else if (dispatchConfig.registrationName) { - publishRegistrationName( - dispatchConfig.registrationName, - pluginModule, - eventName - ); - return true; - } - return false; -} - -/** - * Publishes a registration name that is used to identify dispatched events. - * - * @param {string} registrationName Registration name to add. - * @param {object} PluginModule Plugin publishing the event. - * @private - */ -function publishRegistrationName(registrationName, pluginModule, eventName) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same " + - "registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; - registrationNameDependencies[registrationName] = - pluginModule.eventTypes[eventName].dependencies; - - { - var lowerCasedName = registrationName.toLowerCase(); - } -} - -/** - * Registers plugins so that they can extract and dispatch events. - * - * @see {EventPluginHub} - */ - -/** - * Ordered list of injected plugins. - */ -var plugins = []; - -/** - * Mapping from event name to dispatch config - */ -var eventNameDispatchConfigs = {}; - -/** - * Mapping from registration name to plugin module - */ -var registrationNameModules = {}; - -/** - * Mapping from registration name to event name - */ -var registrationNameDependencies = {}; - -/** - * Mapping from lowercase registration names to the properly cased version, - * used to warn in the case of missing event handlers. Available - * only in true. - * @type {Object} - */ - -// Trust the developer to only use possibleRegistrationNames in true - -/** - * Injects an ordering of plugins (by plugin name). This allows the ordering - * to be decoupled from injection of the actual plugins so that ordering is - * always deterministic regardless of packaging, on-the-fly injection, etc. - * - * @param {array} InjectedEventPluginOrder - * @internal - * @see {EventPluginHub.injection.injectEventPluginOrder} - */ -function injectEventPluginOrder(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "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`. - * - * Plugins can be injected as part of page initialization or on-the-fly. - * - * @param {object} injectedNamesToPlugins Map from names to plugin modules. - * @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 - ) { - invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins " + - "using the same name, `%s`.", - pluginName - ); - namesToPlugins[pluginName] = pluginModule; - isOrderingDirty = true; - } - } - if (isOrderingDirty) { - recomputePluginOrdering(); + })(); } } @@ -796,10 +794,11 @@ function executeDirectDispatch(event) { } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + (function() { + if (!!Array.isArray(dispatchListener)) { + throw ReactError("executeDirectDispatch(...): Invalid `event`."); + } + })(); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -832,10 +831,13 @@ function hasDispatches(event) { */ function accumulateInto(current, next) { - invariant( - next != null, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + (function() { + if (!(next != null)) { + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); + } + })(); if (current == null) { return next; @@ -902,6 +904,32 @@ var executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(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 + // events get enqueued while processing. + var processingEventQueue = eventQueue; + eventQueue = null; + + if (!processingEventQueue) { + return; + } + + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + (function() { + if (!!eventQueue) { + throw ReactError( + "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(); +} + function isInteractive(tag) { return ( tag === "button" || @@ -992,12 +1020,17 @@ function getListener(inst, registrationName) { if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } - invariant( - !listener || typeof listener === "function", - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + (function() { + if (!(!listener || typeof listener === "function")) { + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); + } + })(); return listener; } @@ -1008,7 +1041,7 @@ function getListener(inst, registrationName) { * @return {*} An accumulation of synthetic events. * @internal */ -function extractEvents( +function extractPluginEvents( topLevelType, targetInst, nativeEvent, @@ -1033,37 +1066,13 @@ function extractEvents( return events; } -function runEventsInBatch(events) { - if (events !== null) { - eventQueue = accumulateInto(eventQueue, events); - } - - // Set `eventQueue` to null before processing it so that we can tell if more - // events get enqueued while processing. - var processingEventQueue = eventQueue; - eventQueue = null; - - if (!processingEventQueue) { - return; - } - - forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - invariant( - !eventQueue, - "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(); -} - -function runExtractedEventsInBatch( +function runExtractedPluginEventsInBatch( topLevelType, targetInst, nativeEvent, nativeEventTarget ) { - var events = extractEvents( + var events = extractPluginEvents( topLevelType, targetInst, nativeEvent, @@ -1091,6 +1100,8 @@ var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedSuspenseComponent = 18; +var EventComponent = 19; +var EventTarget = 20; function getParent(inst) { do { @@ -1609,10 +1620,13 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { function releasePooledEvent(event) { var EventConstructor = this; - invariant( - event instanceof EventConstructor, - "Trying to release an event instance into a pool of a different type." - ); + (function() { + if (!(event instanceof EventConstructor)) { + throw ReactError( + "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); @@ -1719,7 +1733,11 @@ function resetTouchRecord(touchRecord, touch) { function getTouchIdentifier(_ref) { var identifier = _ref.identifier; - invariant(identifier != null, "Touch object is missing identifier."); + (function() { + if (!(identifier != null)) { + throw ReactError("Touch object is missing identifier."); + } + })(); { !(identifier <= MAX_TOUCH_BANK) ? warningWithoutStack$1( @@ -1847,10 +1865,13 @@ var ResponderTouchHistoryStore = { * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { - invariant( - next != null, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + (function() { + if (!(next != null)) { + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); + } + })(); if (current == null) { return next; @@ -2462,11 +2483,13 @@ var ReactNativeBridgeEventPlugin = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType]; var directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + (function() { + if (!(bubbleDispatchConfig || directDispatchConfig)) { + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); + } + })(); var event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -2531,7 +2554,11 @@ function getTagFromInstance(inst) { if (tag === undefined) { tag = inst.stateNode.canonical._nativeTag; } - invariant(tag, "All native instances should have a tag."); + (function() { + if (!tag) { + throw ReactError("All native instances should have a tag."); + } + })(); return tag; } @@ -2557,11 +2584,13 @@ function restoreStateOfTarget(target) { // Unmounted return; } - invariant( - typeof restoreImpl === "function", - "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() { + if (!(typeof restoreImpl === "function")) { + throw ReactError( + "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); } @@ -2704,7 +2733,7 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT; var inst = getInstanceFromTag(rootNodeID); batchedUpdates(function() { - runExtractedEventsInBatch( + runExtractedPluginEventsInBatch( topLevelType, inst, nativeEvent, @@ -2873,6 +2902,17 @@ var REACT_FORWARD_REF_TYPE = hasSymbol var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 0xead4; +var REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 0xead5; +var REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 0xead6; + +// React event targets +var REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; @@ -2956,6 +2996,25 @@ function getComponentName(type) { if (resolvedThenable) { return getComponentName(resolvedThenable); } + break; + } + case REACT_EVENT_COMPONENT_TYPE: { + var eventComponent = type; + var displayName = eventComponent.displayName; + if (displayName !== undefined) { + return displayName; + } + break; + } + case REACT_EVENT_TARGET_TYPE: { + var eventTarget = type; + if (eventTarget.type === REACT_EVENT_TARGET_TOUCH_HIT) { + return "TouchHitTarget"; + } + var _displayName = eventTarget.displayName; + if (_displayName !== undefined) { + return _displayName; + } } } } @@ -3055,10 +3114,11 @@ function isMounted(component) { } function assertIsMounted(fiber) { - invariant( - isFiberMountedImpl(fiber) === MOUNTED, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(isFiberMountedImpl(fiber) === MOUNTED)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } function findCurrentFiberUsingSlowPath(fiber) { @@ -3066,10 +3126,11 @@ function findCurrentFiberUsingSlowPath(fiber) { if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. var state = isFiberMountedImpl(fiber); - invariant( - state !== UNMOUNTED, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(state !== UNMOUNTED)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); if (state === MOUNTING) { return null; } @@ -3082,11 +3143,24 @@ function findCurrentFiberUsingSlowPath(fiber) { var b = alternate; while (true) { var parentA = a.return; - var parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) { + 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 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 @@ -3108,7 +3182,11 @@ function findCurrentFiberUsingSlowPath(fiber) { } // 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. - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } if (a.return !== b.return) { @@ -3159,26 +3237,31 @@ function findCurrentFiberUsingSlowPath(fiber) { } _child = _child.sibling; } - invariant( - didFindChild, - "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 (!didFindChild) { + throw ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); + } + })(); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(a.alternate === b)) { + throw ReactError( + "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. - invariant( - a.tag === HostRoot, - "Unable to find node on an unmounted component." - ); + (function() { + if (!(a.tag === HostRoot)) { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; @@ -3729,12 +3812,16 @@ var debugRenderPhaseSideEffects = false; var debugRenderPhaseSideEffectsForStrictMode = false; var enableUserTimingAPI = true; var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; -var warnAboutDeprecatedLifecycles = false; +var warnAboutDeprecatedLifecycles = true; var enableProfilerTimer = true; var enableSchedulerTracing = true; var enableSuspenseServerRenderer = false; +var disableYielding = false; + var warnAboutDeprecatedSetNativeProps = false; +var enableEventAPI = false; +var enableNewScheduler = false; // Only used in www builds. @@ -3770,14 +3857,16 @@ var ReactNativeFiberHostComponent = (function() { TextInputState.focusTextInput(this._nativeTag); }; - ReactNativeFiberHostComponent.prototype.measure = function measure(callback) { + ReactNativeFiberHostComponent.prototype.measure = function measure$$1( + callback + ) { UIManager.measure( this._nativeTag, mountSafeCallback_NOT_REALLY_SAFE(this, callback) ); }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function measureInWindow( + ReactNativeFiberHostComponent.prototype.measureInWindow = function measureInWindow$$1( callback ) { UIManager.measureInWindow( @@ -3791,9 +3880,32 @@ var ReactNativeFiberHostComponent = (function() { onSuccess, onFail /* currently unused */ ) { + var relativeNode = void 0; + + if (typeof relativeToNativeNode === "number") { + // Already a node handle + relativeNode = relativeToNativeNode; + } else if (relativeToNativeNode._nativeTag) { + relativeNode = relativeToNativeNode._nativeTag; + } else if ( + relativeToNativeNode.canonical && + relativeToNativeNode.canonical._nativeTag + ) { + relativeNode = relativeToNativeNode.canonical._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; + } + UIManager.measureLayout( this._nativeTag, - relativeToNativeNode, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); @@ -3832,63 +3944,17 @@ var ReactNativeFiberHostComponent = (function() { return ReactNativeFiberHostComponent; })(); -var hasNativePerformanceNow = - typeof performance === "object" && typeof performance.now === "function"; - -var now$1 = hasNativePerformanceNow - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }; - -var scheduledCallback = null; -var frameDeadline = 0; - -function setTimeoutCallback() { - // TODO (bvaughn) Hard-coded 5ms unblocks initial async testing. - // React API probably changing to boolean rather than time remaining. - // Longer-term plan is to rewrite this using shared memory, - // And just return the value of the bit as the boolean. - frameDeadline = now$1() + 5; - - var callback = scheduledCallback; - scheduledCallback = null; - if (callback !== null) { - callback(); - } -} - -// RN has a poor polyfill for requestIdleCallback so we aren't using it. -// This implementation is only intended for short-term use anyway. -// We also don't implement cancel functionality b'c Fiber doesn't currently need it. -function scheduleDeferredCallback$1(callback, options) { - // We assume only one callback is scheduled at a time b'c that's how Fiber works. - scheduledCallback = callback; - var timeoutId = setTimeout(setTimeoutCallback, 1); - return timeoutId; // Timeouts are always numbers on RN -} - -function cancelDeferredCallback$1(callbackID) { - scheduledCallback = null; - clearTimeout(callbackID); // Timeouts are always numbers on RN -} - -function shouldYield$1() { - return frameDeadline <= now$1(); -} - // Renderers that don't support persistence // can re-export everything from this module. function shim() { - invariant( - false, - "The current renderer does not support persistence. " + - "This error is likely caused by a bug in React. " + - "Please file an issue." - ); + (function() { + { + throw ReactError( + "The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } // Persistence (when unsupported) @@ -3899,19 +3965,19 @@ var appendChildToContainerChildSet = shim; var finalizeContainerChildren = shim; var replaceContainerChildren = shim; var cloneHiddenInstance = shim; -var cloneUnhiddenInstance = shim; -var createHiddenTextInstance = shim; +var cloneHiddenTextInstance = shim; // Renderers that don't support hydration // can re-export everything from this module. function shim$1() { - invariant( - false, - "The current renderer does not support hydration. " + - "This error is likely caused by a bug in React. " + - "Please file an issue." - ); + (function() { + { + throw ReactError( + "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } // Hydration (when unsupported) @@ -3995,10 +4061,13 @@ function createInstance( } } - invariant( - type !== "RCTView" || !hostContext.isInAParentText, - "Nesting of within is not currently supported." - ); + (function() { + if (!(type !== "RCTView" || !hostContext.isInAParentText)) { + throw ReactError( + "Nesting of within is not currently supported." + ); + } + })(); var updatePayload = create(props, viewConfig.validAttributes); @@ -4025,10 +4094,13 @@ function createTextInstance( hostContext, internalInstanceHandle ) { - invariant( - hostContext.isInAParentText, - "Text strings must be rendered within a component." - ); + (function() { + if (!hostContext.isInAParentText) { + throw ReactError( + "Text strings must be rendered within a component." + ); + } + })(); var tag = allocateTag(); @@ -4092,6 +4164,16 @@ function getChildHostContext(parentHostContext, type, rootContainerInstance) { } } +function getChildHostContextForEventComponent(parentHostContext) { + // TODO: add getChildHostContextForEventComponent implementation + return parentHostContext; +} + +function getChildHostContextForEventTarget(parentHostContext, type) { + // TODO: add getChildHostContextForEventTarget implementation + return parentHostContext; +} + function getPublicInstance(instance) { return instance; } @@ -4115,17 +4197,11 @@ function resetAfterCommit(containerInfo) { // Noop } -var now$$1 = now$1; var isPrimaryRenderer = true; -var scheduleDeferredCallback$$1 = scheduleDeferredCallback$1; -var cancelDeferredCallback$$1 = cancelDeferredCallback$1; -var shouldYield$$1 = shouldYield$1; var scheduleTimeout = setTimeout; var cancelTimeout = clearTimeout; var noTimeout = -1; -var schedulePassiveEffects = scheduleDeferredCallback$$1; -var cancelPassiveEffects = cancelDeferredCallback$$1; function shouldDeprioritizeSubtree(type, props) { return false; @@ -4260,10 +4336,11 @@ function insertInContainerBefore(parentInstance, child, beforeChild) { // 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. - invariant( - typeof parentInstance !== "number", - "Container does not support insertBefore operation" - ); + (function() { + if (!(typeof parentInstance !== "number")) { + throw ReactError("Container does not support insertBefore operation"); + } + })(); } function removeChild(parentInstance, child) { @@ -4334,6 +4411,35 @@ function unhideTextInstance(textInstance, text) { throw new Error("Not yet implemented."); } +function mountEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function updateEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function unmountEventComponent(eventComponentInstance) { + throw new Error("Not yet implemented."); +} + +function getEventTargetChildElement(type, props) { + throw new Error("Not yet implemented."); +} + +function handleEventTarget( + type, + props, + rootContainerInstance, + internalInstanceHandle +) { + throw new Error("Not yet implemented."); +} + +function commitEventTarget(type, props, instance, parentInstance) { + throw new Error("Not yet implemented."); +} + var BEFORE_SLASH_RE = /^(.*)[\\\/]/; var describeComponentFrame = function(name, source, ownerName) { @@ -5080,11 +5186,13 @@ function popTopLevelContextObject(fiber) { } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(contextStackCursor.current === emptyContextObject)) { + throw ReactError( + "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); @@ -5126,12 +5234,16 @@ function processChildContext(fiber, type, parentContext) { setCurrentPhase(null); } for (var contextKey in childContext) { - invariant( - contextKey in childContextTypes, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + (function() { + if (!(contextKey in childContextTypes)) { + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); + } + })(); } { var name = getComponentName(type) || "Unknown"; @@ -5176,11 +5288,13 @@ function pushContextProvider(workInProgress) { function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "Expected to have an instance by this point. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!instance) { + throw ReactError( + "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. @@ -5209,11 +5323,13 @@ function invalidateContextProvider(workInProgress, type, didChange) { function findCurrentUnmaskedContext(fiber) { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere - invariant( - isFiberMounted(fiber) && fiber.tag === ClassComponent, - "Expected subtree parent to be a mounted class component. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) { + throw ReactError( + "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 { @@ -5230,11 +5346,13 @@ function findCurrentUnmaskedContext(fiber) { } node = node.return; } while (node !== null); - invariant( - false, - "Found unexpected detached subtree parent. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var onCommitFiberRoot = null; @@ -5322,14 +5440,166 @@ function onCommitUnmount(fiber) { // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 -var maxSigned31BitInt = 1073741823; +var MAX_SIGNED_31_BIT_INT = 1073741823; + +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority; +var Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback; +var Scheduler_cancelCallback = Scheduler.unstable_cancelCallback; +var Scheduler_shouldYield = Scheduler.unstable_shouldYield; +var Scheduler_now = Scheduler.unstable_now; +var Scheduler_getCurrentPriorityLevel = + Scheduler.unstable_getCurrentPriorityLevel; +var Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority; +var Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; +var Scheduler_NormalPriority = Scheduler.unstable_NormalPriority; +var Scheduler_LowPriority = Scheduler.unstable_LowPriority; +var Scheduler_IdlePriority = Scheduler.unstable_IdlePriority; + +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 now = Scheduler_now; +var shouldYield = disableYielding + ? function() { + return false; + } // Never yield when `disableYielding` is on + : Scheduler_shouldYield; + +var immediateQueue = null; +var immediateQueueCallbackNode = null; +var isFlushingImmediate = false; + +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("Unknown priority level."); + } + })(); + } +} + +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("Unknown priority level."); + } + })(); + } +} + +function runWithPriority(reactPriorityLevel, fn) { + var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); + return Scheduler_runWithPriority(priorityLevel, fn); +} + +function scheduleCallback(reactPriorityLevel, callback, options) { + if (reactPriorityLevel === ImmediatePriority) { + // Push this callback into an internal queue. We'll flush these either in + // the next tick, or earlier if something calls `flushImmediateQueue`. + if (immediateQueue === null) { + immediateQueue = [callback]; + // Flush the queue in the next tick, at the earliest. + immediateQueueCallbackNode = Scheduler_scheduleCallback( + Scheduler_ImmediatePriority, + flushImmediateQueueImpl + ); + } else { + // Push onto existing queue. Don't need to schedule a callback because + // we already scheduled one when we created the queue. + immediateQueue.push(callback); + } + return fakeCallbackNode; + } + // Otherwise pass through to Scheduler. + var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); + return Scheduler_scheduleCallback(priorityLevel, callback, options); +} + +function cancelCallback(callbackNode) { + if (callbackNode !== fakeCallbackNode) { + Scheduler_cancelCallback(callbackNode); + } +} + +function flushImmediateQueue() { + if (immediateQueueCallbackNode !== null) { + Scheduler_cancelCallback(immediateQueueCallbackNode); + } + flushImmediateQueueImpl(); +} + +function flushImmediateQueueImpl() { + if (!isFlushingImmediate && immediateQueue !== null) { + // Prevent re-entrancy. + isFlushingImmediate = true; + var i = 0; + try { + var _isSync = true; + for (; i < immediateQueue.length; i++) { + var callback = immediateQueue[i]; + do { + callback = callback(_isSync); + } while (callback !== null); + } + immediateQueue = null; + } catch (error) { + // If something throws, leave the remaining callbacks on the queue. + if (immediateQueue !== null) { + immediateQueue = immediateQueue.slice(i + 1); + } + // Resume flushing in the next tick + Scheduler_scheduleCallback( + Scheduler_ImmediatePriority, + flushImmediateQueue + ); + throw error; + } finally { + isFlushingImmediate = false; + } + } +} var NoWork = 0; var Never = 1; -var Sync = maxSigned31BitInt; +var Sync = MAX_SIGNED_31_BIT_INT; var UNIT_SIZE = 10; -var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1; +var MAGIC_NUMBER_OFFSET = MAX_SIGNED_31_BIT_INT - 1; // 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { @@ -5355,6 +5625,8 @@ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { ); } +// 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; @@ -5366,6 +5638,12 @@ function computeAsyncExpiration(currentTime) { ); } +// Same as computeAsyncExpiration but without the bucketing logic. This is +// used to compute timestamps instead of actual expiration times. +function computeAsyncExpirationNoBucket(currentTime) { + return currentTime - LOW_PRIORITY_EXPIRATION / UNIT_SIZE; +} + // We intentionally set a higher expiration time for interactive updates in // dev than in production. // @@ -5388,6 +5666,31 @@ function computeInteractiveExpiration(currentTime) { ); } +function inferPriorityFromExpirationTime(currentTime, expirationTime) { + if (expirationTime === Sync) { + return ImmediatePriority; + } + if (expirationTime === Never) { + return IdlePriority; + } + var msUntil = + msToExpirationTime(expirationTime) - msToExpirationTime(currentTime); + if (msUntil <= 0) { + return ImmediatePriority; + } + if (msUntil <= HIGH_PRIORITY_EXPIRATION) { + return UserBlockingPriority; + } + if (msUntil <= LOW_PRIORITY_EXPIRATION) { + return NormalPriority; + } + + // TODO: Handle LowPriority + + // Assume anything lower has idle priority + return IdlePriority; +} + var NoContext = 0; var ConcurrentMode = 1; var StrictMode = 2; @@ -5489,6 +5792,7 @@ function FiberNode(tag, pendingProps, key, mode) { this._debugSource = null; this._debugOwner = null; this._debugIsCurrentlyTiming = false; + this._debugHookTypes = null; if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { Object.preventExtensions(this); } @@ -5565,6 +5869,7 @@ function createWorkInProgress(current, pendingProps, expirationTime) { workInProgress._debugID = current._debugID; workInProgress._debugSource = current._debugSource; workInProgress._debugOwner = current._debugOwner; + workInProgress._debugHookTypes = current._debugHookTypes; } workInProgress.alternate = current; @@ -5692,6 +5997,28 @@ function createFiberFromTypeAndProps( fiberTag = LazyComponent; resolvedType = null; break getTag; + case REACT_EVENT_COMPONENT_TYPE: + if (enableEventAPI) { + return createFiberFromEventComponent( + type, + pendingProps, + mode, + expirationTime, + key + ); + } + break; + case REACT_EVENT_TARGET_TYPE: + if (enableEventAPI) { + return createFiberFromEventTarget( + type, + pendingProps, + mode, + expirationTime, + key + ); + } + break; } } var info = ""; @@ -5712,14 +6039,16 @@ function createFiberFromTypeAndProps( info += "\n\nCheck the render method of `" + ownerName + "`."; } } - invariant( - false, - "Element type is invalid: expected a string (for built-in " + - "components) or a class/function (for composite components) " + - "but got: %s.%s", - type == null ? type : typeof type, - info - ); + (function() { + { + throw ReactError( + "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 + ); + } + })(); } } } @@ -5761,6 +6090,34 @@ function createFiberFromFragment(elements, mode, expirationTime, key) { return fiber; } +function createFiberFromEventComponent( + eventComponent, + pendingProps, + mode, + expirationTime, + key +) { + var fiber = createFiber(EventComponent, pendingProps, key, mode); + fiber.elementType = eventComponent; + fiber.type = eventComponent; + fiber.expirationTime = expirationTime; + return fiber; +} + +function createFiberFromEventTarget( + eventTarget, + pendingProps, + mode, + expirationTime, + key +) { + var fiber = createFiber(EventTarget, pendingProps, key, mode); + fiber.elementType = eventTarget; + fiber.type = eventTarget; + fiber.expirationTime = expirationTime; + return fiber; +} + function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if ( @@ -5883,6 +6240,7 @@ function assignFiberPropertiesInDEV(target, source) { target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming; + target._debugHookTypes = source._debugHookTypes; return target; } @@ -5899,78 +6257,53 @@ function assignFiberPropertiesInDEV(target, source) { // 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, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pendingChildren = null; + this.pingCache = null; + this.pendingCommitExpirationTime = NoWork; + this.finishedWork = null; + this.timeoutHandle = noTimeout; + this.context = null; + this.pendingContext = null; + this.hydrate = hydrate; + this.firstBatch = null; + + if (enableNewScheduler) { + this.callbackNode = null; + this.callbackExpirationTime = NoWork; + this.firstPendingTime = NoWork; + this.lastPendingTime = NoWork; + this.pingTime = NoWork; + } else { + this.earliestPendingTime = NoWork; + this.latestPendingTime = NoWork; + this.earliestSuspendedTime = NoWork; + this.latestSuspendedTime = NoWork; + this.latestPingedTime = NoWork; + this.didError = false; + this.nextExpirationTimeToWorkOn = NoWork; + this.expirationTime = NoWork; + this.nextScheduledRoot = null; + } + + if (enableSchedulerTracing) { + this.interactionThreadID = tracing.unstable_getThreadID(); + this.memoizedInteractions = new Set(); + this.pendingInteractionMap = new Map(); + } +} + function createFiberRoot(containerInfo, isConcurrent, hydrate) { + var root = new FiberRootNode(containerInfo, hydrate); + // Cyclic construction. This cheats the type system right now because // stateNode is any. var uninitializedFiber = createHostRootFiber(isConcurrent); - - var root = void 0; - if (enableSchedulerTracing) { - root = { - current: uninitializedFiber, - containerInfo: containerInfo, - pendingChildren: null, - - earliestPendingTime: NoWork, - latestPendingTime: NoWork, - earliestSuspendedTime: NoWork, - latestSuspendedTime: NoWork, - latestPingedTime: NoWork, - - pingCache: null, - - didError: false, - - pendingCommitExpirationTime: NoWork, - finishedWork: null, - timeoutHandle: noTimeout, - context: null, - pendingContext: null, - hydrate: hydrate, - nextExpirationTimeToWorkOn: NoWork, - expirationTime: NoWork, - firstBatch: null, - nextScheduledRoot: null, - - interactionThreadID: tracing.unstable_getThreadID(), - memoizedInteractions: new Set(), - pendingInteractionMap: new Map() - }; - } else { - root = { - current: uninitializedFiber, - containerInfo: containerInfo, - pendingChildren: null, - - pingCache: null, - - earliestPendingTime: NoWork, - latestPendingTime: NoWork, - earliestSuspendedTime: NoWork, - latestSuspendedTime: NoWork, - latestPingedTime: NoWork, - - didError: false, - - pendingCommitExpirationTime: NoWork, - finishedWork: null, - timeoutHandle: noTimeout, - context: null, - pendingContext: null, - hydrate: hydrate, - nextExpirationTimeToWorkOn: NoWork, - expirationTime: NoWork, - firstBatch: null, - nextScheduledRoot: null - }; - } - + root.current = uninitializedFiber; uninitializedFiber.stateNode = root; - // The reason for the way the Flow types are structured in this file, - // Is to avoid needing :any casts everywhere interaction tracing fields are used. - // Unfortunately that requires an :any cast for non-interaction tracing capable builds. - // $FlowFixMe Remove this :any cast and replace it with something better. return root; } @@ -6373,6 +6706,43 @@ var ReactStrictModeWarnings = { }; } +/** + * 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; + // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. // This is not part of the public API, not even for React DevTools. @@ -6572,20 +6942,6 @@ function clearPing(root, completedTime) { } } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestExpirationTime = renderExpirationTime; - - var earliestPendingTime = root.earliestPendingTime; - var earliestSuspendedTime = root.earliestSuspendedTime; - if (earliestPendingTime > earliestExpirationTime) { - earliestExpirationTime = earliestPendingTime; - } - if (earliestSuspendedTime > earliestExpirationTime) { - earliestExpirationTime = earliestSuspendedTime; - } - return earliestExpirationTime; -} - function didExpireAtExpirationTime(root, currentTime) { var expirationTime = root.expirationTime; if (expirationTime !== NoWork && currentTime <= expirationTime) { @@ -6628,43 +6984,6 @@ function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { root.expirationTime = expirationTime; } -/** - * 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; - /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is @@ -6860,15 +7179,13 @@ var didWarnAboutInvalidateContextType = void 0; Object.defineProperty(fakeInternalInstance, "_processChildContext", { enumerable: false, value: function() { - invariant( - false, - "_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)." - ); + (function() { + { + throw ReactError( + "_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); @@ -6917,8 +7234,8 @@ var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function(inst, payload, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.payload = payload; @@ -6929,14 +7246,14 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); }, enqueueReplaceState: function(inst, payload, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ReplaceState; @@ -6949,14 +7266,14 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); }, enqueueForceUpdate: function(inst, callback) { var fiber = get$1(inst); - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ForceUpdate; @@ -6968,9 +7285,9 @@ var classComponentUpdater = { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$$1(fiber, expirationTime); } }; @@ -7282,23 +7599,51 @@ function constructClassInstance( var unmaskedContext = emptyContextObject; var context = null; var contextType = ctor.contextType; - if (typeof contextType === "object" && contextType !== null) { - { - if ( - contextType.$$typeof !== REACT_CONTEXT_TYPE && - !didWarnAboutInvalidateContextType.has(ctor) - ) { + + { + if ("contextType" in ctor) { + var isValid = + // Allow null for conditional declaration + contextType === null || + (contextType !== undefined && + contextType.$$typeof === REACT_CONTEXT_TYPE && + contextType._context === undefined); // Not a + + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); + + var addendum = ""; + if (contextType === undefined) { + addendum = + " However, it is set to undefined. " + + "This can be caused by a typo or by mixing up named and default imports. " + + "This can also happen due to a circular dependency, so " + + "try moving the createContext() call to a separate file."; + } else if (typeof contextType !== "object") { + addendum = " However, it is set to a " + typeof contextType + "."; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = " Did you accidentally pass the Context.Provider instead?"; + } else if (contextType._context !== undefined) { + // + addendum = " Did you accidentally pass the Context.Consumer instead?"; + } else { + addendum = + " However, it is set to an object with keys {" + + Object.keys(contextType).join(", ") + + "}."; + } warningWithoutStack$1( false, "%s defines an invalid contextType. " + - "contextType should point to the Context object returned by React.createContext(). " + - "Did you accidentally pass the Context.Provider instead?", - getComponentName(ctor) || "Component" + "contextType should point to the Context object returned by React.createContext().%s", + getComponentName(ctor) || "Component", + addendum ); } } + } + if (typeof contextType === "object" && contextType !== null) { context = readContext(contextType); } else { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); @@ -7940,11 +8285,13 @@ var warnForMissingKey = function(child) {}; if (!child._store || child._store.validated || child.key != null) { return; } - invariant( - typeof child._store === "object", - "React Component in warnForMissingKey should have a _store. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!(typeof child._store === "object")) { + throw ReactError( + "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 = @@ -8000,19 +8347,24 @@ function coerceRef(returnFiber, current$$1, element) { var inst = void 0; if (owner) { var ownerFiber = owner; - invariant( - ownerFiber.tag === ClassComponent, - "Function components cannot have refs. " + - "Did you mean to use React.forwardRef()?" - ); + (function() { + if (!(ownerFiber.tag === ClassComponent)) { + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + } + })(); inst = ownerFiber.stateNode; } - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a " + - "bug in React. Please file an issue.", - mixedRef - ); + (function() { + if (!inst) { + throw ReactError( + "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 ( @@ -8038,20 +8390,22 @@ function coerceRef(returnFiber, current$$1, element) { ref._stringRef = stringRef; return ref; } else { - invariant( - typeof mixedRef === "string", - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) but no owner was set. This could happen for one of" + - " the following reasons:\n" + - "1. You may be adding a ref to a function component\n" + - "2. You may be adding a ref to a component that was not created inside a component's render method\n" + - "3. You have multiple copies of React loaded\n" + - "See https://fb.me/react-refs-must-have-owner for more information.", - mixedRef - ); + (function() { + if (!(typeof mixedRef === "string")) { + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + } + })(); + (function() { + if (!element._owner) { + throw ReactError( + "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; @@ -8066,14 +8420,18 @@ function throwOnInvalidObjectType(returnFiber, newChild) { "instead." + getCurrentFiberStackInDev(); } - invariant( - false, - "Objects are not valid as a React child (found: %s).%s", - Object.prototype.toString.call(newChild) === "[object Object]" - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - addendum - ); + (function() { + { + throw ReactError( + "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 + ); + } + })(); } } @@ -8732,11 +9090,13 @@ function ChildReconciler(shouldTrackSideEffects) { // but using the iterator instead. var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - typeof iteratorFn === "function", - "An object is not an iterable. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + if (!(typeof iteratorFn === "function")) { + throw ReactError( + "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. @@ -8786,7 +9146,11 @@ function ChildReconciler(shouldTrackSideEffects) { } var newChildren = iteratorFn.call(newChildrenIterable); - invariant(newChildren != null, "An iterable object provided no iterator."); + (function() { + if (!(newChildren != null)) { + throw ReactError("An iterable object provided no iterator."); + } + })(); var resultingFirstChild = null; var previousNewFiber = null; @@ -9157,13 +9521,14 @@ function ChildReconciler(shouldTrackSideEffects) { // eslint-disable-next-lined no-fallthrough case FunctionComponent: { var Component = returnFiber.type; - invariant( - false, - "%s(...): Nothing was returned from render. This usually means a " + - "return statement is missing. Or, to render nothing, " + - "return null.", - Component.displayName || Component.name || "Component" - ); + (function() { + { + throw ReactError( + (Component.displayName || Component.name || "Component") + + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." + ); + } + })(); } } } @@ -9179,10 +9544,11 @@ var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); function cloneChildFibers(current$$1, workInProgress) { - invariant( - current$$1 === null || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + (function() { + if (!(current$$1 === null || workInProgress.child === current$$1.child)) { + throw ReactError("Resuming work not yet implemented."); + } + })(); if (workInProgress.child === null) { return; @@ -9216,11 +9582,13 @@ var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + if (!(c !== NO_CONTEXT)) { + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); return c; } @@ -9276,6 +9644,37 @@ function pushHostContext(fiber) { push(contextStackCursor$1, nextContext, fiber); } +function pushHostContextForEventComponent(fiber) { + var context = requiredContext(contextStackCursor$1.current); + var nextContext = getChildHostContextForEventComponent(context); + + // Don't push this Fiber's context unless it's unique. + if (context === nextContext) { + return; + } + + // 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); +} + +function pushHostContextForEventTarget(fiber) { + var context = requiredContext(contextStackCursor$1.current); + var eventTargetType = fiber.type.type; + var nextContext = getChildHostContextForEventTarget(context, eventTargetType); + + // Don't push this Fiber's context unless it's unique. + if (context === nextContext) { + return; + } + + // 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); +} + function popHostContext(fiber) { // Do not pop unless this Fiber provided the current context. // pushHostContext() only pushes Fibers that provide unique contexts. @@ -9313,7 +9712,6 @@ var currentlyRenderingFiber$1 = null; // 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 firstCurrentHook = null; var currentHook = null; var nextCurrentHook = null; var firstWorkInProgressHook = null; @@ -9343,60 +9741,107 @@ var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev = null; -function warnOnHookMismatchInDev() { +// 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; + +function mountHookTypesDev() { { - var componentName = getComponentName(currentlyRenderingFiber$1.type); - if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { - didWarnAboutMismatchedHooksForComponent.add(componentName); + var hookName = currentHookNameInDev; - var secondColumnStart = 22; + if (hookTypesDev === null) { + hookTypesDev = [hookName]; + } else { + hookTypesDev.push(hookName); + } + } +} - var table = ""; - var prevHook = firstCurrentHook; - var nextHook = firstWorkInProgressHook; - var n = 1; - while (prevHook !== null && nextHook !== null) { - var oldHookName = prevHook._debugType; - var newHookName = nextHook._debugType; +function updateHookTypesDev() { + { + var hookName = currentHookNameInDev; - var row = n + ". " + oldHookName; - - // Extra space so second column lines up - // lol @ IE not supporting String#repeat - while (row.length < secondColumnStart) { - row += " "; - } - - row += newHookName + "\n"; - - table += row; - prevHook = prevHook.next; - nextHook = nextHook.next; - n++; + if (hookTypesDev !== null) { + hookTypesUpdateIndexDev++; + if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { + warnOnHookMismatchInDev(hookName); } + } + } +} +function checkDepsAreArrayDev(deps) { + { + if (deps !== undefined && deps !== null && !Array.isArray(deps)) { + // Verify deps, but only on mount to avoid extra checks. + // It's unlikely their type would change as usually you define them inline. warning$1( false, - "React has detected a change in the order of Hooks called by %s. " + - "This will lead to bugs and errors if not fixed. " + - "For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n" + - " Previous render Next render\n" + - " -------------------------------\n" + - "%s" + - " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", - componentName, - table + "%s received a final argument that is not an array (instead, received `%s`). When " + + "specified, the final argument must be an array.", + currentHookNameInDev, + typeof deps ); } } } +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 + // lol @ IE not supporting String#repeat + while (row.length < secondColumnStart) { + row += " "; + } + + row += newHookName + "\n"; + + table += row; + } + + warning$1( + false, + "React has detected a change in the order of Hooks called by %s. " + + "This will lead to bugs and errors if not fixed. " + + "For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n" + + " Previous render Next render\n" + + " ------------------------------------------------------\n" + + "%s" + + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", + componentName, + table + ); + } + } + } +} + function throwInvalidHookError() { - invariant( - false, - "Hooks can only be called inside the body of a function component. " + - "(https://fb.me/react-invalid-hook-call)" - ); + (function() { + { + throw ReactError( + "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) { @@ -9424,8 +9869,8 @@ function areHookInputsEqual(nextDeps, prevDeps) { "Previous: %s\n" + "Incoming: %s", currentHookNameInDev, - "[" + nextDeps.join(", ") + "]", - "[" + prevDeps.join(", ") + "]" + "[" + prevDeps.join(", ") + "]", + "[" + nextDeps.join(", ") + "]" ); } } @@ -9448,8 +9893,12 @@ function renderWithHooks( ) { renderExpirationTime = nextRenderExpirationTime; currentlyRenderingFiber$1 = workInProgress; - firstCurrentHook = nextCurrentHook = - current !== null ? current.memoizedState : null; + nextCurrentHook = current !== null ? current.memoizedState : null; + + { + hookTypesDev = current !== null ? current._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; + } // The following should have already been reset // currentHook = null; @@ -9463,11 +9912,26 @@ function renderWithHooks( // 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. { - ReactCurrentDispatcher$1.current = - nextCurrentHook === null - ? HooksDispatcherOnMountInDEV - : HooksDispatcherOnUpdateInDEV; + if (nextCurrentHook !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + // This dispatcher handles an edge case where a component is updating, + // but no stateful hooks have been used. + // We want to match the production code behavior (which will use HooksDispatcherOnMount), + // but with the extra DEV validation to ensure hooks ordering hasn't changed. + // This dispatcher does that. + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } } var children = Component(props, refOrContext); @@ -9478,14 +9942,18 @@ function renderWithHooks( numberOfReRenders += 1; // Start over from the beginning of the list - firstCurrentHook = nextCurrentHook = - current !== null ? current.memoizedState : null; + nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; currentHook = null; workInProgressHook = null; componentUpdateQueue = null; + { + // Also validate hook order for cascading updates. + hookTypesUpdateIndexDev = -1; + } + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; children = Component(props, refOrContext); @@ -9495,10 +9963,6 @@ function renderWithHooks( numberOfReRenders = 0; } - { - currentHookNameInDev = null; - } - // 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; @@ -9510,18 +9974,29 @@ function renderWithHooks( renderedWork.updateQueue = componentUpdateQueue; renderedWork.effectTag |= sideEffectTag; + { + renderedWork._debugHookTypes = hookTypesDev; + } + + // 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; renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; - firstCurrentHook = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + } + remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; @@ -9531,11 +10006,13 @@ function renderWithHooks( // renderPhaseUpdates = null; // numberOfReRenders = 0; - invariant( - !didRenderTooFewHooks, - "Rendered fewer hooks than expected. This may be caused by an accidental " + - "early return statement." - ); + (function() { + if (!!didRenderTooFewHooks) { + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); + } + })(); return children; } @@ -9559,21 +10036,23 @@ function resetHooks() { renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; - firstCurrentHook = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; + { + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + + currentHookNameInDev = null; + } + remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; - { - currentHookNameInDev = null; - } - didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; @@ -9590,9 +10069,6 @@ function mountWorkInProgressHook() { next: null }; - { - hook._debugType = currentHookNameInDev; - } if (workInProgressHook === null) { // This is the first hook in the list firstWorkInProgressHook = workInProgressHook = hook; @@ -9618,10 +10094,13 @@ function updateWorkInProgressHook() { nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. - invariant( - nextCurrentHook !== null, - "Rendered more hooks than during the previous render." - ); + (function() { + if (!(nextCurrentHook !== null)) { + throw ReactError( + "Rendered more hooks than during the previous render." + ); + } + })(); currentHook = nextCurrentHook; var newHook = { @@ -9642,13 +10121,6 @@ function updateWorkInProgressHook() { workInProgressHook = workInProgressHook.next = newHook; } nextCurrentHook = currentHook.next; - - { - newHook._debugType = currentHookNameInDev; - if (currentHookNameInDev !== currentHook._debugType) { - warnOnHookMismatchInDev(); - } - } } return workInProgressHook; } @@ -9663,20 +10135,6 @@ function basicStateReducer(state, action) { return typeof action === "function" ? action(state) : action; } -function mountContext(context, observedBits) { - { - mountWorkInProgressHook(); - } - return readContext(context, observedBits); -} - -function updateContext(context, observedBits) { - { - updateWorkInProgressHook(); - } - return readContext(context, observedBits); -} - function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); var initialState = void 0; @@ -9689,8 +10147,8 @@ function mountReducer(reducer, initialArg, init) { var queue = (hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialState + lastRenderedReducer: reducer, + lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( null, @@ -9704,10 +10162,15 @@ function mountReducer(reducer, initialArg, init) { function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; - invariant( - queue !== null, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + (function() { + if (!(queue !== null)) { + throw ReactError( + "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 @@ -9743,8 +10206,7 @@ function updateReducer(reducer, initialArg, init) { hook.baseState = newState; } - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } @@ -9794,6 +10256,16 @@ function updateReducer(reducer, initialArg, init) { remainingExpirationTime = 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. + markRenderEventTime$$1(updateExpirationTime); + // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the @@ -9823,8 +10295,7 @@ function updateReducer(reducer, initialArg, init) { hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; - queue.eagerReducer = reducer; - queue.eagerState = _newState; + queue.lastRenderedState = _newState; } var dispatch = queue.dispatch; @@ -9840,8 +10311,8 @@ function mountState(initialState) { var queue = (hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }); var dispatch = (queue.dispatch = dispatchAction.bind( null, @@ -10084,25 +10555,14 @@ function updateMemo(nextCreate, deps) { return nextValue; } -// in a test-like environment, we want to warn if dispatchAction() -// is called outside of a batchedUpdates/TestUtils.act(...) call. -var shouldWarnForUnbatchedSetState = false; - -{ - // jest isn't a 'global', it's just exposed to tests via a wrapped function - // further, this isn't a test file, so flow doesn't recognize the symbol. So... - // $FlowExpectedError - because requirements don't give a damn about your type sigs. - if ("undefined" !== typeof jest) { - shouldWarnForUnbatchedSetState = true; - } -} - function dispatchAction(fiber, queue, action) { - invariant( - numberOfReRenders < RE_RENDER_LIMIT, - "Too many re-renders. React limits the number of renders to prevent " + - "an infinite loop." - ); + (function() { + if (!(numberOfReRenders < RE_RENDER_LIMIT)) { + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); + } + })(); { !(arguments.length <= 3) @@ -10146,10 +10606,10 @@ function dispatchAction(fiber, queue, action) { lastRenderPhaseUpdate.next = update; } } else { - flushPassiveEffects(); + flushPassiveEffects$$1(); - var currentTime = requestCurrentTime(); - var _expirationTime = computeExpirationForFiber(currentTime, fiber); + var currentTime = requestCurrentTime$$1(); + var _expirationTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: _expirationTime, @@ -10181,21 +10641,21 @@ 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 _eagerReducer = queue.eagerReducer; - if (_eagerReducer !== null) { + var _lastRenderedReducer = queue.lastRenderedReducer; + if (_lastRenderedReducer !== null) { var prevDispatcher = void 0; { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { - var currentState = queue.eagerState; - var _eagerState = _eagerReducer(currentState, action); + var currentState = queue.lastRenderedState; + 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 = _eagerReducer; + _update2.eagerReducer = _lastRenderedReducer; _update2.eagerState = _eagerState; if (is(_eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. @@ -10214,11 +10674,14 @@ function dispatchAction(fiber, queue, action) { } } { - if (shouldWarnForUnbatchedSetState === true) { - warnIfNotCurrentlyBatchingInDev(fiber); + // jest isn't a 'global', it's just exposed to tests via a wrapped function + // further, this isn't a test file, so flow doesn't recognize the symbol. So... + // $FlowExpectedError - because requirements don't give a damn about your type sigs. + if ("undefined" !== typeof jest) { + warnIfNotCurrentlyActingUpdatesInDev$$1(fiber); } } - scheduleWork(fiber, _expirationTime); + scheduleWork$$1(fiber, _expirationTime); } } @@ -10238,6 +10701,7 @@ var ContextOnlyDispatcher = { }; var HooksDispatcherOnMountInDEV = null; +var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; var InvalidNestedHooksDispatcherOnMountInDEV = null; var InvalidNestedHooksDispatcherOnUpdateInDEV = null; @@ -10269,26 +10733,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; - return mountContext(context, observedBits); + mountHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); return mountLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; + mountHookTypesDev(); + checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10299,6 +10774,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10309,10 +10785,12 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useRef: function(initialValue) { currentHookNameInDev = "useRef"; + mountHookTypesDev(); return mountRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10323,6 +10801,81 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; + mountHookTypesDev(); + return mountDebugValue(value, formatterFn); + } + }; + + HooksDispatcherOnMountWithHookTypesInDEV = { + readContext: function(context, observedBits) { + return readContext(context, observedBits); + }, + useCallback: function(callback, deps) { + currentHookNameInDev = "useCallback"; + updateHookTypesDev(); + return mountCallback(callback, deps); + }, + useContext: function(context, observedBits) { + currentHookNameInDev = "useContext"; + updateHookTypesDev(); + return readContext(context, observedBits); + }, + useEffect: function(create, deps) { + currentHookNameInDev = "useEffect"; + updateHookTypesDev(); + return mountEffect(create, deps); + }, + useImperativeHandle: function(ref, create, deps) { + currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); + return mountImperativeHandle(ref, create, deps); + }, + useLayoutEffect: function(create, deps) { + currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); + return mountLayoutEffect(create, deps); + }, + useMemo: function(create, deps) { + currentHookNameInDev = "useMemo"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountMemo(create, deps); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useReducer: function(reducer, initialArg, init) { + currentHookNameInDev = "useReducer"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountReducer(reducer, initialArg, init); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useRef: function(initialValue) { + currentHookNameInDev = "useRef"; + updateHookTypesDev(); + return mountRef(initialValue); + }, + useState: function(initialState) { + currentHookNameInDev = "useState"; + updateHookTypesDev(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; + try { + return mountState(initialState); + } finally { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + }, + useDebugValue: function(value, formatterFn) { + currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); return mountDebugValue(value, formatterFn); } }; @@ -10333,26 +10886,32 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; + updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; - return updateContext(context, observedBits); + updateHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; + updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; + updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; + updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10363,6 +10922,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10373,10 +10933,12 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useRef: function(initialValue) { currentHookNameInDev = "useRef"; + updateHookTypesDev(); return updateRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10387,6 +10949,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; }, useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; + updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; @@ -10399,31 +10962,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; warnInvalidHookAccess(); - return mountContext(context, observedBits); + mountHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10435,6 +11004,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10446,11 +11016,13 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useRef: function(initialValue) { currentHookNameInDev = "useRef"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; warnInvalidHookAccess(); + mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { @@ -10462,6 +11034,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; warnInvalidHookAccess(); + mountHookTypesDev(); return mountDebugValue(value, formatterFn); } }; @@ -10474,31 +11047,37 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useCallback: function(callback, deps) { currentHookNameInDev = "useCallback"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function(context, observedBits) { currentHookNameInDev = "useContext"; warnInvalidHookAccess(); - return updateContext(context, observedBits); + updateHookTypesDev(); + return readContext(context, observedBits); }, useEffect: function(create, deps) { currentHookNameInDev = "useEffect"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function(ref, create, deps) { currentHookNameInDev = "useImperativeHandle"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function(create, deps) { currentHookNameInDev = "useLayoutEffect"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function(create, deps) { currentHookNameInDev = "useMemo"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10510,6 +11089,7 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useReducer: function(reducer, initialArg, init) { currentHookNameInDev = "useReducer"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10521,11 +11101,13 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useRef: function(initialValue) { currentHookNameInDev = "useRef"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateRef(initialValue); }, useState: function(initialState) { currentHookNameInDev = "useState"; warnInvalidHookAccess(); + updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { @@ -10537,11 +11119,16 @@ var InvalidNestedHooksDispatcherOnUpdateInDEV = null; useDebugValue: function(value, formatterFn) { currentHookNameInDev = "useDebugValue"; warnInvalidHookAccess(); + updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; } +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var now$2 = Scheduler.unstable_now; + var commitTime = 0; var profilerStartTime = -1; @@ -10553,7 +11140,7 @@ function recordCommitTime() { if (!enableProfilerTimer) { return; } - commitTime = now$$1(); + commitTime = now$2(); } function startProfilerTimer(fiber) { @@ -10561,10 +11148,10 @@ function startProfilerTimer(fiber) { return; } - profilerStartTime = now$$1(); + profilerStartTime = now$2(); if (fiber.actualStartTime < 0) { - fiber.actualStartTime = now$$1(); + fiber.actualStartTime = now$2(); } } @@ -10581,7 +11168,7 @@ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { } if (profilerStartTime >= 0) { - var elapsedTime = now$$1() - profilerStartTime; + var elapsedTime = now$2() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; @@ -10800,11 +11387,13 @@ function prepareToHydrateHostInstance( hostContext ) { if (!supportsHydration) { - invariant( - false, - "Expected prepareToHydrateHostInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var instance = fiber.stateNode; @@ -10828,11 +11417,13 @@ function prepareToHydrateHostInstance( function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { - invariant( - false, - "Expected prepareToHydrateHostTextInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var textInstance = fiber.stateNode; @@ -10876,18 +11467,22 @@ function prepareToHydrateHostTextInstance(fiber) { function skipPastDehydratedSuspenseInstance(fiber) { if (!supportsHydration) { - invariant( - false, - "Expected skipPastDehydratedSuspenseInstance() to never be called. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var suspenseInstance = fiber.stateNode; - invariant( - suspenseInstance, - "Expected to have a hydrated suspense instance. " + - "This error is likely caused by a bug in React. Please file an issue." - ); + (function() { + if (!suspenseInstance) { + throw ReactError( + "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance( suspenseInstance ); @@ -10966,17 +11561,21 @@ 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; { didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; + didWarnAboutMaxDuration = false; } function reconcileChildren( @@ -11642,12 +12241,13 @@ function pushHostRootContext(workInProgress) { function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; - invariant( - updateQueue !== null, - "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." - ); + (function() { + if (!(updateQueue !== null)) { + throw ReactError( + "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; @@ -11871,13 +12471,16 @@ function mountLazyComponent( // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. - invariant( - false, - "Element type is invalid. Received a promise that resolves to: %s. " + - "Lazy element type must resolve to a class or function.%s", - Component, - hint - ); + (function() { + { + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + Component + + ". Lazy element type must resolve to a class or function." + + hint + ); + } + })(); } } return child; @@ -12008,6 +12611,24 @@ function mountIndeterminateComponent( typeof value.render === "function" && value.$$typeof === undefined ) { + { + var _componentName = getComponentName(Component) || "Unknown"; + if (!didWarnAboutModulePatternComponent[_componentName]) { + warningWithoutStack$1( + false, + "The <%s /> component appears to be a function component that returns a class instance. " + + "Change %s to a class that extends React.Component instead. " + + "If you can't use a class try assigning the prototype on the function as a workaround. " + + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + + "cannot be called with `new` by React.", + _componentName, + _componentName, + _componentName + ); + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; @@ -12129,15 +12750,15 @@ function validateFunctionComponentInDev(workInProgress, Component) { typeof Component.contextType === "object" && Component.contextType !== null ) { - var _componentName = getComponentName(Component) || "Unknown"; + var _componentName2 = getComponentName(Component) || "Unknown"; - if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) { + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) { warningWithoutStack$1( false, "%s: Function components do not support contextType.", - _componentName + _componentName2 ); - didWarnAboutContextTypeOnFunctionComponent[_componentName] = true; + didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true; } } } @@ -12150,6 +12771,12 @@ function updateSuspenseComponent( var mode = workInProgress.mode; var nextProps = workInProgress.pendingProps; + { + if (shouldSuspend(workInProgress)) { + workInProgress.effectTag |= DidCapture; + } + } + // We should attempt to render the primary children unless this boundary // already suspended during this render (`alreadyCaptured` is true). var nextState = workInProgress.memoizedState; @@ -12163,12 +12790,26 @@ function updateSuspenseComponent( // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. nextState = { - timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork + fallbackExpirationTime: + nextState !== null ? nextState.fallbackExpirationTime : NoWork }; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } + { + if ("maxDuration" in nextProps) { + if (!didWarnAboutMaxDuration) { + didWarnAboutMaxDuration = true; + warning$1( + false, + "maxDuration has been removed from React. " + + "Remove the maxDuration prop." + ); + } + } + } + // 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 @@ -12419,15 +13060,73 @@ function updateSuspenseComponent( return next; } +function retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime +) { + // Detach from the current dehydrated boundary. + current$$1.alternate = null; + workInProgress.alternate = null; + + // Insert a deletion in the effect list. + var returnFiber = workInProgress.return; + (function() { + if (!(returnFiber !== null)) { + throw ReactError( + "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; + + // 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); +} + function updateDehydratedSuspenseComponent( current$$1, workInProgress, renderExpirationTime ) { + 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. - workInProgress.expirationTime = Never; + 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$$1(); + // 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) { @@ -12436,56 +13135,32 @@ function updateDehydratedSuspenseComponent( workInProgress.child = null; return null; } + 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; - var suspenseInstance = current$$1.stateNode; - if ( - didReceiveUpdate || - hasContextChanged$$1 || - isSuspenseInstanceFallback(suspenseInstance) - ) { + 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. - - // Alternatively, 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. - - // Detach from the current dehydrated boundary. - current$$1.alternate = null; - workInProgress.alternate = null; - - // Insert a deletion in the effect list. - var returnFiber = workInProgress.return; - invariant( - returnFiber !== null, - "Suspense boundaries are never on the root. " + - "This is probably a bug in React." + return retrySuspenseComponentWithoutHydrating( + current$$1, + workInProgress, + renderExpirationTime ); - 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; - - // 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); } else if (isSuspenseInstancePending(suspenseInstance)) { // This component is still pending more data from the server, so we can't hydrate its // content. We treat it as if this component suspended itself. It might seem as if @@ -12502,7 +13177,7 @@ function updateDehydratedSuspenseComponent( // Register a callback to retry this boundary once the server has sent the result. registerSuspenseInstanceRetry( suspenseInstance, - retryTimedOutBoundary.bind(null, current$$1) + retryTimedOutBoundary$$1.bind(null, current$$1) ); return null; } else { @@ -12683,6 +13358,55 @@ function updateContextConsumer( return workInProgress.child; } +function updateEventComponent$1( + current$$1, + workInProgress, + renderExpirationTime +) { + var nextProps = workInProgress.pendingProps; + var nextChildren = nextProps.children; + + reconcileChildren( + current$$1, + workInProgress, + nextChildren, + renderExpirationTime + ); + pushHostContextForEventComponent(workInProgress); + return workInProgress.child; +} + +function updateEventTarget(current$$1, workInProgress, renderExpirationTime) { + var type = workInProgress.type.type; + var nextProps = workInProgress.pendingProps; + var eventTargetChild = getEventTargetChildElement(type, nextProps); + + { + !(nextProps.children == null) + ? warning$1(false, "Event targets should not have children.") + : void 0; + } + if (eventTargetChild !== null) { + var child = (workInProgress.child = createFiberFromTypeAndProps( + eventTargetChild.type, + null, + eventTargetChild.props, + null, + workInProgress.mode, + renderExpirationTime + )); + child.return = workInProgress; + + if (current$$1 === null || current$$1.child === null) { + child.effectTag = Placement; + } + } else { + reconcileChildren(current$$1, workInProgress, null, renderExpirationTime); + } + pushHostContextForEventTarget(workInProgress); + return workInProgress.child; +} + function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } @@ -12812,8 +13536,19 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { // 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; } + break; + } + case EventComponent: + if (enableEventAPI) { + pushHostContextForEventComponent(workInProgress); + } + break; + case EventTarget: { + if (enableEventAPI) { + pushHostContextForEventTarget(workInProgress); + } + break; } } return bailoutOnAlreadyFinishedWork( @@ -12998,12 +13733,34 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { } break; } + case EventComponent: { + if (enableEventAPI) { + return updateEventComponent$1( + current$$1, + workInProgress, + renderExpirationTime + ); + } + break; + } + case EventTarget: { + if (enableEventAPI) { + return updateEventTarget( + current$$1, + workInProgress, + renderExpirationTime + ); + } + break; + } } - invariant( - false, - "Unknown unit of work tag. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } var valueCursor = createCursor(null); @@ -13106,10 +13863,10 @@ function calculateChangedBits(context, newValue, oldValue) { var changedBits = typeof context._calculateChangedBits === "function" ? context._calculateChangedBits(oldValue, newValue) - : maxSigned31BitInt; + : MAX_SIGNED_31_BIT_INT; { - !((changedBits & maxSigned31BitInt) === changedBits) + !((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits) ? warning$1( false, "calculateChangedBits: Expected the return value to be a " + @@ -13312,11 +14069,11 @@ function readContext(context, observedBits) { var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. if ( typeof observedBits !== "number" || - observedBits === maxSigned31BitInt + observedBits === MAX_SIGNED_31_BIT_INT ) { // Observe all updates. lastContextWithAllBitsObserved = context; - resolvedObservedBits = maxSigned31BitInt; + resolvedObservedBits = MAX_SIGNED_31_BIT_INT; } else { resolvedObservedBits = observedBits; } @@ -13328,13 +14085,13 @@ function readContext(context, observedBits) { }; if (lastContextDependency === null) { - invariant( - currentlyRenderingFiber !== null, - "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()." - ); + (function() { + if (!(currentlyRenderingFiber !== null)) { + throw ReactError( + "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. lastContextDependency = contextItem; @@ -13738,8 +14495,17 @@ function processUpdateQueue( newExpirationTime = updateExpirationTime; } } else { - // This update does have sufficient priority. Process it and compute - // a new result. + // 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. + markRenderEventTime$$1(updateExpirationTime); + + // Process it and compute a new result. resultState = getStateFromUpdate( workInProgress, queue, @@ -13848,12 +14614,14 @@ function processUpdateQueue( } function callCallback(callback, context) { - invariant( - typeof callback === "function", - "Invalid argument passed as callback. Expected a function. Instead " + - "received: %s", - callback - ); + (function() { + if (!(typeof callback === "function")) { + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + callback + ); + } + })(); callback.call(context); } @@ -14032,43 +14800,19 @@ if (supportsMutation) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; - if (isHidden) { - // This child is inside a timed out tree. Hide it. - instance = cloneHiddenInstance(instance, type, props, node); - } else { - // This child was previously inside a timed out tree. If it was not - // updated during this render, it may need to be unhidden. Clone - // again to be sure. - instance = cloneUnhiddenInstance(instance, type, props, node); - } - node.stateNode = instance; + instance = cloneHiddenInstance(instance, type, props, node); } appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - if (isHidden) { - _instance = createHiddenTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } else { - _instance = createTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } - node.stateNode = _instance; + _instance = cloneHiddenTextInstance(_instance, text, node); } appendInitialChild(parent, _instance); } else if (node.tag === HostPortal) { @@ -14076,22 +14820,28 @@ if (supportsMutation) { // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { - var current = node.alternate; - if (current !== null) { - var oldState = current.memoizedState; - var newState = node.memoizedState; - var oldIsHidden = oldState !== null; - var newIsHidden = newState !== null; - if (oldIsHidden !== newIsHidden) { - // The placeholder either just timed out or switched back to the normal - // children after having previously timed out. Toggle the visibility of - // the direct host children. - var primaryChildParent = newIsHidden ? node.child : node; + 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) { - appendAllChildren(parent, primaryChildParent, true, newIsHidden); + if (primaryChildParent.child !== null) { + primaryChildParent.child.return = primaryChildParent; + appendAllChildren( + parent, + primaryChildParent, + true, + newIsHidden + ); + } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { + fallbackChildParent.return = node; + node = fallbackChildParent; + continue; + } } - // eslint-disable-next-line no-labels - break branches; } } if (node.child !== null) { @@ -14135,43 +14885,19 @@ if (supportsMutation) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var props = node.memoizedProps; var type = node.type; - if (isHidden) { - // This child is inside a timed out tree. Hide it. - instance = cloneHiddenInstance(instance, type, props, node); - } else { - // This child was previously inside a timed out tree. If it was not - // updated during this render, it may need to be unhidden. Clone - // again to be sure. - instance = cloneUnhiddenInstance(instance, type, props, node); - } - node.stateNode = instance; + instance = cloneHiddenInstance(instance, type, props, node); } appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance2 = node.stateNode; - if (needsVisibilityToggle) { + if (needsVisibilityToggle && isHidden) { + // This child is inside a timed out tree. Hide it. var text = node.memoizedProps; - var rootContainerInstance = getRootHostContainer(); - var currentHostContext = getHostContext(); - if (isHidden) { - _instance2 = createHiddenTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } else { - _instance2 = createTextInstance( - text, - rootContainerInstance, - currentHostContext, - workInProgress - ); - } - node.stateNode = _instance2; + _instance2 = cloneHiddenTextInstance(_instance2, text, node); } appendChildToContainerChildSet(containerChildSet, _instance2); } else if (node.tag === HostPortal) { @@ -14179,27 +14905,28 @@ if (supportsMutation) { // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { - var current = node.alternate; - if (current !== null) { - var oldState = current.memoizedState; - var newState = node.memoizedState; - var oldIsHidden = oldState !== null; - var newIsHidden = newState !== null; - if (oldIsHidden !== newIsHidden) { - // The placeholder either just timed out or switched back to the normal - // children after having previously timed out. Toggle the visibility of - // the direct host children. - var primaryChildParent = newIsHidden ? node.child : node; + 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) { - appendAllChildrenToContainer( - containerChildSet, - primaryChildParent, - true, - newIsHidden - ); + if (primaryChildParent.child !== null) { + primaryChildParent.child.return = primaryChildParent; + appendAllChildrenToContainer( + containerChildSet, + primaryChildParent, + true, + newIsHidden + ); + } + var fallbackChildParent = primaryChildParent.sibling; + if (fallbackChildParent !== null) { + fallbackChildParent.return = node; + node = fallbackChildParent; + continue; + } } - // eslint-disable-next-line no-labels - break branches; } } if (node.child !== null) { @@ -14403,11 +15130,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { } } else { if (!newProps) { - invariant( - workInProgress.stateNode !== null, - "We must have new props for new mounts. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(workInProgress.stateNode !== null)) { + throw ReactError( + "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; } @@ -14476,11 +15205,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== "string") { - invariant( - workInProgress.stateNode !== null, - "We must have new props for new mounts. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(workInProgress.stateNode !== null)) { + throw ReactError( + "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(); @@ -14513,37 +15244,72 @@ function completeWork(current, workInProgress, renderExpirationTime) { } var nextDidTimeout = nextState !== null; - var prevDidTimeout = current !== null && current.memoizedState !== 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); - } else if (!nextDidTimeout && prevDidTimeout) { - // We just switched from the fallback to the normal children. Delete - // the fallback. - // TODO: Would it be better to store the fallback fragment on - 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; - } else { - workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; - currentFallbackChild.nextEffect = null; + } else { + var prevState = current.memoizedState; + prevDidTimeout = prevState !== null; + if (!nextDidTimeout && prevState !== null) { + // We just switched from the fallback to the normal children. + + // Mark the event time of the switching from fallback to normal children, + // based on the start of when we first showed the fallback. This time + var fallbackExpirationTimeExpTime = prevState.fallbackExpirationTime; + markRenderEventTime$$1(fallbackExpirationTimeExpTime); + + // 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; + } else { + workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; + currentFallbackChild.nextEffect = null; + } + currentFallbackChild.effectTag = Deletion; } - currentFallbackChild.effectTag = Deletion; } } - if (nextDidTimeout || prevDidTimeout) { - // If the children are hidden, or if they were previous hidden, schedule - // an effect to toggle their visibility. This is also used to attach a - // retry listener to the promise. - workInProgress.effectTag |= Update; + if (nextDidTimeout && !prevDidTimeout) { + // If this subtreee is running in concurrent mode we can suspend, + // otherwise we won't suspend. + // TODO: This will still suspend a synchronous tree if anything + // in the concurrent tree already suspended during this render. + // This is a known bug. + if ((workInProgress.mode & ConcurrentMode) !== NoContext) { + renderDidSuspend$$1(); + } + } + + if (supportsPersistence) { + // TODO: Only schedule updates if not prevDidTimeout. + if (nextDidTimeout) { + // If this boundary just timed out, schedule an effect to attach a + // retry listener to the proimse. This flag is also used to hide the + // primary children. + workInProgress.effectTag |= Update; + } + } + if (supportsMutation) { + // TODO: Only schedule updates if these values are non equal, i.e. it changed. + if (nextDidTimeout || prevDidTimeout) { + // If this boundary just timed out, schedule an effect to attach a + // retry listener to the proimse. This flag is also used to hide the + // primary children. In mutation mode, we also need the flag to + // *unhide* children that were previously hidden, so check if the + // is currently timed out, too. + workInProgress.effectTag |= Update; + } } break; } @@ -14578,11 +15344,13 @@ function completeWork(current, workInProgress, renderExpirationTime) { if (enableSuspenseServerRenderer) { if (current === null) { var _wasHydrated2 = popHydrationState(workInProgress); - invariant( - _wasHydrated2, - "A dehydrated suspense component was completed without a hydrated node. " + - "This is probably a bug in React." - ); + (function() { + if (!_wasHydrated2) { + throw ReactError( + "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React." + ); + } + })(); skipPastDehydratedSuspenseInstance(workInProgress); } else if ((workInProgress.effectTag & DidCapture) === NoEffect) { // This boundary did not suspend so it's now hydrated. @@ -14597,12 +15365,61 @@ function completeWork(current, workInProgress, renderExpirationTime) { } break; } + case EventComponent: { + if (enableEventAPI) { + popHostContext(workInProgress); + var _rootContainerInstance2 = getRootHostContainer(); + var responder = workInProgress.type.responder; + var eventComponentInstance = workInProgress.stateNode; + + if (eventComponentInstance === null) { + var responderState = null; + if (responder.createInitialState !== undefined) { + responderState = responder.createInitialState(newProps); + } + eventComponentInstance = workInProgress.stateNode = { + context: null, + props: newProps, + responder: responder, + rootInstance: _rootContainerInstance2, + state: responderState + }; + mountEventComponent(eventComponentInstance); + } else { + // Update the props on the event component state node + eventComponentInstance.props = newProps; + // Update the root container, so we can properly unmount events at some point + eventComponentInstance.rootInstance = _rootContainerInstance2; + updateEventComponent(eventComponentInstance); + } + } + break; + } + case EventTarget: { + if (enableEventAPI) { + popHostContext(workInProgress); + var _type = workInProgress.type.type; + var _rootContainerInstance3 = getRootHostContainer(); + var shouldUpdate = handleEventTarget( + _type, + newProps, + _rootContainerInstance3, + workInProgress + ); + if (shouldUpdate) { + markUpdate(workInProgress); + } + } + break; + } default: - invariant( - false, - "Unknown unit of work tag. This error is likely caused by a bug in " + - "React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } return null; @@ -14799,7 +15616,7 @@ function safelyCallComponentWillUnmount(current$$1, instance) { ); if (hasCaughtError()) { var unmountError = clearCaughtError(); - captureCommitPhaseError(current$$1, unmountError); + captureCommitPhaseError$$1(current$$1, unmountError); } } } @@ -14812,7 +15629,7 @@ function safelyDetachRef(current$$1) { invokeGuardedCallback(null, ref, null, null); if (hasCaughtError()) { var refError = clearCaughtError(); - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } } } else { @@ -14826,7 +15643,7 @@ function safelyCallDestroy(current$$1, destroy) { invokeGuardedCallback(null, destroy, null); if (hasCaughtError()) { var error = clearCaughtError(); - captureCommitPhaseError(current$$1, error); + captureCommitPhaseError$$1(current$$1, error); } } } @@ -14907,14 +15724,17 @@ function commitBeforeMutationLifeCycles(current$$1, finishedWork) { case HostText: case HostPortal: case IncompleteClassComponent: + case EventTarget: // Nothing to do for these component types return; default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -14950,22 +15770,23 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { } else if (typeof _destroy.then === "function") { addendum = "\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. " + - "Instead, you may write an async function separately " + - "and then call it from inside the effect:\n\n" + - "async function fetchComment(commentId) {\n" + - " // You can await here\n" + - "}\n\n" + + "Instead, write the async function inside your effect " + + "and call it immediately:\n\n" + "useEffect(() => {\n" + - " fetchComment(commentId);\n" + - "}, [commentId]);\n\n" + - "In the future, React will provide a more idiomatic solution for data fetching " + - "that doesn't involve writing effects manually."; + " async function fetchData() {\n" + + " // You can await here\n" + + " const response = await MyAPI.getData(someId);\n" + + " // ...\n" + + " }\n" + + " fetchData();\n" + + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + + "Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching"; } else { addendum = " You returned: " + _destroy; } warningWithoutStack$1( false, - "An Effect function must not return anything besides a function, " + + "An effect function must not return anything besides a function, " + "which is used for clean-up.%s%s", addendum, getStackByFiberInDevAndProd(finishedWork) @@ -15201,15 +16022,17 @@ function commitLifeCycles( return; } case SuspenseComponent: - break; case IncompleteClassComponent: + case EventTarget: break; default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -15356,6 +16179,13 @@ function commitUnmount(current$$1) { } return; } + case EventComponent: { + if (enableEventAPI) { + var eventComponentInstance = current$$1.stateNode; + unmountEventComponent(eventComponentInstance); + current$$1.stateNode = null; + } + } } } @@ -15430,13 +16260,10 @@ function commitContainer(finishedWork) { } switch (finishedWork.tag) { - case ClassComponent: { - return; - } - case HostComponent: { - return; - } - case HostText: { + case ClassComponent: + case HostComponent: + case HostText: + case EventTarget: { return; } case HostRoot: @@ -15449,11 +16276,13 @@ function commitContainer(finishedWork) { return; } default: { - invariant( - false, - "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() { + { + throw ReactError( + "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } } } @@ -15466,11 +16295,13 @@ function getHostParentFiber(fiber) { } parent = parent.return; } - invariant( - false, - "Expected to find a host parent. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); } function isHostParent(fiber) { @@ -15552,11 +16383,13 @@ function commitPlacement(finishedWork) { isContainer = true; break; default: - invariant( - false, - "Invalid host parent fiber. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + { + throw ReactError( + "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 @@ -15569,17 +16402,18 @@ function commitPlacement(finishedWork) { var node = finishedWork; while (true) { if (node.tag === HostComponent || node.tag === HostText) { + var stateNode = node.stateNode; if (before) { if (isContainer) { - insertInContainerBefore(parent, node.stateNode, before); + insertInContainerBefore(parent, stateNode, before); } else { - insertBefore(parent, node.stateNode, before); + insertBefore(parent, stateNode, before); } } else { if (isContainer) { - appendChildToContainer(parent, node.stateNode); + appendChildToContainer(parent, stateNode); } else { - appendChild(parent, node.stateNode); + appendChild(parent, stateNode); } } } else if (node.tag === HostPortal) { @@ -15621,11 +16455,13 @@ function unmountHostComponents(current$$1) { if (!currentParentIsValid) { var parent = node.return; findParent: while (true) { - invariant( - parent !== null, - "Expected to find a host parent. This error is likely caused by " + - "a bug in React. Please file an issue." - ); + (function() { + if (!(parent !== null)) { + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); switch (parent.tag) { case HostComponent: currentParent = parent.stateNode; @@ -15728,6 +16564,13 @@ function commitWork(current$$1, finishedWork) { commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } + case Profiler: { + return; + } + case SuspenseComponent: { + commitSuspenseComponent(finishedWork); + return; + } } commitContainer(finishedWork); @@ -15775,11 +16618,13 @@ function commitWork(current$$1, finishedWork) { return; } case HostText: { - invariant( - finishedWork.stateNode !== null, - "This should have a text node initialized. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(finishedWork.stateNode !== null)) { + throw ReactError( + "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 @@ -15789,6 +16634,36 @@ function commitWork(current$$1, finishedWork) { commitTextUpdate(textInstance, oldText, newText); return; } + case EventTarget: { + if (enableEventAPI) { + var _type = finishedWork.type.type; + var props = finishedWork.memoizedProps; + var _instance4 = finishedWork.stateNode; + var parentInstance = null; + + var node = finishedWork.return; + // Traverse up the fiber tree until we find the parent host node. + while (node !== null) { + if (node.tag === HostComponent) { + parentInstance = node.stateNode; + break; + } else if (node.tag === HostRoot) { + parentInstance = node.stateNode.containerInfo; + break; + } + node = node.return; + } + (function() { + if (!(parentInstance !== null)) { + throw ReactError( + "This should have a parent host component initialized. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + commitEventTarget(_type, props, _instance4, parentInstance); + } + return; + } case HostRoot: { return; } @@ -15796,63 +16671,72 @@ function commitWork(current$$1, finishedWork) { return; } case SuspenseComponent: { - var newState = finishedWork.memoizedState; - - var newDidTimeout = void 0; - var primaryChildParent = finishedWork; - if (newState === null) { - newDidTimeout = false; - } else { - newDidTimeout = true; - primaryChildParent = finishedWork.child; - if (newState.timedOutAt === NoWork) { - // If the children had not already timed out, record the time. - // This is used to compute the elapsed time during subsequent - // attempts to render the children. - newState.timedOutAt = requestCurrentTime(); - } - } - - if (primaryChildParent !== null) { - hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); - } - - // 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(); - } - thenables.forEach(function(thenable) { - // Memoize using the boundary fiber to prevent redundant listeners. - var retry = resolveRetryThenable.bind(null, finishedWork, thenable); - if (enableSchedulerTracing) { - retry = tracing.unstable_wrap(retry); - } - if (!retryCache.has(thenable)) { - retryCache.add(thenable); - thenable.then(retry, retry); - } - }); - } - + commitSuspenseComponent(finishedWork); return; } case IncompleteClassComponent: { return; } default: { - invariant( - false, - "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() { + { + throw ReactError( + "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 primaryChildParent = finishedWork; + if (newState === null) { + newDidTimeout = false; + } else { + newDidTimeout = true; + primaryChildParent = finishedWork.child; + if (newState.fallbackExpirationTime === NoWork) { + // If the children had not already timed out, record the time. + // This is used to compute the elapsed time during subsequent + // attempts to render the children. + // We model this as a normal pri expiration time since that's + // how we infer start time for updates. + newState.fallbackExpirationTime = computeAsyncExpirationNoBucket( + requestCurrentTime$$1() ); } } + + if (supportsMutation && primaryChildParent !== null) { + hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); + } + + // 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(); + } + thenables.forEach(function(thenable) { + // Memoize using the boundary fiber to prevent redundant listeners. + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + if (enableSchedulerTracing) { + retry = tracing.unstable_wrap(retry); + } + if (!retryCache.has(thenable)) { + retryCache.add(thenable); + thenable.then(retry, retry); + } + }); + } } function commitResetTextContent(current$$1) { @@ -15874,7 +16758,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { update.payload = { element: null }; var error = errorInfo.value; update.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return update; @@ -15900,7 +16784,7 @@ function createClassErrorUpdate(fiber, errorInfo, expirationTime) { // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. - markLegacyErrorBoundaryAsFailed(this); + markLegacyErrorBoundaryAsFailed$$1(this); } var error = errorInfo.value; var stack = errorInfo.stack; @@ -15948,7 +16832,7 @@ function attachPingListener(root, renderExpirationTime, thenable) { if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); - var ping = pingSuspendedRoot.bind( + var ping = pingSuspendedRoot$$1.bind( null, root, thenable, @@ -15981,48 +16865,8 @@ function throwException( // This is a thenable. var thenable = value; - // Find the earliest timeout threshold of all the placeholders in the - // ancestor path. We could avoid this traversal by storing the thresholds on - // the stack, but we choose not to because we only hit this path if we're - // IO-bound (i.e. if something suspends). Whereas the stack is used even in - // the non-IO- bound case. - var _workInProgress = returnFiber; - var earliestTimeoutMs = -1; - var startTimeMs = -1; - do { - if (_workInProgress.tag === SuspenseComponent) { - var current$$1 = _workInProgress.alternate; - if (current$$1 !== null) { - var currentState = current$$1.memoizedState; - if (currentState !== null) { - // Reached a boundary that already timed out. Do not search - // any further. - var timedOutAt = currentState.timedOutAt; - startTimeMs = expirationTimeToMs(timedOutAt); - // Do not search any further. - break; - } - } - var timeoutPropMs = _workInProgress.pendingProps.maxDuration; - if (typeof timeoutPropMs === "number") { - if (timeoutPropMs <= 0) { - earliestTimeoutMs = 0; - } else if ( - earliestTimeoutMs === -1 || - timeoutPropMs < earliestTimeoutMs - ) { - earliestTimeoutMs = timeoutPropMs; - } - } - } - // If there is a DehydratedSuspenseComponent we don't have to do anything because - // if something suspends inside it, we will simply leave that as dehydrated. It - // will never timeout. - _workInProgress = _workInProgress.return; - } while (_workInProgress !== null); - // Schedule the nearest Suspense to re-render the timed out view. - _workInProgress = returnFiber; + var _workInProgress = returnFiber; do { if ( _workInProgress.tag === SuspenseComponent && @@ -16048,7 +16892,7 @@ function throwException( // Note: It doesn't matter whether the component that suspended was // inside a concurrent mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. - if ((_workInProgress.mode & ConcurrentMode) === NoEffect) { + if ((_workInProgress.mode & ConcurrentMode) === NoContext) { _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. @@ -16086,41 +16930,6 @@ function throwException( attachPingListener(root, renderExpirationTime, thenable); - var absoluteTimeoutMs = void 0; - if (earliestTimeoutMs === -1) { - // If no explicit threshold is given, default to an arbitrarily large - // value. The actual size doesn't matter because the threshold for the - // whole tree will be clamped to the expiration time. - absoluteTimeoutMs = maxSigned31BitInt; - } else { - if (startTimeMs === -1) { - // This suspend happened outside of any already timed-out - // placeholders. We don't know exactly when the update was - // scheduled, but we can infer an approximate start time from the - // expiration time. First, find the earliest uncommitted expiration - // time in the tree, including work that is suspended. Then subtract - // the offset used to compute an async update's expiration time. - // This will cause high priority (interactive) work to expire - // earlier than necessary, but we can account for this by adjusting - // for the Just Noticeable Difference. - var earliestExpirationTime = findEarliestOutstandingPriorityLevel( - root, - renderExpirationTime - ); - var earliestExpirationTimeMs = expirationTimeToMs( - earliestExpirationTime - ); - startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; - } - absoluteTimeoutMs = startTimeMs + earliestTimeoutMs; - } - - // Mark the earliest timeout in the suspended fiber's ancestor path. - // After completing the root, we'll take the largest of all the - // suspended fiber's timeouts and use it to compute a timeout for the - // whole tree. - renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime); - _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; @@ -16134,18 +16943,20 @@ function throwException( var retryCache = _workInProgress.memoizedState; if (retryCache === null) { retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); - var _current = _workInProgress.alternate; - invariant( - _current, - "A dehydrated suspense boundary must commit before trying to render. " + - "This is probably a bug in React." - ); - _current.memoizedState = retryCache; + var current$$1 = _workInProgress.alternate; + (function() { + if (!current$$1) { + throw ReactError( + "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( + var retry = resolveRetryThenable$$1.bind( null, _workInProgress, thenable @@ -16178,7 +16989,7 @@ function throwException( // 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(); + renderDidError$$1(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; do { @@ -16205,7 +17016,7 @@ function throwException( (typeof ctor.getDerivedStateFromError === "function" || (instance !== null && typeof instance.componentDidCatch === "function" && - !isAlreadyFailedLegacyErrorBoundary(instance))) + !isAlreadyFailedLegacyErrorBoundary$$1(instance))) ) { workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; @@ -16244,11 +17055,13 @@ function unwindWork(workInProgress, renderExpirationTime) { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; - invariant( - (_effectTag & DidCapture) === NoEffect, - "The root failed to unmount after an error. This is likely a bug in " + - "React. Please file an issue." - ); + (function() { + if (!((_effectTag & DidCapture) === NoEffect)) { + throw ReactError( + "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; } @@ -16285,6 +17098,12 @@ function unwindWork(workInProgress, renderExpirationTime) { case ContextProvider: popProvider(workInProgress); return null; + case EventComponent: + case EventTarget: + if (enableEventAPI) { + popHostContext(workInProgress); + } + return null; default: return null; } @@ -16319,8 +17138,20 @@ function unwindInterruptedWork(interruptedWork) { } } +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +// Intentionally not named imports because Rollup would use dynamic dispatch for +// CommonJS interop named imports. +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback; +var cancelCallback$1 = Scheduler.unstable_cancelCallback; +var shouldYield$1 = Scheduler.unstable_shouldYield; +var now$1 = Scheduler.unstable_now; +var getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel; +var NormalPriority$1 = Scheduler.unstable_NormalPriority; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; +var ReactShouldWarnActingUpdates = + ReactSharedInternals.ReactShouldWarnActingUpdates; var didWarnAboutStateTransition = void 0; var didWarnSetStateChildContext = void 0; @@ -16330,14 +17161,18 @@ var warnAboutInvalidUpdates = void 0; 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 - invariant( - tracing.__interactionsRef != null && - tracing.__interactionsRef.current != null, - "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" - ); + (function() { + if ( + !( + tracing.__interactionsRef != null && + tracing.__interactionsRef.current != null + ) + ) { + throw ReactError( + "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" + ); + } + })(); } { @@ -16392,6 +17227,11 @@ if (enableSchedulerTracing) { }; } +// Represents the expiration time that incoming updates should use. (If this +// is NoWork, use the default strategy: async updates in async mode, sync +// updates in sync mode.) +var expirationContext = NoWork; + var isWorking = false; // The next work in progress fiber that we're currently working on. @@ -16399,7 +17239,8 @@ var nextUnitOfWork = null; var nextRoot = null; // The time at which we're currently rendering work. var nextRenderExpirationTime = NoWork; -var nextLatestAbsoluteTimeoutMs = -1; +var mostRecentEventTime = Sync; +var nextRenderDidSuspend = false; var nextRenderDidError = false; // The next fiber with an effect that we're currently committing. @@ -16522,7 +17363,8 @@ function resetStack() { nextRoot = null; nextRenderExpirationTime = NoWork; - nextLatestAbsoluteTimeoutMs = -1; + mostRecentEventTime = Sync; + nextRenderDidSuspend = false; nextRenderDidError = false; nextUnitOfWork = null; } @@ -16675,14 +17517,16 @@ function commitPassiveEffects(root, firstEffect) { var didError = false; var error = void 0; { + isInPassiveEffectDEV = true; invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); + isInPassiveEffectDEV = false; if (hasCaughtError()) { didError = true; error = clearCaughtError(); } } if (didError) { - captureCommitPhaseError(effect, error); + captureCommitPhaseError$1(effect, error); } } effect = effect.nextEffect; @@ -16702,16 +17546,24 @@ function commitPassiveEffects(root, firstEffect) { if (!isBatchingUpdates && !isRendering) { performSyncWork(); } + + { + if (rootWithPendingPassiveEffects === root) { + nestedPassiveEffectCountDEV++; + } else { + nestedPassiveEffectCountDEV = 0; + } + } } -function isAlreadyFailedLegacyErrorBoundary(instance) { +function isAlreadyFailedLegacyErrorBoundary$1(instance) { return ( legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance) ); } -function markLegacyErrorBoundaryAsFailed(instance) { +function markLegacyErrorBoundaryAsFailed$1(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); } else { @@ -16719,15 +17571,17 @@ function markLegacyErrorBoundaryAsFailed(instance) { } } -function flushPassiveEffects() { +function flushPassiveEffects$1() { + var didFlushEffects = passiveEffectCallback !== null; if (passiveEffectCallbackHandle !== null) { - cancelPassiveEffects(passiveEffectCallbackHandle); + cancelCallback$1(passiveEffectCallbackHandle); } if (passiveEffectCallback !== null) { // We call the scheduled callback instead of commitPassiveEffects directly // to ensure tracing works correctly. passiveEffectCallback(); } + return didFlushEffects; } function commitRoot(root, finishedWork) { @@ -16735,18 +17589,21 @@ function commitRoot(root, finishedWork) { isCommitting$1 = true; startCommitTimer(); - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug " + - "related to the return field. This error is likely caused by a bug " + - "in React. Please file an issue." - ); + (function() { + if (!(root.current !== finishedWork)) { + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - committedExpirationTime !== NoWork, - "Cannot commit an incomplete root. This error is likely caused by a " + - "bug in React. Please file an issue." - ); + (function() { + if (!(committedExpirationTime !== NoWork)) { + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); root.pendingCommitExpirationTime = NoWork; // Update the pending priority levels to account for the work that we are @@ -16804,12 +17661,14 @@ function commitRoot(root, finishedWork) { } } if (didError) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, error); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; @@ -16840,12 +17699,14 @@ function commitRoot(root, finishedWork) { } } if (_didError) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, _error); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, _error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; @@ -16885,12 +17746,14 @@ function commitRoot(root, finishedWork) { } } if (_didError2) { - invariant( - nextEffect !== null, - "Should have next effect. This error is likely caused by a bug " + - "in React. Please file an issue." - ); - captureCommitPhaseError(nextEffect, _error2); + (function() { + if (!(nextEffect !== null)) { + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); + captureCommitPhaseError$1(nextEffect, _error2); if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; } @@ -16909,11 +17772,9 @@ function commitRoot(root, finishedWork) { // here because that code is still in flux. callback = tracing.unstable_wrap(callback); } - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return schedulePassiveEffects(callback); - } + passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + callback ); passiveEffectCallback = callback; } @@ -17317,20 +18178,22 @@ function workLoop(isYieldy) { } } else { // Flush asynchronous work until there's a higher priority event - while (nextUnitOfWork !== null && !shouldYield$$1()) { + while (nextUnitOfWork !== null && !shouldYield$1()) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } } function renderRoot(root, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused " + - "by a bug in React. Please file an issue." - ); + (function() { + if (!!isWorking) { + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); - flushPassiveEffects(); + flushPassiveEffects$1(); isWorking = true; var previousDispatcher = ReactCurrentDispatcher.current; @@ -17430,7 +18293,7 @@ function renderRoot(root, isYieldy) { if (nextUnitOfWork === null) { // This is a fatal error. didFatal = true; - onUncaughtError(thrownValue); + onUncaughtError$1(thrownValue); } else { if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) { // Record the time spent rendering before an error was thrown. @@ -17454,12 +18317,13 @@ function renderRoot(root, isYieldy) { // TODO: we already know this isn't true in some cases. // At least this shows a nicer error message until we figure out the cause. // https://github.com/facebook/react/issues/12449#issuecomment-386727431 - invariant( - nextUnitOfWork !== null, - "Failed to replay rendering after an error. This " + - "is likely caused by a bug in React. Please file an issue " + - "with a reproducing case to help us find it." - ); + (function() { + if (!(nextUnitOfWork !== null)) { + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); + } + })(); var sourceFiber = nextUnitOfWork; var returnFiber = sourceFiber.return; @@ -17471,7 +18335,7 @@ function renderRoot(root, isYieldy) { // which phase it fails in, but doesn't seem worth it. At least // for now. didFatal = true; - onUncaughtError(thrownValue); + onUncaughtError$1(thrownValue); } else { throwException( root, @@ -17532,11 +18396,13 @@ function renderRoot(root, isYieldy) { var didCompleteRoot = true; stopWorkLoopTimer(interruptedBy, didCompleteRoot); var rootWorkInProgress = root.current.alternate; - invariant( - rootWorkInProgress !== null, - "Finished root should have a work-in-progress. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(rootWorkInProgress !== null)) { + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); // `nextRoot` points to the in-progress root. A non-null value indicates // that we're in the middle of an async render. Set it to null to indicate @@ -17585,32 +18451,23 @@ function renderRoot(root, isYieldy) { } } - if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) { + // Check if we should suspend this commit. + // If mostRecentEventTime is Sync, that means we didn't track any event + // times. That can happen if we retried but nothing switched from fallback + // to content. There's no reason to delay doing no work. + if (isYieldy && nextRenderDidSuspend && mostRecentEventTime !== Sync) { // The tree was suspended. var _suspendedExpirationTime2 = expirationTime; markSuspendedPriorityLevel(root, _suspendedExpirationTime2); - // Find the earliest uncommitted expiration time in the tree, including - // work that is suspended. The timeout threshold cannot be longer than - // the overall expiration. - var earliestExpirationTime = findEarliestOutstandingPriorityLevel( - root, - expirationTime - ); - var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime); - if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) { - nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs; - } - - // Subtract the current time from the absolute timeout to get the number - // of milliseconds until the timeout. In other words, convert an absolute - // timestamp to a relative time. This is the value that is passed - // to `setTimeout`. - var currentTimeMs = expirationTimeToMs(requestCurrentTime()); - var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs; - msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout; + var eventTimeMs = inferTimeFromExpirationTime(mostRecentEventTime); + var currentTimeMs = now$1(); + var timeElapsed = currentTimeMs - eventTimeMs; // TODO: Account for the Just Noticeable Difference + var timeoutMs = 150; + var msUntilTimeout = timeoutMs - timeElapsed; + msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout; var _rootExpirationTime2 = root.expirationTime; onSuspend( @@ -17627,7 +18484,7 @@ function renderRoot(root, isYieldy) { onComplete(root, rootWorkInProgress, expirationTime); } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { var expirationTime = Sync; var fiber = sourceFiber.return; while (fiber !== null) { @@ -17638,12 +18495,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( typeof ctor.getDerivedStateFromError === "function" || (typeof instance.componentDidCatch === "function" && - !isAlreadyFailedLegacyErrorBoundary(instance)) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { var errorInfo = createCapturedValue(value, sourceFiber); var update = createClassErrorUpdate(fiber, errorInfo, expirationTime); enqueueUpdate(fiber, update); - scheduleWork(fiber, expirationTime); + scheduleWork$1(fiber, expirationTime); return; } break; @@ -17651,7 +18508,7 @@ function captureCommitPhaseError(sourceFiber, value) { var _errorInfo = createCapturedValue(value, sourceFiber); var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime); enqueueUpdate(fiber, _update); - scheduleWork(fiber, expirationTime); + scheduleWork$1(fiber, expirationTime); return; } } @@ -17669,7 +18526,7 @@ function captureCommitPhaseError(sourceFiber, value) { expirationTime ); enqueueUpdate(rootFiber, _update2); - scheduleWork(rootFiber, expirationTime); + scheduleWork$1(rootFiber, expirationTime); } } @@ -17678,77 +18535,80 @@ function computeThreadID(expirationTime, interactionThreadID) { return expirationTime * 1000 + interactionThreadID; } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(); - +function computeExpirationForFiber$1(currentTime, fiber) { var expirationTime = void 0; - if ((fiber.mode & ConcurrentMode) === NoContext) { - // Outside of concurrent mode, updates are always synchronous. - expirationTime = Sync; - } else if (isWorking && !isCommitting$1) { - // During render phase, updates expire during as the current render. - expirationTime = nextRenderExpirationTime; + if (expirationContext !== NoWork) { + // An explicit expiration context was set; + expirationTime = expirationContext; + } else if (isWorking) { + if (isCommitting$1) { + // Updates that occur during the commit phase should have sync priority + // by default. + expirationTime = Sync; + } else { + // Updates during the render phase should expire at the same time as + // the work that is being rendered. + expirationTime = nextRenderExpirationTime; + } } else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = Sync; - break; - case scheduler.unstable_UserBlockingPriority: + // No explicit expiration context was set, and we're not currently + // performing work. Calculate a new expiration time. + if (fiber.mode & ConcurrentMode) { + if (isBatchingInteractiveUpdates) { + // This is an interactive update expirationTime = computeInteractiveExpiration(currentTime); - break; - case scheduler.unstable_NormalPriority: - // This is a normal, concurrent update + } else { + // This is an async update expirationTime = computeAsyncExpiration(currentTime); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = Never; - break; - default: - invariant( - false, - "Unknown priority level. This error is likely caused by a bug in " + - "React. Please file an issue." - ); - } - - // If we're in the middle of rendering a tree, do not update at the same - // expiration time that is already rendering. - if (nextRoot !== null && expirationTime === nextRenderExpirationTime) { - expirationTime -= 1; + } + // If we're in the middle of rendering a tree, do not update at the same + // expiration time that is already rendering. + if (nextRoot !== null && expirationTime === nextRenderExpirationTime) { + expirationTime -= 1; + } + } else { + // This is a sync update + expirationTime = Sync; } } - - // Keep track of the lowest pending interactive expiration time. This - // allows us to synchronously flush all interactive updates - // when needed. - // TODO: Move this to renderer? - if ( - priorityLevel === scheduler.unstable_UserBlockingPriority && - (lowestPriorityPendingInteractiveExpirationTime === NoWork || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) - ) { - lowestPriorityPendingInteractiveExpirationTime = expirationTime; + if (isBatchingInteractiveUpdates) { + // This is an interactive update. Keep track of the lowest pending + // interactive expiration time. This allows us to synchronously flush + // all interactive updates when needed. + if ( + lowestPriorityPendingInteractiveExpirationTime === NoWork || + expirationTime < lowestPriorityPendingInteractiveExpirationTime + ) { + lowestPriorityPendingInteractiveExpirationTime = expirationTime; + } } - return expirationTime; } -function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) { - // Schedule the timeout. - if ( - absoluteTimeoutMs >= 0 && - nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs - ) { - nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs; +function markRenderEventTime$1(expirationTime) { + if (expirationTime < mostRecentEventTime) { + mostRecentEventTime = expirationTime; } } -function renderDidError() { +function renderDidSuspend$1() { + nextRenderDidSuspend = true; +} + +function renderDidError$1() { nextRenderDidError = true; } -function pingSuspendedRoot(root, thenable, pingTime) { +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 + originalStartTimeMs + ); +} + +function pingSuspendedRoot$1(root, thenable, pingTime) { // A promise that previously suspended React from committing has resolved. // If React is still suspended, try again at the previous level (pingTime). @@ -17776,9 +18636,9 @@ function pingSuspendedRoot(root, thenable, pingTime) { } } -function retryTimedOutBoundary(boundaryFiber) { - var currentTime = requestCurrentTime(); - var retryTime = computeExpirationForFiber(currentTime, boundaryFiber); +function retryTimedOutBoundary$1(boundaryFiber) { + var currentTime = requestCurrentTime$1(); + var retryTime = computeExpirationForFiber$1(currentTime, boundaryFiber); var root = scheduleWorkToRoot(boundaryFiber, retryTime); if (root !== null) { markPendingPriorityLevel(root, retryTime); @@ -17789,7 +18649,7 @@ function retryTimedOutBoundary(boundaryFiber) { } } -function resolveRetryThenable(boundaryFiber, thenable) { +function resolveRetryThenable$1(boundaryFiber, thenable) { // The boundary fiber (a Suspense component) previously timed out and 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 @@ -17803,11 +18663,13 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache = boundaryFiber.memoizedState; break; default: - invariant( - false, - "Pinged unknown suspense boundary type. " + - "This is probably a bug in React." - ); + (function() { + { + throw ReactError( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } + })(); } } else { retryCache = boundaryFiber.stateNode; @@ -17818,7 +18680,7 @@ function resolveRetryThenable(boundaryFiber, thenable) { retryCache.delete(thenable); } - retryTimedOutBoundary(boundaryFiber); + retryTimedOutBoundary$1(boundaryFiber); } function scheduleWorkToRoot(fiber, expirationTime) { @@ -17907,9 +18769,20 @@ function scheduleWorkToRoot(fiber, expirationTime) { return root; } -function warnIfNotCurrentlyBatchingInDev(fiber) { +// in a test-like environment, we want to warn if dispatchAction() is +// called outside of a TestUtils.act(...)/batchedUpdates/render call. +// so we have a a step counter for when we descend/ascend from +// act() calls, and test on it for when to warn +// It's a tuple with a single value. Look for shared/createAct to +// see how we change the value inside act() calls + +function warnIfNotCurrentlyActingUpdatesInDev$1(fiber) { { - if (isRendering === false && isBatchingUpdates === false) { + if ( + isBatchingUpdates === false && + isRendering === false && + ReactShouldWarnActingUpdates.current === false + ) { warningWithoutStack$1( false, "An update to %s inside a test was not wrapped in act(...).\n\n" + @@ -17928,7 +18801,7 @@ function warnIfNotCurrentlyBatchingInDev(fiber) { } } -function scheduleWork(fiber, expirationTime) { +function scheduleWork$1(fiber, expirationTime) { var root = scheduleWorkToRoot(fiber, expirationTime); if (root === null) { { @@ -17971,13 +18844,28 @@ function scheduleWork(fiber, expirationTime) { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { // Reset this back to zero so subsequent updates don't throw. nestedUpdateCount = 0; - invariant( - false, - "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." - ); + (function() { + { + throw ReactError( + "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." + ); + } + })(); + } + { + if ( + isInPassiveEffectDEV && + nestedPassiveEffectCountDEV > NESTED_PASSIVE_UPDATE_LIMIT + ) { + nestedPassiveEffectCountDEV = 0; + warning$1( + false, + "Maximum update depth exceeded. This can happen when a " + + "component calls setState inside useEffect, but " + + "useEffect either doesn't have a dependency array, or " + + "one of the dependencies changes on every render." + ); + } } } @@ -17999,10 +18887,11 @@ var unhandledError = null; var isBatchingUpdates = false; var isUnbatchingUpdates = false; +var isBatchingInteractiveUpdates = false; var completedBatches = null; -var originalStartTimeMs = now$$1(); +var originalStartTimeMs = now$1(); var currentRendererTime = msToExpirationTime(originalStartTimeMs); var currentSchedulerTime = currentRendererTime; @@ -18011,8 +18900,17 @@ var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var lastCommittedRootDuringThisBatch = null; +// Similar, but for useEffect infinite loops. These are DEV-only. +var NESTED_PASSIVE_UPDATE_LIMIT = 50; +var nestedPassiveEffectCountDEV = void 0; +var isInPassiveEffectDEV = void 0; +{ + nestedPassiveEffectCountDEV = 0; + isInPassiveEffectDEV = false; +} + function recomputeCurrentRendererTime() { - var currentTimeMs = now$$1() - originalStartTimeMs; + var currentTimeMs = now$1() - originalStartTimeMs; currentRendererTime = msToExpirationTime(currentTimeMs); } @@ -18026,7 +18924,7 @@ function scheduleCallbackWithExpirationTime(root, expirationTime) { if (callbackID !== null) { // Existing callback has insufficient timeout. Cancel and schedule a // new one. - cancelDeferredCallback$$1(callbackID); + cancelCallback$1(callbackID); } } // The request callback timer is already running. Don't start a new one. @@ -18035,10 +18933,11 @@ function scheduleCallbackWithExpirationTime(root, expirationTime) { } callbackExpirationTime = expirationTime; - var currentMs = now$$1() - originalStartTimeMs; + var currentMs = now$1() - originalStartTimeMs; var expirationTimeMs = expirationTimeToMs(expirationTime); var timeout = expirationTimeMs - currentMs; - callbackID = scheduleDeferredCallback$$1(performAsyncWork, { + var priorityLevel = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(priorityLevel, performAsyncWork, { timeout: timeout }); } @@ -18064,7 +18963,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - if (msUntilTimeout === 0 && !shouldYield$$1()) { + if (msUntilTimeout === 0 && (disableYielding || !shouldYield$1())) { // Don't wait an additional tick. Commit the tree immediately. root.pendingCommitExpirationTime = suspendedExpirationTime; root.finishedWork = finishedWork; @@ -18090,7 +18989,7 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { // because we're at the top of a timer event. recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - flushRoot(root, suspendedExpirationTime); + flushRoot$1(root, suspendedExpirationTime); } function onCommit(root, expirationTime) { @@ -18098,7 +18997,7 @@ function onCommit(root, expirationTime) { root.finishedWork = null; } -function requestCurrentTime() { +function requestCurrentTime$1() { // requestCurrentTime is called by the scheduler to compute an expiration // time. // @@ -18210,11 +19109,13 @@ function findHighestPriorityRoot() { // TODO: This check is redudant, but Flow is confused by the branch // below where we set lastScheduledRoot to null, even though we break // from the loop right after. - invariant( - previousScheduledRoot !== null && lastScheduledRoot !== null, - "Should have a previous and last root. This error is likely " + - "caused by a bug in React. Please file an issue." - ); + (function() { + if (!(previousScheduledRoot !== null && lastScheduledRoot !== null)) { + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); if (root === root.nextScheduledRoot) { // This is the only root in the list. root.nextScheduledRoot = null; @@ -18278,19 +19179,18 @@ function performAsyncWork(didTimeout) { } while (root !== firstScheduledRoot); } } - performWork(NoWork, true); -} -function performSyncWork() { - performWork(Sync, false); -} - -function performWork(minExpirationTime, isYieldy) { // Keep working on roots until there's no more work, or until there's a higher // priority event. findHighestPriorityRoot(); - if (isYieldy) { + if (disableYielding) { + // Just do it all + while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork) { + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); + findHighestPriorityRoot(); + } + } else { recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; @@ -18303,8 +19203,7 @@ function performWork(minExpirationTime, isYieldy) { while ( nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && - minExpirationTime <= nextFlushedExpirationTime && - !(shouldYield$$1() && currentRendererTime > nextFlushedExpirationTime) + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime) ) { performWorkOnRoot( nextFlushedRoot, @@ -18315,25 +19214,15 @@ function performWork(minExpirationTime, isYieldy) { recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; } - } else { - while ( - nextFlushedRoot !== null && - nextFlushedExpirationTime !== NoWork && - minExpirationTime <= nextFlushedExpirationTime - ) { - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); - findHighestPriorityRoot(); - } } // We're done flushing work. Either we ran out of time in this callback, // or there's no more work left with sufficient priority. // If we're inside a callback, set this to false since we just completed it. - if (isYieldy) { - callbackExpirationTime = NoWork; - callbackID = null; - } + callbackExpirationTime = NoWork; + callbackID = null; + // If there's work left over, schedule a new callback. if (nextFlushedExpirationTime !== NoWork) { scheduleCallbackWithExpirationTime( @@ -18346,12 +19235,47 @@ function performWork(minExpirationTime, isYieldy) { finishRendering(); } -function flushRoot(root, expirationTime) { - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely " + - "means you attempted to commit from inside a lifecycle method." - ); +function performSyncWork() { + performWork(Sync); +} + +function performWork(minExpirationTime) { + // Keep working on roots until there's no more work, or until there's a higher + // priority event. + findHighestPriorityRoot(); + + while ( + nextFlushedRoot !== null && + nextFlushedExpirationTime !== NoWork && + minExpirationTime <= nextFlushedExpirationTime + ) { + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); + findHighestPriorityRoot(); + } + + // We're done flushing work. Either we ran out of time in this callback, + // or there's no more work left with sufficient priority. + + // If there's work left over, schedule a new callback. + if (nextFlushedExpirationTime !== NoWork) { + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + } + + // Clean-up. + finishRendering(); +} + +function flushRoot$1(root, expirationTime) { + (function() { + if (!!isRendering) { + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); + } + })(); // Perform work on root as if the given expiration time is the current time. // This has the effect of synchronously flushing all work up to and // including the given time. @@ -18366,6 +19290,12 @@ function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; + { + if (rootWithPendingPassiveEffects === null) { + nestedPassiveEffectCountDEV = 0; + } + } + if (completedBatches !== null) { var batches = completedBatches; completedBatches = null; @@ -18391,11 +19321,13 @@ function finishRendering() { } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused " + - "by a bug in React. Please file an issue." - ); + (function() { + if (!!isRendering) { + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); isRendering = true; @@ -18448,7 +19380,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { if (_finishedWork !== null) { // We've completed the root. Check the if we should yield one more time // before committing. - if (!shouldYield$$1()) { + if (!shouldYield$1()) { // Still time left. Commit the root. completeRoot(root, _finishedWork, expirationTime); } else { @@ -18495,20 +19427,17 @@ function completeRoot(root, finishedWork, expirationTime) { lastCommittedRootDuringThisBatch = root; nestedUpdateCount = 0; } - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); - } - ); + commitRoot(root, finishedWork); } -function onUncaughtError(error) { - invariant( - nextFlushedRoot !== null, - "Should be working on a root. This error is likely caused by a bug in " + - "React. Please file an issue." - ); +function onUncaughtError$1(error) { + (function() { + if (!(nextFlushedRoot !== null)) { + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); + } + })(); // Unschedule this root so we don't work on it again until there's // another update. nextFlushedRoot.expirationTime = NoWork; @@ -18520,7 +19449,7 @@ function onUncaughtError(error) { // TODO: Batching should be implemented at the renderer level, not inside // the reconciler. -function batchedUpdates$1(fn, a) { +function batchedUpdates$2(fn, a) { var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { @@ -18533,7 +19462,10 @@ function batchedUpdates$1(fn, a) { } } -function interactiveUpdates$1(fn, a, b) { +function interactiveUpdates$2(fn, a, b, c) { + if (isBatchingInteractiveUpdates) { + return fn(a, b, c); + } // If there are any pending interactive updates, synchronously flush them. // This needs to happen before we read any handlers, because the effect of // the previous event may influence which handlers are called during @@ -18544,19 +19476,17 @@ function interactiveUpdates$1(fn, a, b) { lowestPriorityPendingInteractiveExpirationTime !== NoWork ) { // Synchronously flush pending interactive updates. - performWork(lowestPriorityPendingInteractiveExpirationTime, false); + performWork(lowestPriorityPendingInteractiveExpirationTime); lowestPriorityPendingInteractiveExpirationTime = NoWork; } + var previousIsBatchingInteractiveUpdates = isBatchingInteractiveUpdates; var previousIsBatchingUpdates = isBatchingUpdates; + isBatchingInteractiveUpdates = true; isBatchingUpdates = true; try { - return scheduler.unstable_runWithPriority( - scheduler.unstable_UserBlockingPriority, - function() { - return fn(a, b); - } - ); + return fn(a, b, c); } finally { + isBatchingInteractiveUpdates = previousIsBatchingInteractiveUpdates; isBatchingUpdates = previousIsBatchingUpdates; if (!isBatchingUpdates && !isRendering) { performSyncWork(); @@ -18564,17 +19494,1985 @@ function interactiveUpdates$1(fn, a, b) { } } -function flushInteractiveUpdates$1() { +function flushInteractiveUpdates$2() { if ( !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork ) { // Synchronously flush pending interactive updates. - performWork(lowestPriorityPendingInteractiveExpirationTime, false); + performWork(lowestPriorityPendingInteractiveExpirationTime); lowestPriorityPendingInteractiveExpirationTime = NoWork; } } +// TODO: Ahaha Andrew is bad at spellling +// DEV stuff +var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentOwner$4 = ReactSharedInternals.ReactCurrentOwner; +var ReactShouldWarnActingUpdates$1 = + ReactSharedInternals.ReactShouldWarnActingUpdates; + +var NotWorking = 0; +var BatchedPhase = 1; +var LegacyUnbatchedPhase = 2; +var RenderPhase = 4; +var CommitPhase = 5; + +var RootIncomplete = 0; +var RootErrored = 1; +var RootSuspended = 2; +var RootCompleted = 3; + +// The phase of work we're currently in +var workPhase = NotWorking; +// 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$1 = NoWork; +// Whether to root completed, errored, suspended, etc. +var workInProgressRootExitStatus = RootIncomplete; +// 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 workInProgressRootMostRecentEventTime = Sync; + +var nextEffect$1 = null; +var hasUncaughtError = false; +var firstUncaughtError = null; +var legacyErrorBoundariesThatAlreadyFailed$1 = null; + +var rootDoesHavePassiveEffects = false; +var rootWithPendingPassiveEffects$1 = null; +var pendingPassiveEffectsExpirationTime = NoWork; + +var rootsWithPendingDiscreteUpdates = null; + +// Use these to prevent an infinite loop of nested updates +var NESTED_UPDATE_LIMIT$1 = 50; +var nestedUpdateCount$1 = 0; +var rootWithNestedUpdates = null; + +var NESTED_PASSIVE_UPDATE_LIMIT$1 = 50; +var nestedPassiveUpdateCount = 0; + +var interruptedBy$1 = 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 initialTimeMs = now(); +var currentEventTime = NoWork; + +function requestCurrentTime$2() { + if (workPhase === RenderPhase || workPhase === CommitPhase) { + // We're inside React, so it's fine to read the actual time. + return msToExpirationTime(now() - initialTimeMs); + } + // 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. + currentEventTime = msToExpirationTime(now() - initialTimeMs); + return currentEventTime; +} + +function computeExpirationForFiber$2(currentTime, fiber) { + if ((fiber.mode & ConcurrentMode) === NoContext) { + return Sync; + } + + if (workPhase === RenderPhase) { + // Use whatever time we're already rendering + return renderExpirationTime$1; + } + + // Compute an expiration time based on the Scheduler priority. + var expirationTime = void 0; + var priorityLevel = getCurrentPriorityLevel(); + switch (priorityLevel) { + 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; + break; + default: + (function() { + { + throw ReactError("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. + if ( + workInProgressRoot !== null && + expirationTime === renderExpirationTime$1 + ) { + // This is a trick to move this update into a separate batch + expirationTime -= 1; + } + + 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(); + + if (expirationTime === Sync) { + if (workPhase === LegacyUnbatchedPhase) { + // 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$1(root, Sync, true); + while (callback !== null) { + callback = callback(true); + } + } else { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + if (workPhase === NotWorking) { + // Flush the synchronous work now, wnless 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-initated + // updates, to preserve historical behavior of sync mode. + flushImmediateQueue(); + } + } + } else { + // TODO: computeExpirationForFiber also reads the priority. Pass the + // priority as an argument to that function and this one. + var priorityLevel = getCurrentPriorityLevel(); + if (priorityLevel === UserBlockingPriority) { + // This is the result of a discrete event. Track the lowest priority + // discrete update per root so we can flush them early, if needed. + if (rootsWithPendingDiscreteUpdates === null) { + rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]); + } else { + var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root); + if ( + lastDiscreteTime === undefined || + lastDiscreteTime > expirationTime + ) { + rootsWithPendingDiscreteUpdates.set(root, expirationTime); + } + } + } + scheduleCallbackForRoot(root, priorityLevel, expirationTime); + } +} +var scheduleWork$2 = 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. + 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 + ) { + alternate.childExpirationTime = expirationTime; + } + } else if ( + alternate !== null && + alternate.childExpirationTime < 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; + } + } + + 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; + var options = + expirationTime === Sync + ? null + : { timeout: expirationTimeToMs(expirationTime) }; + root.callbackNode = scheduleCallback( + priorityLevel, + runRootCallback.bind( + null, + root, + renderRoot$1.bind(null, root, expirationTime) + ), + options + ); + if ( + enableUserTimingAPI && + expirationTime !== Sync && + workPhase !== RenderPhase && + workPhase !== CommitPhase + ) { + // 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(); + } + } + + 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); + } + + // Add the current set of interactions to the pending set associated with + // this root. + schedulePendingInteraction(root, expirationTime); +} + +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) { + root.callbackNode = null; + root.callbackExpirationTime = NoWork; + } + } +} + +function flushInteractiveUpdates$3() { + if (workPhase === RenderPhase || workPhase === CommitPhase) { + // Can't synchronously flush interactive updates if React is already + // working. This is currently a no-op. + // TODO: Should we fire a warning? This happens if you synchronously invoke + // an input event inside an effect, like with `element.click()`. + return; + } + flushPendingDiscreteUpdates(); +} + +function resolveLocksOnRoot(root, expirationTime) { + var firstBatch = root.firstBatch; + if ( + firstBatch !== null && + firstBatch._defer && + firstBatch._expirationTime >= expirationTime + ) { + root.finishedWork = root.current.alternate; + root.pendingCommitExpirationTime = expirationTime; + scheduleCallback(NormalPriority, function() { + firstBatch._onComplete(); + return null; + }); + return true; + } else { + return false; + } +} + +function interactiveUpdates$3(fn, a, b, c) { + if (workPhase === NotWorking) { + // TODO: Remove this call. Instead of doing this automatically, the caller + // should explicitly call flushInteractiveUpdates. + flushPendingDiscreteUpdates(); + } + return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c)); +} + +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) { + scheduleCallback( + ImmediatePriority, + renderRoot$1.bind(null, root, expirationTime) + ); + }); + // Now flush the immediate queue. + flushImmediateQueue(); + } +} + +function batchedUpdates$3(fn, a) { + if (workPhase !== NotWorking) { + // We're already working, or inside a batch, so batchedUpdates is a no-op. + return fn(a); + } + workPhase = BatchedPhase; + try { + return fn(a); + } finally { + workPhase = NotWorking; + // Flush the immediate callbacks that were scheduled during this batch + flushImmediateQueue(); + } +} + +function prepareFreshStack(root, expirationTime) { + root.pendingCommitExpirationTime = 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$1 = expirationTime; + workInProgressRootExitStatus = RootIncomplete; + workInProgressRootMostRecentEventTime = Sync; + + { + ReactStrictModeWarnings.discardPendingWarnings(); + } +} + +function renderRoot$1(root, expirationTime, isSync) { + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Should not already be working."); + } + })(); + + if (enableUserTimingAPI && expirationTime !== Sync) { + var didExpire = isSync; + var timeoutMs = expirationTimeToMs(expirationTime); + stopRequestCallbackTimer(didExpire, timeoutMs); + } + + 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.pendingCommitExpirationTime === expirationTime) { + // There's already a pending commit at this expiration time. + root.pendingCommitExpirationTime = NoWork; + return commitRoot$1.bind(null, root, expirationTime); + } + + flushPassiveEffects$2(); + + // 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$1 + ) { + prepareFreshStack(root, expirationTime); + startWorkOnPendingInteraction(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 prevWorkPhase = workPhase; + workPhase = RenderPhase; + var prevDispatcher = ReactCurrentDispatcher$2.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$2.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$2(); + if (currentTime < expirationTime) { + // Restart at the current time. + workPhase = prevWorkPhase; + resetContextDependences(); + ReactCurrentDispatcher$2.current = prevDispatcher; + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + return renderRoot$1.bind(null, root, currentTime); + } + } + } 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$1(); + } + break; + } catch (thrownValue) { + // Reset module-level state that was set during the render phase. + resetContextDependences(); + 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); + workPhase = prevWorkPhase; + 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( + root, + returnFiber, + sourceFiber, + thrownValue, + renderExpirationTime$1 + ); + workInProgress = completeUnitOfWork$1(sourceFiber); + } + } while (true); + + workPhase = prevWorkPhase; + resetContextDependences(); + ReactCurrentDispatcher$2.current = prevDispatcher; + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + + if (workInProgress !== null) { + // There's still work left over. Return a continuation. + stopInterruptedWorkLoopTimer(); + if (expirationTime !== Sync) { + startRequestCallbackTimer(); + } + return renderRoot$1.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(); + + 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; + } + + // Set this to null to indicate there's no in-progress render. + workInProgressRoot = null; + + switch (workInProgressRootExitStatus) { + case RootIncomplete: { + (function() { + { + throw ReactError("Should have a work-in-progress."); + } + })(); + } + // Flow knows about invariant, so it compains 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 (root.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$1.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); + scheduleCallback( + ImmediatePriority, + renderRoot$1.bind(null, root, expirationTime) + ); + return null; + } + // If we're already rendering synchronously, commit the root in its + // errored state. + return commitRoot$1.bind(null, root, expirationTime); + } + case RootSuspended: { + if (!isSync) { + var _lastPendingTime = root.lastPendingTime; + if (root.lastPendingTime < expirationTime) { + // There's lower priority work. It might be unsuspended. Try rendering + // at that level. + return renderRoot$1.bind(null, root, _lastPendingTime); + } + // If workInProgressRootMostRecentEventTime is Sync, that means we didn't + // track any event times. That can happen if we retried but nothing switched + // from fallback to content. There's no reason to delay doing no work. + if (workInProgressRootMostRecentEventTime !== Sync) { + var msUntilTimeout = computeMsUntilTimeout( + workInProgressRootMostRecentEventTime + ); + if (msUntilTimeout > 0) { + // 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$1.bind(null, root, expirationTime), + msUntilTimeout + ); + return null; + } + } + } + // The work expired. Commit immediately. + return commitRoot$1.bind(null, root, expirationTime); + } + case RootCompleted: { + // The work completed. Ready to commit. + return commitRoot$1.bind(null, root, expirationTime); + } + default: { + (function() { + { + throw ReactError("Unknown root exit status."); + } + })(); + } + } +} + +function markRenderEventTime$2(expirationTime) { + if (expirationTime < workInProgressRootMostRecentEventTime) { + workInProgressRootMostRecentEventTime = expirationTime; + } +} + +function renderDidSuspend$2() { + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootSuspended; + } +} + +function renderDidError$2() { + if ( + workInProgressRootExitStatus === RootIncomplete || + workInProgressRootExitStatus === RootSuspended + ) { + workInProgressRootExitStatus = RootErrored; + } +} + +function inferTimeFromExpirationTime$1(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 + initialTimeMs; +} + +function workLoopSync() { + // Already timed out, so perform work without checking if we need to yield. + while (workInProgress !== null) { + workInProgress = performUnitOfWork$1(workInProgress); + } +} + +function workLoop$1() { + // Perform work until Scheduler asks us to yield + while (workInProgress !== null && !shouldYield()) { + workInProgress = performUnitOfWork$1(workInProgress); + } +} + +function performUnitOfWork$1(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 = void 0; + if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1); + } + + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { + // If this doesn't spawn new work, complete the current work. + next = completeUnitOfWork$1(unitOfWork); + } + + ReactCurrentOwner$4.current = null; + return next; +} + +function completeUnitOfWork$1(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; + + // 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) === NoContext + ) { + next = completeWork(current$$1, workInProgress, renderExpirationTime$1); + } else { + startProfilerTimer(workInProgress); + next = completeWork(current$$1, workInProgress, renderExpirationTime$1); + // Update render duration assuming we didn't error. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + } + stopWorkTimer(workInProgress); + resetCurrentFiber(); + resetChildExpirationTime$1(workInProgress); + + if (next !== null) { + // Completing this fiber spawned new work. Work on that next. + return next; + } + + if ( + 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 + // list of the parent. The completion order of the children affects the + // side-effect order. + 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 + // 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 + // 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; + } + } + } else { + // 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$1); + + // Because this fiber did not complete, don't reset its expiration time. + + if ( + enableProfilerTimer && + (workInProgress.mode & ProfileMode) !== NoContext + ) { + // Record the render duration for the fiber that errored. + stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); + + // 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; + } + + if (_next !== null) { + // If completing this work spawned new work, do that next. We'll come + // back here again. + // Since we're restarting, remove anything that is not a host effect + // from the effect tag. + // TODO: The name stopFailedWorkTimer is misleading because Suspense + // also captures and restarts. + stopFailedWorkTimer(workInProgress); + _next.effectTag &= HostEffectMask; + return _next; + } + stopWorkTimer(workInProgress); + + if (returnFiber !== null) { + // Mark the parent fiber as incomplete and clear its effect list. + returnFiber.firstEffect = returnFiber.lastEffect = null; + returnFiber.effectTag |= Incomplete; + } + } + + 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 + workInProgress = returnFiber; + } while (workInProgress !== null); + + // We've reached the root. + if (workInProgressRootExitStatus === RootIncomplete) { + workInProgressRootExitStatus = RootCompleted; + } + return null; +} + +function resetChildExpirationTime$1(completedWork) { + if ( + renderExpirationTime$1 !== Never && + completedWork.childExpirationTime === Never + ) { + // The children of this component are hidden. Don't bubble their + // expiration times. + return; + } + + var newChildExpirationTime = NoWork; + + // Bubble up the earliest expiration time. + if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) { + // 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 + // 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; + } + } + + completedWork.childExpirationTime = newChildExpirationTime; +} + +function commitRoot$1(root, expirationTime) { + runWithPriority( + ImmediatePriority, + commitRootImpl.bind(null, root, expirationTime) + ); + // 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$1 !== null) { + var priorityLevel = getCurrentPriorityLevel(); + scheduleCallback(priorityLevel, function() { + flushPassiveEffects$2(); + return null; + }); + } + return null; +} + +function commitRootImpl(root, expirationTime) { + flushPassiveEffects$2(); + flushRenderPhaseStrictModeWarningsInDEV(); + + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Should not already be working."); + } + })(); + var finishedWork = root.current.alternate; + (function() { + if (!(finishedWork !== null)) { + throw ReactError("Should have a work-in-progress root."); + } + })(); + + // 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 + // 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; + } + + if (root === workInProgressRoot) { + // We can reset these now that they are finished. + workInProgressRoot = null; + workInProgress = null; + renderExpirationTime$1 = NoWork; + } else { + } + // 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; + 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 + // resulting list is the set that would belong to the root's parent, if it + // had one; that is, all the effects in the tree including the root. + if (finishedWork.lastEffect !== null) { + finishedWork.lastEffect.nextEffect = finishedWork; + firstEffect = finishedWork.firstEffect; + } else { + firstEffect = finishedWork; + } + } else { + // There is no effect on the root. + firstEffect = finishedWork.firstEffect; + } + + if (firstEffect !== null) { + var prevWorkPhase = workPhase; + workPhase = CommitPhase; + var prevInteractions = null; + if (enableSchedulerTracing) { + prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + } + + // Reset this to null before calling lifecycles + ReactCurrentOwner$4.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$1 = firstEffect; + do { + { + invokeGuardedCallback(null, commitBeforeMutationEffects, null); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var error = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, error); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== 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. + startCommitHostEffectsTimer(); + nextEffect$1 = firstEffect; + do { + { + invokeGuardedCallback(null, commitMutationEffects, null); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var _error = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, _error); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== null); + 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 + // 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$1 = firstEffect; + do { + { + invokeGuardedCallback( + null, + commitLayoutEffects, + null, + root, + expirationTime + ); + if (hasCaughtError()) { + (function() { + if (!(nextEffect$1 !== null)) { + throw ReactError("Should be working on an effect."); + } + })(); + var _error2 = clearCaughtError(); + captureCommitPhaseError$2(nextEffect$1, _error2); + nextEffect$1 = nextEffect$1.nextEffect; + } + } + } while (nextEffect$1 !== null); + stopCommitLifeCyclesTimer(); + + nextEffect$1 = null; + + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + } + workPhase = prevWorkPhase; + } else { + // No effects. + 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(); + stopCommitLifeCyclesTimer(); + } + + stopCommitTimer(); + + if (rootDoesHavePassiveEffects) { + // This commit has passive effects. Stash a reference to them. But don't + // schedule a callback until after flushing layout work. + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects$1 = root; + pendingPassiveEffectsExpirationTime = expirationTime; + } else { + if (enableSchedulerTracing) { + // If there are no passive effects, then we can complete the pending + // interactions. Otherwise, we'll wait until after the passive effects + // are flushed. + finishPendingInteractions(root, expirationTime); + } + } + + // Check if there's remaining work on this root + var remainingExpirationTime = root.firstPendingTime; + if (remainingExpirationTime !== NoWork) { + var currentTime = requestCurrentTime$2(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + remainingExpirationTime + ); + scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime); + } else { + // If there's no remaining work, we can clear the set of already failed + // error boundaries. + legacyErrorBoundariesThatAlreadyFailed$1 = null; + } + + onCommitRoot(finishedWork.stateNode); + + 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. + if (root === rootWithNestedUpdates) { + nestedUpdateCount$1++; + } else { + nestedUpdateCount$1 = 0; + rootWithNestedUpdates = root; + } + } else { + nestedUpdateCount$1 = 0; + } + + if (hasUncaughtError) { + hasUncaughtError = false; + var _error3 = firstUncaughtError; + firstUncaughtError = null; + throw _error3; + } + + if (workPhase === LegacyUnbatchedPhase) { + // This is a legacy edge case. We just committed the initial mount of + // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired + // synchronously, but layout updates should be deferred until the end + // of the batch. + return null; + } + + // If layout work was scheduled, flush it now. + flushImmediateQueue(); + return null; +} + +function commitBeforeMutationEffects() { + while (nextEffect$1 !== null) { + if ((nextEffect$1.effectTag & Snapshot) !== NoEffect) { + setCurrentFiber(nextEffect$1); + recordEffect(); + + var current$$1 = nextEffect$1.alternate; + commitBeforeMutationLifeCycles(current$$1, nextEffect$1); + + resetCurrentFiber(); + } + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function commitMutationEffects() { + // TODO: Should probably move the bulk of this function to commitWork. + while (nextEffect$1 !== null) { + setCurrentFiber(nextEffect$1); + + var effectTag = nextEffect$1.effectTag; + + if (effectTag & ContentReset) { + commitResetTextContent(nextEffect$1); + } + + if (effectTag & Ref) { + var current$$1 = nextEffect$1.alternate; + if (current$$1 !== null) { + commitDetachRef(current$$1); + } + } + + // 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); + switch (primaryEffectTag) { + case Placement: { + commitPlacement(nextEffect$1); + // 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$1.effectTag &= ~Placement; + break; + } + case PlacementAndUpdate: { + // Placement + commitPlacement(nextEffect$1); + // Clear the "placement" from effect tag so that we know that this is + // inserted, before any life-cycles like componentDidMount gets called. + nextEffect$1.effectTag &= ~Placement; + + // Update + var _current = nextEffect$1.alternate; + commitWork(_current, nextEffect$1); + break; + } + case Update: { + var _current2 = nextEffect$1.alternate; + commitWork(_current2, nextEffect$1); + break; + } + case Deletion: { + commitDeletion(nextEffect$1); + break; + } + } + + // TODO: Only record a mutation effect if primaryEffectTag is non-zero. + recordEffect(); + + resetCurrentFiber(); + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function commitLayoutEffects(root, committedExpirationTime) { + // TODO: Should probably move the bulk of this function to commitWork. + while (nextEffect$1 !== null) { + setCurrentFiber(nextEffect$1); + + var effectTag = nextEffect$1.effectTag; + + if (effectTag & (Update | Callback)) { + recordEffect(); + var current$$1 = nextEffect$1.alternate; + commitLifeCycles(root, current$$1, nextEffect$1, committedExpirationTime); + } + + if (effectTag & Ref) { + recordEffect(); + commitAttachRef(nextEffect$1); + } + + if (effectTag & Passive) { + rootDoesHavePassiveEffects = true; + } + + resetCurrentFiber(); + nextEffect$1 = nextEffect$1.nextEffect; + } +} + +function flushPassiveEffects$2() { + if (rootWithPendingPassiveEffects$1 === null) { + return false; + } + var root = rootWithPendingPassiveEffects$1; + var expirationTime = pendingPassiveEffectsExpirationTime; + rootWithPendingPassiveEffects$1 = null; + pendingPassiveEffectsExpirationTime = NoWork; + + var prevInteractions = null; + if (enableSchedulerTracing) { + prevInteractions = tracing.__interactionsRef.current; + tracing.__interactionsRef.current = root.memoizedInteractions; + } + + (function() { + if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) { + throw ReactError("Cannot flush passive effects while already rendering."); + } + })(); + var prevWorkPhase = workPhase; + workPhase = CommitPhase; + + // 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("Should be working on an effect."); + } + })(); + var error = clearCaughtError(); + captureCommitPhaseError$2(effect, error); + } + resetCurrentFiber(); + } + effect = effect.nextEffect; + } + + if (enableSchedulerTracing) { + tracing.__interactionsRef.current = prevInteractions; + finishPendingInteractions(root, expirationTime); + } + + workPhase = prevWorkPhase; + flushImmediateQueue(); + + // If additional passive effects were scheduled, increment a counter. If this + // exceeds the limit, we'll fire a warning. + nestedPassiveUpdateCount = + rootWithPendingPassiveEffects$1 === null ? 0 : nestedPassiveUpdateCount + 1; + + return true; +} + +function isAlreadyFailedLegacyErrorBoundary$2(instance) { + return ( + legacyErrorBoundariesThatAlreadyFailed$1 !== null && + legacyErrorBoundariesThatAlreadyFailed$1.has(instance) + ); +} + +function markLegacyErrorBoundaryAsFailed$2(instance) { + if (legacyErrorBoundariesThatAlreadyFailed$1 === null) { + legacyErrorBoundariesThatAlreadyFailed$1 = new Set([instance]); + } else { + legacyErrorBoundariesThatAlreadyFailed$1.add(instance); + } +} + +function prepareToThrowUncaughtError(error) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error; + } +} +var onUncaughtError$2 = prepareToThrowUncaughtError; + +function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, Sync); + enqueueUpdate(rootFiber, update); + var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync); + if (root !== null) { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + } +} + +function captureCommitPhaseError$2(sourceFiber, error) { + if (sourceFiber.tag === HostRoot) { + // Error was thrown at the root. There is no parent, so the root + // itself should capture it. + captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error); + return; + } + + var fiber = sourceFiber.return; + while (fiber !== null) { + if (fiber.tag === HostRoot) { + captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error); + return; + } else if (fiber.tag === ClassComponent) { + var ctor = fiber.type; + var instance = fiber.stateNode; + if ( + typeof ctor.getDerivedStateFromError === "function" || + (typeof instance.componentDidCatch === "function" && + !isAlreadyFailedLegacyErrorBoundary$2(instance)) + ) { + var errorInfo = createCapturedValue(error, sourceFiber); + var update = createClassErrorUpdate( + fiber, + errorInfo, + // TODO: This is always sync + Sync + ); + enqueueUpdate(fiber, update); + var root = markUpdateTimeFromFiberToRoot(fiber, Sync); + if (root !== null) { + scheduleCallbackForRoot(root, ImmediatePriority, Sync); + } + return; + } + } + fiber = fiber.return; + } +} + +function pingSuspendedRoot$2(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. + pingCache.delete(thenable); + } + + if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) { + // Received a ping at the same priority level at which we're currently + // rendering. Restart from the root. Don't need to schedule a ping because + // we're already working on this tree. + prepareFreshStack(root, renderExpirationTime$1); + return; + } + + var lastPendingTime = root.lastPendingTime; + if (lastPendingTime < suspendedTime) { + // The root is no longer suspended at this time. + return; + } + + var pingTime = root.pingTime; + if (pingTime !== NoWork && pingTime < suspendedTime) { + // There's already a lower priority ping scheduled. + return; + } + + // Mark the time at which this ping was scheduled. + root.pingTime = suspendedTime; + + var currentTime = requestCurrentTime$2(); + var priorityLevel = inferPriorityFromExpirationTime( + currentTime, + suspendedTime + ); + scheduleCallbackForRoot(root, priorityLevel, suspendedTime); +} + +function retryTimedOutBoundary$2(boundaryFiber) { + // The boundary fiber (a Suspense component) previously timed out and 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$2(); + var retryTime = computeExpirationForFiber$2(currentTime, boundaryFiber); + // TODO: Special case idle priority? + var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime); + var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime); + if (root !== null) { + scheduleCallbackForRoot(root, priorityLevel, retryTime); + } +} + +function resolveRetryThenable$2(boundaryFiber, thenable) { + var retryCache = void 0; + if (enableSuspenseServerRenderer) { + switch (boundaryFiber.tag) { + case SuspenseComponent: + retryCache = boundaryFiber.stateNode; + break; + case DehydratedSuspenseComponent: + retryCache = boundaryFiber.memoizedState; + break; + default: + (function() { + { + throw ReactError( + "Pinged unknown suspense boundary type. This is probably a bug in React." + ); + } + })(); + } + } else { + retryCache = boundaryFiber.stateNode; + } + + if (retryCache !== null) { + // The thenable resolved, so we no longer need to memoize, because it will + // never be thrown again. + retryCache.delete(thenable); + } + + retryTimedOutBoundary$2(boundaryFiber); +} + +function computeMsUntilTimeout(mostRecentEventTime) { + if (disableYielding) { + // Timeout immediately when yielding is disabled. + return 0; + } + + var eventTimeMs = inferTimeFromExpirationTime$1(mostRecentEventTime); + var currentTimeMs = now(); + var timeElapsed = currentTimeMs - eventTimeMs; + + // TODO: Account for the Just Noticeable Difference + var timeoutMs = 150; + var msUntilTimeout = timeoutMs - timeElapsed; + // This is the value that is passed to `setTimeout`. + return msUntilTimeout < 0 ? 0 : msUntilTimeout; +} + +function checkForNestedUpdates() { + if (nestedUpdateCount$1 > NESTED_UPDATE_LIMIT$1) { + nestedUpdateCount$1 = 0; + rootWithNestedUpdates = null; + (function() { + { + throw ReactError( + "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." + ); + } + })(); + } + + { + if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT$1) { + nestedPassiveUpdateCount = 0; + warning$1( + false, + "Maximum update depth exceeded. This can happen when a component " + + "calls setState inside useEffect, but useEffect either doesn't " + + "have a dependency array, or one of the dependencies changes on " + + "every render." + ); + } + } +} + +function flushRenderPhaseStrictModeWarningsInDEV() { + { + ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); + ReactStrictModeWarnings.flushLegacyContextWarning(); + + if (warnAboutDeprecatedLifecycles) { + ReactStrictModeWarnings.flushPendingDeprecationWarnings(); + } + } +} + +function stopFinishedWorkLoopTimer() { + var didCompleteRoot = true; + stopWorkLoopTimer(interruptedBy$1, didCompleteRoot); + interruptedBy$1 = null; +} + +function stopInterruptedWorkLoopTimer() { + // TODO: Track which fiber caused the interruption. + var didCompleteRoot = false; + stopWorkLoopTimer(interruptedBy$1, didCompleteRoot); + interruptedBy$1 = null; +} + +function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) { + if ( + enableUserTimingAPI && + workInProgressRoot !== null && + updateExpirationTime > renderExpirationTime$1 + ) { + interruptedBy$1 = fiberThatReceivedUpdate; + } +} + +var didWarnStateUpdateForUnmountedComponent$1 = null; +function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { + { + var tag = fiber.tag; + if ( + tag !== HostRoot && + tag !== ClassComponent && + tag !== FunctionComponent && + tag !== ForwardRef && + tag !== MemoComponent && + tag !== SimpleMemoComponent + ) { + // 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 + // the problematic code almost always lies inside that component. + var componentName = getComponentName(fiber.type) || "ReactComponent"; + if (didWarnStateUpdateForUnmountedComponent$1 !== null) { + if (didWarnStateUpdateForUnmountedComponent$1.has(componentName)) { + return; + } + didWarnStateUpdateForUnmountedComponent$1.add(componentName); + } else { + didWarnStateUpdateForUnmountedComponent$1 = new Set([componentName]); + } + warningWithoutStack$1( + false, + "Can't perform a React state update on an unmounted component. This " + + "is a no-op, but it indicates a memory leak in your application. To " + + "fix, cancel all subscriptions and asynchronous tasks in %s.%s", + tag === ClassComponent + ? "the componentWillUnmount method" + : "a useEffect cleanup function", + getStackByFiberInDevAndProd(fiber) + ); + } +} + +var beginWork$1 = void 0; +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(current$$1, unitOfWork, expirationTime); + } catch (originalError) { + if ( + originalError !== null && + typeof originalError === "object" && + typeof originalError.then === "function" + ) { + // Don't replay promises. Treat everything else like an error. + throw originalError; + } + + // Keep this code in sync with renderRoot; any changes here must have + // corresponding changes there. + resetContextDependences(); + resetHooks(); + + // Unwind the failed stack frame + 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. + invokeGuardedCallback( + null, + beginWork, + null, + current$$1, + unitOfWork, + expirationTime + ); + + if (hasCaughtError()) { + 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. + throw originalError; + } + } + }; +} else { + beginWork$1 = beginWork; +} + +var didWarnAboutUpdateInRender = false; +var didWarnAboutUpdateInGetChildContext = false; +function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) { + { + if (fiber.tag === ClassComponent) { + switch (phase) { + case "getChildContext": + 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 " + + "within `render`). Render methods should be a pure function of " + + "props and state." + ); + didWarnAboutUpdateInRender = true; + break; + } + } + } +} + +function warnIfNotCurrentlyActingUpdatesInDEV(fiber) { + { + if ( + workPhase === NotWorking && + ReactShouldWarnActingUpdates$1.current === false + ) { + warningWithoutStack$1( + false, + "An update to %s inside a test was not wrapped in act(...).\n\n" + + "When testing, code that causes React state updates should be " + + "wrapped into act(...):\n\n" + + "act(() => {\n" + + " /* fire events that update state */\n" + + "});\n" + + "/* assert on the output */\n\n" + + "This ensures that you're testing the behavior the user would see " + + "in the browser." + + " Learn more at https://fb.me/react-wrap-tests-with-act" + + "%s", + getComponentName(fiber.type), + getStackByFiberInDevAndProd(fiber) + ); + } + } +} + +var warnIfNotCurrentlyActingUpdatesInDev$2 = warnIfNotCurrentlyActingUpdatesInDEV; + +function computeThreadID$1(root, expirationTime) { + // Interaction threads are unique per root and expiration time. + return expirationTime * 1000 + root.interactionThreadID; +} + +function schedulePendingInteraction(root, expirationTime) { + // This is called when work is scheduled on a root. It sets up a pending + // interaction, which is completed once the work commits. + if (!enableSchedulerTracing) { + return; + } + + var interactions = tracing.__interactionsRef.current; + if (interactions.size > 0) { + var pendingInteractionMap = root.pendingInteractionMap; + var pendingInteractions = pendingInteractionMap.get(expirationTime); + if (pendingInteractions != null) { + interactions.forEach(function(interaction) { + if (!pendingInteractions.has(interaction)) { + // Update the pending async work count for previously unscheduled interaction. + interaction.__count++; + } + + pendingInteractions.add(interaction); + }); + } else { + pendingInteractionMap.set(expirationTime, new Set(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$1(root, expirationTime); + subscriber.onWorkScheduled(interactions, threadID); + } + } +} + +function startWorkOnPendingInteraction(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 + // 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, + scheduledExpirationTime + ) { + if (scheduledExpirationTime >= expirationTime) { + scheduledInteractions.forEach(function(interaction) { + 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 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$1(root, expirationTime); + try { + subscriber.onWorkStarted(interactions, threadID); + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } + } + } +} + +function finishPendingInteractions(root, committedExpirationTime) { + if (!enableSchedulerTracing) { + return; + } + + var earliestRemainingTimeAfterCommit = root.firstPendingTime; + + var subscriber = void 0; + + try { + subscriber = tracing.__subscriberRef.current; + if (subscriber !== null && root.memoizedInteractions.size > 0) { + var threadID = computeThreadID$1(root, committedExpirationTime); + subscriber.onWorkStopped(root.memoizedInteractions, threadID); + } + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } finally { + // Clear completed interactions from the pending Map. + // Unless the render was suspended or cascading work was scheduled, + // In which case– leave pending interactions until the subsequent render. + var pendingInteractionMap = root.pendingInteractionMap; + pendingInteractionMap.forEach(function( + scheduledInteractions, + scheduledExpirationTime + ) { + // Only decrement the pending interaction count if we're done. + // If there's still work at the current priority, + // That indicates that we are waiting for suspense data. + if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { + pendingInteractionMap.delete(scheduledExpirationTime); + + scheduledInteractions.forEach(function(interaction) { + interaction.__count--; + + if (subscriber !== null && interaction.__count === 0) { + try { + subscriber.onInteractionScheduledWorkCompleted(interaction); + } catch (error) { + // If the subscriber throws, rethrow it in a separate task + scheduleCallback(ImmediatePriority, function() { + throw error; + }); + } + } + }); + } + }); + } +} + +var requestCurrentTime$$1 = enableNewScheduler + ? requestCurrentTime$2 + : requestCurrentTime$1; +var computeExpirationForFiber$$1 = enableNewScheduler + ? computeExpirationForFiber$2 + : computeExpirationForFiber$1; +var captureCommitPhaseError$$1 = enableNewScheduler + ? captureCommitPhaseError$2 + : captureCommitPhaseError$1; +var onUncaughtError$$1 = enableNewScheduler + ? onUncaughtError$2 + : onUncaughtError$1; +var markRenderEventTime$$1 = enableNewScheduler + ? markRenderEventTime$2 + : markRenderEventTime$1; +var renderDidSuspend$$1 = enableNewScheduler + ? renderDidSuspend$2 + : renderDidSuspend$1; +var renderDidError$$1 = enableNewScheduler + ? renderDidError$2 + : renderDidError$1; +var pingSuspendedRoot$$1 = enableNewScheduler + ? pingSuspendedRoot$2 + : pingSuspendedRoot$1; +var retryTimedOutBoundary$$1 = enableNewScheduler + ? retryTimedOutBoundary$2 + : retryTimedOutBoundary$1; +var resolveRetryThenable$$1 = enableNewScheduler + ? resolveRetryThenable$2 + : resolveRetryThenable$1; +var markLegacyErrorBoundaryAsFailed$$1 = enableNewScheduler + ? markLegacyErrorBoundaryAsFailed$2 + : markLegacyErrorBoundaryAsFailed$1; +var isAlreadyFailedLegacyErrorBoundary$$1 = enableNewScheduler + ? isAlreadyFailedLegacyErrorBoundary$2 + : isAlreadyFailedLegacyErrorBoundary$1; +var scheduleWork$$1 = enableNewScheduler ? scheduleWork$2 : scheduleWork$1; + +var batchedUpdates$1 = enableNewScheduler ? batchedUpdates$3 : batchedUpdates$2; + +var interactiveUpdates$1 = enableNewScheduler + ? interactiveUpdates$3 + : interactiveUpdates$2; +var flushInteractiveUpdates$1 = enableNewScheduler + ? flushInteractiveUpdates$3 + : flushInteractiveUpdates$2; + +var flushPassiveEffects$$1 = enableNewScheduler + ? flushPassiveEffects$2 + : flushPassiveEffects$1; +var warnIfNotCurrentlyActingUpdatesInDev$$1 = enableNewScheduler + ? warnIfNotCurrentlyActingUpdatesInDev$2 + : warnIfNotCurrentlyActingUpdatesInDev$1; + // 0 is PROD, 1 is DEV. // Might add PROFILE later. @@ -18637,9 +21535,9 @@ function scheduleRootUpdate(current$$1, element, expirationTime, callback) { update.callback = callback; } - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(current$$1, update); - scheduleWork(current$$1, expirationTime); + scheduleWork$$1(current$$1, expirationTime); return expirationTime; } @@ -18680,13 +21578,20 @@ function findHostInstance(component) { var fiber = get$1(component); if (fiber === undefined) { if (typeof component.render === "function") { - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } else { - invariant( - false, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - ); + (function() { + { + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } + })(); } } var hostFiber = findCurrentHostFiber(fiber); @@ -18701,13 +21606,20 @@ function findHostInstanceWithWarning(component, methodName) { var fiber = get$1(component); if (fiber === undefined) { if (typeof component.render === "function") { - invariant(false, "Unable to find node on an unmounted component."); + (function() { + { + throw ReactError("Unable to find node on an unmounted component."); + } + })(); } else { - invariant( - false, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - ); + (function() { + { + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } + })(); } } var hostFiber = findCurrentHostFiber(fiber); @@ -18760,8 +21672,8 @@ function createContainer(containerInfo, isConcurrent, hydrate) { function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; - var currentTime = requestCurrentTime(); - var expirationTime = computeExpirationForFiber(currentTime, current$$1); + var currentTime = requestCurrentTime$$1(); + var expirationTime = computeExpirationForFiber$$1(currentTime, current$$1); return updateContainerAtExpirationTime( element, container, @@ -18784,7 +21696,18 @@ function getPublicRootInstance(container) { } } +var shouldSuspendImpl = function(fiber) { + return false; +}; + +function shouldSuspend(fiber) { + return shouldSuspendImpl(fiber); +} + +var overrideHookState = null; var overrideProps = null; +var scheduleUpdate = null; +var setSuspenseHandler = null; { var copyWithSetImpl = function(obj, path, idx, value) { @@ -18802,14 +21725,50 @@ var overrideProps = null; return copyWithSetImpl(obj, path, 0, value); }; + // 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) { + flushPassiveEffects$$1(); + + var newState = copyWithSet(currentHook.memoizedState, path, value); + currentHook.memoizedState = newState; + 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); + + scheduleWork$$1(fiber, Sync); + } + }; + // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function(fiber, path, value) { - flushPassiveEffects(); + flushPassiveEffects$$1(); fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } - scheduleWork(fiber, Sync); + scheduleWork$$1(fiber, Sync); + }; + + scheduleUpdate = function(fiber) { + flushPassiveEffects$$1(); + scheduleWork$$1(fiber, Sync); + }; + + setSuspenseHandler = function(newShouldSuspendImpl) { + shouldSuspendImpl = newShouldSuspendImpl; }; } @@ -18819,7 +21778,10 @@ function injectIntoDevTools(devToolsConfig) { return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: overrideHookState, overrideProps: overrideProps, + setSuspenseHandler: setSuspenseHandler, + scheduleUpdate: scheduleUpdate, currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { var hostFiber = findCurrentHostFiber(fiber); @@ -18863,7 +21825,7 @@ function createPortal( // TODO: this is special because it gets imported during build. -var ReactVersion = "16.8.3"; +var ReactVersion = "16.8.6"; // Modules provided by RN: var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { @@ -18901,10 +21863,33 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * prop](docs/view.html#onlayout) instead. */ measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }, /** @@ -18923,10 +21908,33 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * has been completed in native. */ measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }, /** @@ -18942,12 +21950,56 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { onSuccess, onFail /* currently unused */ ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + 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; + } + + UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } }, /** @@ -18957,17 +22009,6 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { * Manipulation](docs/direct-manipulation.html)). */ setNativeProps: function(nativeProps) { - { - if (warnAboutDeprecatedSetNativeProps) { - warningWithoutStack$1( - false, - "Warning: Calling ref.setNativeProps(nativeProps) " + - "is deprecated and will be removed in a future release. " + - "Use the setNativeProps export from the react-native package instead." + - "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" - ); - } - } // 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. @@ -18989,6 +22030,26 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { return; } + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + { + if (warnAboutDeprecatedSetNativeProps) { + warningWithoutStack$1( + false, + "Warning: Calling ref.setNativeProps(nativeProps) " + + "is deprecated and will be removed in a future release. " + + "Use the setNativeProps export from the react-native package instead." + + "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" + ); + } + } + var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; var viewConfig = @@ -19033,13 +22094,18 @@ var NativeMethodsMixin = function(findNodeHandle, findHostInstance) { // true without actually implementing them (setting them to undefined // isn't allowed by ReactClass) var NativeMethodsMixin_DEV = NativeMethodsMixin; - invariant( - !NativeMethodsMixin_DEV.componentWillMount && - !NativeMethodsMixin_DEV.componentWillReceiveProps && - !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && - !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps, - "Do not override existing functions." - ); + (function() { + if ( + !( + !NativeMethodsMixin_DEV.componentWillMount && + !NativeMethodsMixin_DEV.componentWillReceiveProps && + !NativeMethodsMixin_DEV.UNSAFE_componentWillMount && + !NativeMethodsMixin_DEV.UNSAFE_componentWillReceiveProps + ) + ) { + throw ReactError("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() { @@ -19166,11 +22232,34 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * [`onLayout` prop](docs/view.html#onlayout) instead. */ - ReactNativeComponent.prototype.measure = function measure(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + ReactNativeComponent.prototype.measure = function measure$$1(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) { + FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }; /** @@ -19187,13 +22276,36 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { * These values are not available until after natives rendering completes. */ - ReactNativeComponent.prototype.measureInWindow = function measureInWindow( + ReactNativeComponent.prototype.measureInWindow = function measureInWindow$$1( callback ) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, 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) { + FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } else { + UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + } }; /** @@ -19208,12 +22320,56 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { onSuccess, onFail /* currently unused */ ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + 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; + } + + UIManager.measureLayout( + findNodeHandle(this), + relativeNode, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + ); + } }; /** @@ -19226,18 +22382,6 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { ReactNativeComponent.prototype.setNativeProps = function setNativeProps( nativeProps ) { - { - if (warnAboutDeprecatedSetNativeProps) { - warningWithoutStack$1( - false, - "Warning: Calling ref.setNativeProps(nativeProps) " + - "is deprecated and will be removed in a future release. " + - "Use the setNativeProps export from the react-native package instead." + - "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" - ); - } - } - // 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. @@ -19259,6 +22403,26 @@ var ReactNativeComponent = function(findNodeHandle, findHostInstance) { return; } + if (maybeInstance.canonical) { + warningWithoutStack$1( + false, + "Warning: setNativeProps is not currently supported in Fabric" + ); + return; + } + + { + if (warnAboutDeprecatedSetNativeProps) { + warningWithoutStack$1( + false, + "Warning: Calling ref.setNativeProps(nativeProps) " + + "is deprecated and will be removed in a future release. " + + "Use the setNativeProps export from the react-native package instead." + + "\n\timport {setNativeProps} from 'react-native';\n\tsetNativeProps(ref, nativeProps);\n" + ); + } + } + var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; var viewConfig = diff --git a/Libraries/Renderer/oss/ReactNativeRenderer-prod.js b/Libraries/Renderer/oss/ReactNativeRenderer-prod.js index ef16155a086..a8645a716e1 100644 --- a/Libraries/Renderer/oss/ReactNativeRenderer-prod.js +++ b/Libraries/Renderer/oss/ReactNativeRenderer-prod.js @@ -18,30 +18,94 @@ var ReactNativeViewConfigRegistry = require("ReactNativeViewConfigRegistry"), React = require("react"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), - TextInputState = require("TextInputState"); -var scheduler = require("scheduler"), - ExceptionsManager = require("ExceptionsManager"); -function invariant(condition, format, a, b, c, d, e, f) { - if (!condition) { - condition = void 0; - if (void 0 === format) - condition = Error( - "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." - ); - else { - var args = [a, b, c, d, e, f], - argIndex = 0; - condition = Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - condition.name = "Invariant Violation"; - } - condition.framesToPop = 1; - throw condition; - } + TextInputState = require("TextInputState"), + Scheduler = require("scheduler"); +var ExceptionsManager = require("ExceptionsManager"), + FabricUIManager = require("FabricUIManager"); +function ReactError(message) { + message = Error(message); + message.name = "Invariant Violation"; + return message; } +var eventPluginOrder = null, + namesToPlugins = {}; +function recomputePluginOrdering() { + if (eventPluginOrder) + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], + pluginIndex = eventPluginOrder.indexOf(pluginName); + if (!(-1 < pluginIndex)) + throw ReactError( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + if (!plugins[pluginIndex]) { + if (!pluginModule.extractEvents) + throw ReactError( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + plugins[pluginIndex] = pluginModule; + pluginIndex = pluginModule.eventTypes; + for (var eventName in pluginIndex) { + var JSCompiler_inline_result = void 0; + var dispatchConfig = pluginIndex[eventName], + pluginModule$jscomp$0 = pluginModule, + eventName$jscomp$0 = eventName; + if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." + ); + eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (JSCompiler_inline_result in phasedRegistrationNames) + phasedRegistrationNames.hasOwnProperty( + JSCompiler_inline_result + ) && + publishRegistrationName( + phasedRegistrationNames[JSCompiler_inline_result], + pluginModule$jscomp$0, + eventName$jscomp$0 + ); + JSCompiler_inline_result = !0; + } else + dispatchConfig.registrationName + ? (publishRegistrationName( + dispatchConfig.registrationName, + pluginModule$jscomp$0, + eventName$jscomp$0 + ), + (JSCompiler_inline_result = !0)) + : (JSCompiler_inline_result = !1); + if (!JSCompiler_inline_result) + throw ReactError( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + } + } +} +function publishRegistrationName(registrationName, pluginModule) { + if (registrationNameModules[registrationName]) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + registrationNameModules[registrationName] = pluginModule; +} +var plugins = [], + eventNameDispatchConfigs = {}, + registrationNameModules = {}; function invokeGuardedCallbackImpl(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { @@ -83,88 +147,13 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - invariant( - !1, + throw ReactError( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ), - (error = void 0); + ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } } -var eventPluginOrder = null, - namesToPlugins = {}; -function recomputePluginOrdering() { - if (eventPluginOrder) - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName], - pluginIndex = eventPluginOrder.indexOf(pluginName); - invariant( - -1 < pluginIndex, - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", - pluginName - ); - if (!plugins[pluginIndex]) { - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - pluginIndex = pluginModule.eventTypes; - for (var eventName in pluginIndex) { - var JSCompiler_inline_result = void 0; - var dispatchConfig = pluginIndex[eventName], - pluginModule$jscomp$0 = pluginModule, - eventName$jscomp$0 = eventName; - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0), - "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", - eventName$jscomp$0 - ); - eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (JSCompiler_inline_result in phasedRegistrationNames) - phasedRegistrationNames.hasOwnProperty( - JSCompiler_inline_result - ) && - publishRegistrationName( - phasedRegistrationNames[JSCompiler_inline_result], - pluginModule$jscomp$0, - eventName$jscomp$0 - ); - JSCompiler_inline_result = !0; - } else - dispatchConfig.registrationName - ? (publishRegistrationName( - dispatchConfig.registrationName, - pluginModule$jscomp$0, - eventName$jscomp$0 - ), - (JSCompiler_inline_result = !0)) - : (JSCompiler_inline_result = !1); - invariant( - JSCompiler_inline_result, - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } - } -} -function publishRegistrationName(registrationName, pluginModule) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; -} -var plugins = [], - eventNameDispatchConfigs = {}, - registrationNameModules = {}, - getFiberCurrentPropsFromNode = null, +var getFiberCurrentPropsFromNode = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { @@ -176,10 +165,8 @@ function executeDispatch(event, listener, inst) { function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + if (Array.isArray(dispatchListener)) + throw ReactError("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -190,10 +177,10 @@ function executeDirectDispatch(event) { return dispatchListener; } function accumulateInto(current, next) { - invariant( - null != next, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); if (null == current) return next; if (Array.isArray(current)) { if (Array.isArray(next)) return current.push.apply(current, next), current; @@ -227,10 +214,10 @@ function executeDispatchesAndReleaseTopLevel(e) { } var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ); + if (eventPluginOrder) + throw ReactError( + "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,15 +227,19 @@ var injection = { for (pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { var pluginModule = injectedNamesToPlugins[pluginName]; - (namesToPlugins.hasOwnProperty(pluginName) && - namesToPlugins[pluginName] === pluginModule) || - (invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", - pluginName - ), - (namesToPlugins[pluginName] = pluginModule), - (isOrderingDirty = !0)); + if ( + !namesToPlugins.hasOwnProperty(pluginName) || + namesToPlugins[pluginName] !== pluginModule + ) { + if (namesToPlugins[pluginName]) + throw ReactError( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = !0; + } } isOrderingDirty && recomputePluginOrdering(); } @@ -284,12 +275,14 @@ function getListener(inst, registrationName) { inst = !1; } if (inst) return null; - invariant( - !listener || "function" === typeof listener, - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + if (listener && "function" !== typeof listener) + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); return listener; } function getParent(inst) { @@ -450,10 +443,10 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { return new this(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { - invariant( - event instanceof this, - "Trying to release an event instance into a pool of a different type." - ); + if (!(event instanceof this)) + throw ReactError( + "Trying to release an event instance into a pool of a different type." + ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); } @@ -488,7 +481,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - invariant(null != _ref, "Touch object is missing identifier."); + if (null == _ref) throw ReactError("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -601,10 +594,10 @@ var ResponderTouchHistoryStore = { touchHistory: touchHistory }; function accumulate(current, next) { - invariant( - null != next, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); return null == current ? next : Array.isArray(current) @@ -969,11 +962,10 @@ var eventTypes$1 = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType], directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + if (!bubbleDispatchConfig && !directDispatchConfig) + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -1004,14 +996,10 @@ function getInstanceFromTag(tag) { var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { - if ((target = getInstanceFromNode(target))) { - invariant( - !1, + if (getInstanceFromNode(target)) + throw ReactError( "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(target.stateNode); - null(target.stateNode, target.type, props); - } } function _batchedUpdatesImpl(fn, bookkeeping) { return fn(bookkeeping); @@ -1059,19 +1047,18 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { null !== events && (eventQueue = accumulateInto(eventQueue, events)); events = eventQueue; eventQueue = null; - if ( - events && - (forEachAccumulated(events, executeDispatchesAndReleaseTopLevel), - invariant( - !eventQueue, - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ), - hasRethrowError) - ) - throw ((events = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - events); + if (events) { + forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); + if (eventQueue) + throw ReactError( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + if (hasRethrowError) + throw ((events = rethrowError), + (hasRethrowError = !1), + (rethrowError = null), + events); + } }); } RCTEventEmitter.register({ @@ -1118,7 +1105,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - invariant(tag, "All native instances should have a tag."); + if (!tag) throw ReactError("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1147,6 +1134,15 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113, REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116, + REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 60117, + REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 60118, + REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 60119, MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1191,6 +1187,15 @@ function getComponentName(type) { case REACT_LAZY_TYPE: if ((type = 1 === type._status ? type._result : null)) return getComponentName(type); + break; + case REACT_EVENT_COMPONENT_TYPE: + type = type.displayName; + if (void 0 !== type) return type; + break; + case REACT_EVENT_TARGET_TYPE: + if (type.type === REACT_EVENT_TARGET_TOUCH_HIT) return "TouchHitTarget"; + type = type.displayName; + if (void 0 !== type) return type; } return null; } @@ -1205,80 +1210,83 @@ function isFiberMountedImpl(fiber) { return 3 === node.tag ? 2 : 3; } function assertIsMounted(fiber) { - invariant( - 2 === isFiberMountedImpl(fiber), - "Unable to find node on an unmounted component." - ); + if (2 !== isFiberMountedImpl(fiber)) + throw ReactError("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; - if (!alternate) - return ( - (alternate = isFiberMountedImpl(fiber)), - invariant( - 3 !== alternate, - "Unable to find node on an unmounted component." - ), - 1 === alternate ? null : fiber - ); + if (!alternate) { + alternate = isFiberMountedImpl(fiber); + if (3 === alternate) + throw ReactError("Unable to find node on an unmounted component."); + return 1 === alternate ? null : fiber; + } for (var a = fiber, b = alternate; ; ) { - var parentA = a.return, - parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) break; - if (parentA.child === parentB.child) { - for (var child = parentA.child; child; ) { - if (child === a) return assertIsMounted(parentA), fiber; - if (child === b) return assertIsMounted(parentA), alternate; - child = child.sibling; + var parentA = a.return; + if (null === parentA) break; + var parentB = parentA.alternate; + if (null === parentB) { + b = parentA.return; + if (null !== b) { + a = b; + continue; } - invariant(!1, "Unable to find node on an unmounted component."); + break; + } + if (parentA.child === parentB.child) { + for (parentB = parentA.child; parentB; ) { + if (parentB === a) return assertIsMounted(parentA), fiber; + if (parentB === b) return assertIsMounted(parentA), alternate; + parentB = parentB.sibling; + } + throw ReactError("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { - child = !1; - for (var _child = parentA.child; _child; ) { + for (var didFindChild = !1, _child = parentA.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentA; b = parentB; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentA; a = parentB; break; } _child = _child.sibling; } - if (!child) { + if (!didFindChild) { for (_child = parentB.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentB; b = parentA; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentB; a = parentA; break; } _child = _child.sibling; } - invariant( - child, - "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 ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ); + if (a.alternate !== b) + throw ReactError( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - invariant(3 === a.tag, "Unable to find node on an unmounted component."); + if (3 !== a.tag) + throw ReactError("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1527,86 +1535,72 @@ 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() { - TextInputState.blurTextInput(this._nativeTag); - }; - ReactNativeFiberHostComponent.prototype.focus = function() { - TextInputState.focusTextInput(this._nativeTag); - }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { - UIManager.measure( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function( - callback - ) { - UIManager.measureInWindow( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + 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() { + TextInputState.blurTextInput(this._nativeTag); + }; + ReactNativeFiberHostComponent.prototype.focus = function() { + TextInputState.focusTextInput(this._nativeTag); + }; + ReactNativeFiberHostComponent.prototype.measure = function(callback) { + UIManager.measure( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; + ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + 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); + null != relativeNode && UIManager.measureLayout( this._nativeTag, - relativeToNativeNode, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); - }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { - nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - this.viewConfig.validAttributes + }; + ReactNativeFiberHostComponent.prototype.setNativeProps = function( + nativeProps + ) { + nativeProps = diffProperties( + null, + emptyObject, + nativeProps, + this.viewConfig.validAttributes + ); + null != nativeProps && + UIManager.updateView( + this._nativeTag, + this.viewConfig.uiViewClassName, + nativeProps ); - null != nativeProps && - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - nativeProps - ); - }; - return ReactNativeFiberHostComponent; - })(), - now$1 = - "object" === typeof performance && "function" === typeof performance.now - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }, - scheduledCallback = null, - frameDeadline = 0; -function setTimeoutCallback() { - frameDeadline = now$1() + 5; - var callback = scheduledCallback; - scheduledCallback = null; - null !== callback && callback(); -} -function scheduleDeferredCallback$1(callback) { - scheduledCallback = callback; - return setTimeout(setTimeoutCallback, 1); -} + }; + return ReactNativeFiberHostComponent; +})(); function shim$1() { - invariant( - !1, + throw ReactError( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } @@ -1637,24 +1631,8 @@ function finalizeInitialChildren(parentInstance) { return !1; } var scheduleTimeout = setTimeout, - cancelTimeout = clearTimeout; -function commitUpdate(instance, updatePayloadTODO, type, oldProps, newProps) { - updatePayloadTODO = instance.viewConfig; - instanceProps[instance._nativeTag] = newProps; - oldProps = diffProperties( - null, - oldProps, - newProps, - updatePayloadTODO.validAttributes - ); - null != oldProps && - UIManager.updateView( - instance._nativeTag, - updatePayloadTODO.uiViewClassName, - oldProps - ); -} -var BEFORE_SLASH_RE = /^(.*)[\\\/]/; + cancelTimeout = clearTimeout, + BEFORE_SLASH_RE = /^(.*)[\\\/]/; function getStackByFiberInDevAndProd(workInProgress) { var info = ""; do { @@ -1738,10 +1716,10 @@ function popTopLevelContextObject(fiber) { pop(contextStackCursor, fiber); } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); + if (contextStackCursor.current !== emptyContextObject) + throw ReactError( + "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); } @@ -1751,12 +1729,13 @@ function processChildContext(fiber, type, parentContext) { if ("function" !== typeof instance.getChildContext) return parentContext; instance = instance.getChildContext(); for (var contextKey in instance) - invariant( - contextKey in fiber, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + if (!(contextKey in fiber)) + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); return Object.assign({}, parentContext, instance); } function pushContextProvider(workInProgress) { @@ -1775,10 +1754,10 @@ function pushContextProvider(workInProgress) { } function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "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 ReactError( + "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)), (instance.__reactInternalMemoizedMergedChildContext = type), @@ -1812,6 +1791,7 @@ function injectInternals(internals) { } catch (err) {} return !0; } +var Scheduler_now = Scheduler.unstable_now; function FiberNode(tag, pendingProps, key, mode) { this.tag = tag; this.key = key; @@ -1935,11 +1915,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - invariant( - !1, - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", - null == type ? type : typeof type, - "" + throw ReactError( + "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); @@ -1981,6 +1960,21 @@ function createFiberFromPortal(portal, mode, expirationTime) { }; return mode; } +function FiberRootNode(containerInfo, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pingCache = this.pendingChildren = null; + this.pendingCommitExpirationTime = 0; + this.finishedWork = null; + this.timeoutHandle = -1; + this.pendingContext = this.context = null; + this.hydrate = hydrate; + this.firstBatch = null; + this.latestPingedTime = this.latestSuspendedTime = this.earliestSuspendedTime = this.latestPendingTime = this.earliestPendingTime = 0; + this.didError = !1; + this.expirationTime = this.nextExpirationTimeToWorkOn = 0; + this.nextScheduledRoot = null; +} function markPendingPriorityLevel(root, expirationTime) { root.didError = !1; var earliestPendingTime = root.earliestPendingTime; @@ -1992,36 +1986,6 @@ function markPendingPriorityLevel(root, expirationTime) { (root.latestPendingTime = expirationTime); findNextExpirationTimeToWorkOn(expirationTime, root); } -function markCommittedPriorityLevels(root, earliestRemainingTime) { - root.didError = !1; - if (0 === earliestRemainingTime) - (root.earliestPendingTime = 0), - (root.latestPendingTime = 0), - (root.earliestSuspendedTime = 0), - (root.latestSuspendedTime = 0), - (root.latestPingedTime = 0); - else { - earliestRemainingTime < root.latestPingedTime && - (root.latestPingedTime = 0); - var latestPendingTime = root.latestPendingTime; - 0 !== latestPendingTime && - (latestPendingTime > earliestRemainingTime - ? (root.earliestPendingTime = root.latestPendingTime = 0) - : root.earliestPendingTime > earliestRemainingTime && - (root.earliestPendingTime = root.latestPendingTime)); - latestPendingTime = root.earliestSuspendedTime; - 0 === latestPendingTime - ? markPendingPriorityLevel(root, earliestRemainingTime) - : earliestRemainingTime < root.latestSuspendedTime - ? ((root.earliestSuspendedTime = 0), - (root.latestSuspendedTime = 0), - (root.latestPingedTime = 0), - markPendingPriorityLevel(root, earliestRemainingTime)) - : earliestRemainingTime > latestPendingTime && - markPendingPriorityLevel(root, earliestRemainingTime); - } - findNextExpirationTimeToWorkOn(0, root); -} function markSuspendedPriorityLevel(root, suspendedTime) { root.didError = !1; root.latestPingedTime >= suspendedTime && (root.latestPingedTime = 0); @@ -2044,14 +2008,6 @@ function markSuspendedPriorityLevel(root, suspendedTime) { (root.latestSuspendedTime = suspendedTime); findNextExpirationTimeToWorkOn(suspendedTime, root); } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestPendingTime = root.earliestPendingTime; - root = root.earliestSuspendedTime; - earliestPendingTime > renderExpirationTime && - (renderExpirationTime = earliestPendingTime); - root > renderExpirationTime && (renderExpirationTime = root); - return renderExpirationTime; -} function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { var earliestSuspendedTime = root.earliestSuspendedTime, latestSuspendedTime = root.latestSuspendedTime, @@ -2166,37 +2122,37 @@ var classComponentUpdater = { }, enqueueSetState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueReplaceState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ReplaceState; update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueForceUpdate: function(inst, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ForceUpdate; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); } }; function checkShouldComponentUpdate( @@ -2321,17 +2277,19 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { element = element._owner; var inst = void 0; - element && - (invariant( - 1 === element.tag, - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ), - (inst = element.stateNode)); - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.", - returnFiber - ); + if (element) { + if (1 !== element.tag) + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + inst = element.stateNode; + } + if (!inst) + throw ReactError( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." + ); var stringRef = "" + returnFiber; if ( null !== current$$1 && @@ -2348,27 +2306,27 @@ function coerceRef(returnFiber, current$$1, element) { current$$1._stringRef = stringRef; return current$$1; } - invariant( - "string" === typeof returnFiber, - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) 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.", - returnFiber - ); + if ("string" !== typeof returnFiber) + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + if (!element._owner) + throw ReactError( + "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) { - "textarea" !== returnFiber.type && - invariant( - !1, - "Objects are not valid as a React child (found: %s).%s", - "[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - "" + if ("textarea" !== returnFiber.type) + throw ReactError( + "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) { @@ -2767,15 +2725,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) { var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - "function" === typeof iteratorFn, - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ); + if ("function" !== typeof iteratorFn) + throw ReactError( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); newChildrenIterable = iteratorFn.call(newChildrenIterable); - invariant( - null != newChildrenIterable, - "An iterable object provided no iterator." - ); + if (null == newChildrenIterable) + throw ReactError("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -2867,7 +2823,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) + if (isUnkeyedTopLevelFragment.key === isObject) { if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -2892,14 +2848,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren( - returnFiber, - isUnkeyedTopLevelFragment - ); - break; } - else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); + break; + } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -2935,7 +2887,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) + if (currentFirstChild.key === isUnkeyedTopLevelFragment) { if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -2955,11 +2907,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren(returnFiber, currentFirstChild); - break; } - else deleteChild(returnFiber, currentFirstChild); + deleteRemainingChildren(returnFiber, currentFirstChild); + break; + } else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3013,12 +2964,11 @@ function ChildReconciler(shouldTrackSideEffects) { switch (returnFiber.tag) { case 1: case 0: - (expirationTime = returnFiber.type), - invariant( - !1, - "%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.", - expirationTime.displayName || expirationTime.name || "Component" - ); + throw ((returnFiber = returnFiber.type), + ReactError( + (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); }; @@ -3030,10 +2980,10 @@ var reconcileChildFibers = ChildReconciler(!0), contextFiberStackCursor = { current: NO_CONTEXT }, rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ); + if (c === NO_CONTEXT) + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); return c; } function pushHostContainer(fiber, nextRootInstance) { @@ -3070,15 +3020,7 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -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 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3093,9 +3035,8 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - invariant( - !1, - "Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)" + throw ReactError( + "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) { @@ -3143,10 +3084,10 @@ function renderWithHooks( remainingExpirationTime = 0; componentUpdateQueue = null; sideEffectTag = 0; - invariant( - !current, - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ); + if (current) + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); return workInProgress; } function resetHooks() { @@ -3180,10 +3121,8 @@ function updateWorkInProgressHook() { (currentHook = nextCurrentHook), (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { - invariant( - null !== nextCurrentHook, - "Rendered more hooks than during the previous render." - ); + if (null === nextCurrentHook) + throw ReactError("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3206,10 +3145,11 @@ function basicStateReducer(state, action) { function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; - invariant( - null !== queue, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + if (null === queue) + throw ReactError( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { var _dispatch = queue.dispatch; if (null !== renderPhaseUpdates) { @@ -3224,8 +3164,7 @@ function updateReducer(reducer) { is(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } } @@ -3251,10 +3190,12 @@ function updateReducer(reducer) { (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && (remainingExpirationTime = updateExpirationTime)) - : (newState = + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (newState = _update.eagerReducer === reducer ? _update.eagerState - : reducer(newState, _update.action)); + : reducer(newState, _update.action))); baseUpdate = _update; _update = _update.next; } while (null !== _update && _update !== _dispatch); @@ -3264,8 +3205,7 @@ function updateReducer(reducer) { hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; } return [hook.memoizedState, queue.dispatch]; } @@ -3301,7 +3241,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; } } @@ -3328,10 +3268,10 @@ function imperativeHandleEffect(create, ref) { } function mountDebugValue() {} function dispatchAction(fiber, queue, action) { - invariant( - 25 > numberOfReRenders, - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ); + if (!(25 > numberOfReRenders)) + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); var alternate = fiber.alternate; if ( fiber === currentlyRenderingFiber$1 || @@ -3356,9 +3296,9 @@ function dispatchAction(fiber, queue, action) { queue.next = fiber; } else { - flushPassiveEffects(); - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, fiber); + flushPassiveEffects$$1(); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: currentTime, action: action, @@ -3377,10 +3317,10 @@ function dispatchAction(fiber, queue, action) { if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && - ((alternate = queue.eagerReducer), null !== alternate) + ((alternate = queue.lastRenderedReducer), null !== alternate) ) try { - var currentState = queue.eagerState, + var currentState = queue.lastRenderedState, _eagerState = alternate(currentState, action); _update2.eagerReducer = alternate; _update2.eagerState = _eagerState; @@ -3388,7 +3328,7 @@ function dispatchAction(fiber, queue, action) { } catch (error) { } finally { } - scheduleWork(fiber, currentTime); + scheduleWork$$1(fiber, currentTime); } } var ContextOnlyDispatcher = { @@ -3415,19 +3355,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(); @@ -3443,8 +3383,8 @@ var ContextOnlyDispatcher = { reducer = hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialArg + lastRenderedReducer: reducer, + lastRenderedState: initialArg }; reducer = reducer.dispatch = dispatchAction.bind( null, @@ -3465,8 +3405,8 @@ var ContextOnlyDispatcher = { initialState = hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }; initialState = initialState.dispatch = dispatchAction.bind( null, @@ -3494,19 +3434,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(); @@ -4082,7 +4022,10 @@ function updateSuspenseComponent( nextState = null; var nextDidTimeout = !1; } else - (nextState = { timedOutAt: null !== nextState ? nextState.timedOutAt : 0 }), + (nextState = { + fallbackExpirationTime: + null !== nextState ? nextState.fallbackExpirationTime : 0 + }), (nextDidTimeout = !0), (workInProgress.effectTag &= -65); if (null === current$$1) @@ -4177,10 +4120,8 @@ function bailoutOnAlreadyFinishedWork( null !== current$$1 && (workInProgress.contextDependencies = current$$1.contextDependencies); if (workInProgress.childExpirationTime < renderExpirationTime) return null; - invariant( - null === current$$1 || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + if (null !== current$$1 && workInProgress.child !== current$$1.child) + throw ReactError("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4345,59 +4286,57 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ((current$$1.alternate = null), (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); - hasContext = workInProgress.pendingProps; - current$$1 = readLazyComponentType(context); - workInProgress.type = current$$1; - context = workInProgress.tag = resolveLazyComponentTag(current$$1); - hasContext = resolveDefaultProps(current$$1, hasContext); - getDerivedStateFromProps = void 0; - switch (context) { + current$$1 = workInProgress.pendingProps; + context = readLazyComponentType(context); + workInProgress.type = context; + hasContext = workInProgress.tag = resolveLazyComponentTag(context); + current$$1 = resolveDefaultProps(context, current$$1); + switch (hasContext) { case 0: - getDerivedStateFromProps = updateFunctionComponent( + workInProgress = updateFunctionComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 1: - getDerivedStateFromProps = updateClassComponent( + workInProgress = updateClassComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 11: - getDerivedStateFromProps = updateForwardRef( + workInProgress = updateForwardRef( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 14: - getDerivedStateFromProps = updateMemoComponent( + workInProgress = updateMemoComponent( null, workInProgress, - current$$1, - resolveDefaultProps(current$$1.type, hasContext), + context, + resolveDefaultProps(context.type, current$$1), updateExpirationTime, renderExpirationTime ); break; default: - invariant( - !1, - "Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s", - current$$1, - "" + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + context + + ". Lazy element type must resolve to a class or function." ); } - return getDerivedStateFromProps; + return workInProgress; case 0: return ( (updateExpirationTime = workInProgress.type), @@ -4431,38 +4370,36 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); case 3: - return ( - pushHostRootContext(workInProgress), - (updateExpirationTime = workInProgress.updateQueue), - invariant( - null !== updateExpirationTime, + pushHostRootContext(workInProgress); + updateExpirationTime = workInProgress.updateQueue; + if (null === updateExpirationTime) + throw ReactError( "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." - ), - (context = workInProgress.memoizedState), - (context = null !== context ? context.element : null), - processUpdateQueue( - workInProgress, - updateExpirationTime, - workInProgress.pendingProps, - null, - renderExpirationTime - ), - (updateExpirationTime = workInProgress.memoizedState.element), - updateExpirationTime === context - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current$$1, - workInProgress, - renderExpirationTime - )) - : (reconcileChildren( - current$$1, - workInProgress, - updateExpirationTime, - renderExpirationTime - ), - (workInProgress = workInProgress.child)), - workInProgress + ); + context = workInProgress.memoizedState; + context = null !== context ? context.element : null; + processUpdateQueue( + workInProgress, + updateExpirationTime, + workInProgress.pendingProps, + null, + renderExpirationTime ); + updateExpirationTime = workInProgress.memoizedState.element; + updateExpirationTime === context + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current$$1, + workInProgress, + renderExpirationTime + )) + : (reconcileChildren( + current$$1, + workInProgress, + updateExpirationTime, + renderExpirationTime + ), + (workInProgress = workInProgress.child)); + return workInProgress; case 5: return ( pushHostContext(workInProgress), @@ -4475,8 +4412,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - (workInProgress = workInProgress.child), - workInProgress + workInProgress.child ); case 6: return ( @@ -4754,8 +4690,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); } - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -4791,17 +4726,17 @@ function readContext(context, observedBits) { if ("number" !== typeof observedBits || 1073741823 === observedBits) (lastContextWithAllBitsObserved = context), (observedBits = 1073741823); observedBits = { context: context, observedBits: observedBits, next: null }; - null === lastContextDependency - ? (invariant( - null !== currentlyRenderingFiber, + if (null === lastContextDependency) { + if (null === currentlyRenderingFiber) + throw ReactError( "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.contextDependencies = { - first: observedBits, - expirationTime: 0 - })) - : (lastContextDependency = lastContextDependency.next = observedBits); + ); + lastContextDependency = observedBits; + currentlyRenderingFiber.contextDependencies = { + first: observedBits, + expirationTime: 0 + }; + } else lastContextDependency = lastContextDependency.next = observedBits; } return context._currentValue; } @@ -4954,7 +4889,9 @@ function processUpdateQueue( ((newFirstUpdate = update), (newBaseState = resultState)), newExpirationTime < updateExpirationTime && (newExpirationTime = updateExpirationTime)) - : ((resultState = getStateFromUpdate( + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (resultState = getStateFromUpdate( workInProgress, queue, update, @@ -5027,11 +4964,11 @@ function commitUpdateEffects(effect, instance) { if (null !== _callback3) { effect.callback = null; var context = instance; - invariant( - "function" === typeof _callback3, - "Invalid argument passed as callback. Expected a function. Instead received: %s", - _callback3 - ); + if ("function" !== typeof _callback3) + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + _callback3 + ); _callback3.call(context); } effect = effect.nextEffect; @@ -5131,7 +5068,7 @@ function safelyDetachRef(current$$1) { try { ref(null); } catch (refError) { - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } else ref.current = null; } @@ -5141,12 +5078,12 @@ function commitHookEffectList(unmountTag, mountTag, finishedWork) { 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); @@ -5231,7 +5168,7 @@ function commitUnmount(current$$1$jscomp$0) { try { destroy(); } catch (error) { - captureCommitPhaseError(current$$1, error); + captureCommitPhaseError$$1(current$$1, error); } } effect = effect.next; @@ -5247,7 +5184,7 @@ function commitUnmount(current$$1$jscomp$0) { (updateQueue.state = current$$1$jscomp$0.memoizedState), updateQueue.componentWillUnmount(); } catch (unmountError) { - captureCommitPhaseError(current$$1$jscomp$0, unmountError); + captureCommitPhaseError$$1(current$$1$jscomp$0, unmountError); } break; case 5: @@ -5269,17 +5206,14 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - invariant( - !1, + throw ReactError( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); - parentFiber = void 0; } - var isContainer = (parent = void 0); switch (parentFiber.tag) { case 5: parent = parentFiber.stateNode; - isContainer = !1; + var isContainer = !1; break; case 3: parent = parentFiber.stateNode.containerInfo; @@ -5290,8 +5224,7 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - invariant( - !1, + throw ReactError( "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } @@ -5322,23 +5255,23 @@ function commitPlacement(finishedWork) { } } for (var node = finishedWork; ; ) { - if (5 === node.tag || 6 === node.tag) + if (5 === node.tag || 6 === node.tag) { + var stateNode = node.stateNode; if (parentFiber) - if (isContainer) - invariant( - "number" !== typeof parent, - "Container does not support insertBefore operation" - ); - else { + if (isContainer) { + if ("number" === typeof parent) + throw ReactError( + "Container does not support insertBefore operation" + ); + } else { var parentInstance = parent, - child = node.stateNode, beforeChild = parentFiber, children = parentInstance._children, - index = children.indexOf(child); + index = children.indexOf(stateNode); 0 <= index ? (children.splice(index, 1), (beforeChild = children.indexOf(beforeChild)), - children.splice(beforeChild, 0, child), + children.splice(beforeChild, 0, stateNode), UIManager.manageChildren( parentInstance._nativeTag, [index], @@ -5348,32 +5281,33 @@ function commitPlacement(finishedWork) { [] )) : ((index = children.indexOf(beforeChild)), - children.splice(index, 0, child), + children.splice(index, 0, stateNode), UIManager.manageChildren( parentInstance._nativeTag, [], [], - ["number" === typeof child ? child : child._nativeTag], + [ + "number" === typeof stateNode + ? stateNode + : stateNode._nativeTag + ], [index], [] )); } else isContainer - ? ((parentInstance = node.stateNode), - UIManager.setChildren(parent, [ - "number" === typeof parentInstance - ? parentInstance - : parentInstance._nativeTag - ])) + ? UIManager.setChildren(parent, [ + "number" === typeof stateNode ? stateNode : stateNode._nativeTag + ]) : ((parentInstance = parent), - (child = node.stateNode), - (children = "number" === typeof child ? child : child._nativeTag), + (children = + "number" === typeof stateNode ? stateNode : stateNode._nativeTag), (index = parentInstance._children), - (beforeChild = index.indexOf(child)), + (beforeChild = index.indexOf(stateNode)), 0 <= beforeChild ? (index.splice(beforeChild, 1), - index.push(child), + index.push(stateNode), UIManager.manageChildren( parentInstance._nativeTag, [beforeChild], @@ -5382,7 +5316,7 @@ function commitPlacement(finishedWork) { [], [] )) - : (index.push(child), + : (index.push(stateNode), UIManager.manageChildren( parentInstance._nativeTag, [], @@ -5391,7 +5325,7 @@ function commitPlacement(finishedWork) { [index.length - 1], [] ))); - else if (4 !== node.tag && null !== node.child) { + } else if (4 !== node.tag && null !== node.child) { node.child.return = node; node = node.child; continue; @@ -5417,10 +5351,10 @@ function unmountHostComponents(current$$1) { if (!currentParentIsValid) { currentParentIsValid = node.return; a: for (;;) { - invariant( - null !== currentParentIsValid, - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === currentParentIsValid) + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); switch (currentParentIsValid.tag) { case 5: currentParent = currentParentIsValid.stateNode; @@ -5499,7 +5433,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5508,66 +5442,76 @@ function commitWork(current$$1, finishedWork) { if (null != instance) { var newProps = finishedWork.memoizedProps; current$$1 = null !== current$$1 ? current$$1.memoizedProps : newProps; - var type = finishedWork.type, - updatePayload = finishedWork.updateQueue; + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; null !== updatePayload && - commitUpdate( - instance, - updatePayload, - type, + ((finishedWork = instance.viewConfig), + (instanceProps[instance._nativeTag] = newProps), + (newProps = diffProperties( + null, current$$1, newProps, - finishedWork - ); + finishedWork.validAttributes + )), + null != newProps && + UIManager.updateView( + instance._nativeTag, + finishedWork.uiViewClassName, + newProps + )); } break; case 6: - invariant( - null !== finishedWork.stateNode, - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === finishedWork.stateNode) + throw ReactError( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); UIManager.updateView(finishedWork.stateNode, "RCTRawText", { text: finishedWork.memoizedProps }); break; + case 20: + break; case 3: break; case 12: break; case 13: - instance = finishedWork.memoizedState; - newProps = void 0; - current$$1 = finishedWork; - null === instance - ? (newProps = !1) - : ((newProps = !0), - (current$$1 = finishedWork.child), - 0 === instance.timedOutAt && - (instance.timedOutAt = requestCurrentTime())); - null !== current$$1 && hideOrUnhideAllChildren(current$$1, newProps); - instance = finishedWork.updateQueue; - if (null !== instance) { - finishedWork.updateQueue = null; - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); - instance.forEach(function(thenable) { - var retry = resolveRetryThenable.bind(null, finishedWork, thenable); - retryCache.has(thenable) || - (retryCache.add(thenable), thenable.then(retry, retry)); - }); - } + commitSuspenseComponent(finishedWork); break; case 17: break; default: - invariant( - !1, + throw ReactError( "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, + newDidTimeout = void 0, + primaryChildParent = finishedWork; + null === newState + ? (newDidTimeout = !1) + : ((newDidTimeout = !0), + (primaryChildParent = finishedWork.child), + 0 === newState.fallbackExpirationTime && + (newState.fallbackExpirationTime = requestCurrentTime$$1() - 500)); + null !== primaryChildParent && + hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); + newState = finishedWork.updateQueue; + if (null !== newState) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + newState.forEach(function(thenable) { + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + retryCache.has(thenable) || + (retryCache.add(thenable), thenable.then(retry, retry)); + }); + } +} var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime = createUpdate(expirationTime); @@ -5575,7 +5519,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime.payload = { element: null }; var error = errorInfo.value; expirationTime.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return expirationTime; @@ -5617,17 +5561,15 @@ function unwindWork(workInProgress) { workInProgress) : null; case 3: - return ( - popHostContainer(workInProgress), - popTopLevelContextObject(workInProgress), - (effectTag = workInProgress.effectTag), - invariant( - 0 === (effectTag & 64), + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + effectTag = workInProgress.effectTag; + if (0 !== (effectTag & 64)) + throw ReactError( "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 - ); + ); + workInProgress.effectTag = (effectTag & -2049) | 64; + return workInProgress; case 5: return popHostContext(workInProgress), null; case 13: @@ -5644,17 +5586,27 @@ function unwindWork(workInProgress) { return popHostContainer(workInProgress), null; case 10: return popProvider(workInProgress), null; + case 19: + case 20: + return null; default: return null; } } -var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback, + cancelCallback$1 = Scheduler.unstable_cancelCallback, + shouldYield$1 = Scheduler.unstable_shouldYield, + now$1 = Scheduler.unstable_now, + getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel, + NormalPriority$1 = Scheduler.unstable_NormalPriority, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, isWorking = !1, nextUnitOfWork = null, nextRoot = null, nextRenderExpirationTime = 0, - nextLatestAbsoluteTimeoutMs = -1, + mostRecentEventTime = 1073741823, + nextRenderDidSuspend = !1, nextRenderDidError = !1, nextEffect = null, isCommitting$1 = !1, @@ -5695,184 +5647,10 @@ function resetStack() { } nextRoot = null; nextRenderExpirationTime = 0; - nextLatestAbsoluteTimeoutMs = -1; - nextRenderDidError = !1; + mostRecentEventTime = 1073741823; + nextRenderDidError = nextRenderDidSuspend = !1; nextUnitOfWork = null; } -function commitAllHostEffects() { - for (; null !== nextEffect; ) { - var effectTag = nextEffect.effectTag; - if (effectTag & 128) { - var current$$1 = nextEffect.alternate; - null !== current$$1 && - ((current$$1 = current$$1.ref), - null !== current$$1 && - ("function" === typeof current$$1 - ? current$$1(null) - : (current$$1.current = null))); - } - switch (effectTag & 14) { - case 2: - commitPlacement(nextEffect); - nextEffect.effectTag &= -3; - break; - case 6: - commitPlacement(nextEffect); - nextEffect.effectTag &= -3; - commitWork(nextEffect.alternate, nextEffect); - break; - case 4: - commitWork(nextEffect.alternate, nextEffect); - break; - case 8: - (effectTag = nextEffect), - unmountHostComponents(effectTag), - (effectTag.return = null), - (effectTag.child = null), - (effectTag.memoizedState = null), - (effectTag.updateQueue = null), - (effectTag = effectTag.alternate), - null !== effectTag && - ((effectTag.return = null), - (effectTag.child = null), - (effectTag.memoizedState = null), - (effectTag.updateQueue = null)); - } - nextEffect = nextEffect.nextEffect; - } -} -function commitBeforeMutationLifecycles() { - for (; null !== nextEffect; ) { - if (nextEffect.effectTag & 256) - a: { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); - break a; - 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 a; - case 3: - case 5: - case 6: - case 4: - case 17: - break a; - default: - invariant( - !1, - "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; - } -} -function commitAllLifeCycles(finishedRoot, committedExpirationTime$jscomp$0) { - for (; null !== nextEffect; ) { - var effectTag = nextEffect.effectTag; - if (effectTag & 36) { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect, - committedExpirationTime = committedExpirationTime$jscomp$0; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountLayout, MountLayout, finishedWork); - break; - case 1: - var instance = finishedWork.stateNode; - if (finishedWork.effectTag & 4) - if (null === current$$1) instance.componentDidMount(); - else { - var prevProps = - finishedWork.elementType === finishedWork.type - ? current$$1.memoizedProps - : resolveDefaultProps( - finishedWork.type, - current$$1.memoizedProps - ); - instance.componentDidUpdate( - prevProps, - current$$1.memoizedState, - instance.__reactInternalSnapshotBeforeUpdate - ); - } - current$$1 = finishedWork.updateQueue; - null !== current$$1 && - commitUpdateQueue( - finishedWork, - current$$1, - instance, - committedExpirationTime - ); - break; - case 3: - instance = finishedWork.updateQueue; - if (null !== instance) { - current$$1 = null; - if (null !== finishedWork.child) - switch (finishedWork.child.tag) { - case 5: - current$$1 = finishedWork.child.stateNode; - break; - case 1: - current$$1 = finishedWork.child.stateNode; - } - commitUpdateQueue( - finishedWork, - instance, - current$$1, - committedExpirationTime - ); - } - break; - case 5: - break; - case 6: - break; - case 4: - break; - case 12: - break; - case 13: - break; - case 17: - break; - default: - invariant( - !1, - "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." - ); - } - } - effectTag & 128 && - ((finishedWork = nextEffect.ref), - null !== finishedWork && - ((committedExpirationTime = nextEffect.stateNode), - "function" === typeof finishedWork - ? finishedWork(committedExpirationTime) - : (finishedWork.current = committedExpirationTime))); - effectTag & 512 && (rootWithPendingPassiveEffects = finishedRoot); - nextEffect = nextEffect.nextEffect; - } -} function commitPassiveEffects(root, firstEffect) { passiveEffectCallback = passiveEffectCallbackHandle = rootWithPendingPassiveEffects = null; var previousIsRendering = isRendering; @@ -5883,133 +5661,32 @@ function commitPassiveEffects(root, firstEffect) { error = void 0; try { var finishedWork = firstEffect; - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork); - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork); + commitHookEffectList(0, 64, finishedWork); } catch (e) { (didError = !0), (error = e); } - didError && captureCommitPhaseError(firstEffect, error); + didError && captureCommitPhaseError$1(firstEffect, error); } firstEffect = firstEffect.nextEffect; } while (null !== firstEffect); isRendering = previousIsRendering; previousIsRendering = root.expirationTime; 0 !== previousIsRendering && requestWork(root, previousIsRendering); - isBatchingUpdates || isRendering || performWork(1073741823, !1); + isBatchingUpdates || isRendering || performWork(1073741823); } -function flushPassiveEffects() { - if (null !== passiveEffectCallbackHandle) { - var callbackID = passiveEffectCallbackHandle; - scheduledCallback = null; - clearTimeout(callbackID); - } +function isAlreadyFailedLegacyErrorBoundary$1(instance) { + return ( + null !== legacyErrorBoundariesThatAlreadyFailed && + legacyErrorBoundariesThatAlreadyFailed.has(instance) + ); +} +function flushPassiveEffects$1() { + var didFlushEffects = null !== passiveEffectCallback; + null !== passiveEffectCallbackHandle && + cancelCallback$1(passiveEffectCallbackHandle); null !== passiveEffectCallback && passiveEffectCallback(); -} -function commitRoot(root, finishedWork) { - isCommitting$1 = isWorking = !0; - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." - ); - var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - 0 !== committedExpirationTime, - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); - root.pendingCommitExpirationTime = 0; - var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, - childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; - markCommittedPriorityLevels( - root, - childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit - ? childExpirationTimeBeforeCommit - : updateExpirationTimeBeforeCommit - ); - ReactCurrentOwner$2.current = null; - updateExpirationTimeBeforeCommit = void 0; - 1 < finishedWork.effectTag - ? null !== finishedWork.lastEffect - ? ((finishedWork.lastEffect.nextEffect = finishedWork), - (updateExpirationTimeBeforeCommit = finishedWork.firstEffect)) - : (updateExpirationTimeBeforeCommit = finishedWork) - : (updateExpirationTimeBeforeCommit = finishedWork.firstEffect); - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - var error = void 0; - try { - commitBeforeMutationLifecycles(); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - error = void 0; - try { - commitAllHostEffects(); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - root.current = finishedWork; - for (nextEffect = updateExpirationTimeBeforeCommit; null !== nextEffect; ) { - childExpirationTimeBeforeCommit = !1; - error = void 0; - try { - commitAllLifeCycles(root, committedExpirationTime); - } catch (e) { - (childExpirationTimeBeforeCommit = !0), (error = e); - } - childExpirationTimeBeforeCommit && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); - } - if ( - null !== updateExpirationTimeBeforeCommit && - null !== rootWithPendingPassiveEffects - ) { - var callback = commitPassiveEffects.bind( - null, - root, - updateExpirationTimeBeforeCommit - ); - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return scheduleDeferredCallback$1(callback); - } - ); - passiveEffectCallback = callback; - } - isWorking = isCommitting$1 = !1; - "function" === typeof onCommitFiberRoot && - onCommitFiberRoot(finishedWork.stateNode); - committedExpirationTime = finishedWork.expirationTime; - finishedWork = finishedWork.childExpirationTime; - finishedWork = - finishedWork > committedExpirationTime - ? finishedWork - : committedExpirationTime; - 0 === finishedWork && (legacyErrorBoundariesThatAlreadyFailed = null); - onCommit(root, finishedWork); + return didFlushEffects; } function completeUnitOfWork(workInProgress) { for (;;) { @@ -6062,13 +5739,12 @@ function completeUnitOfWork(workInProgress) { current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (newProps) { current = requiredContext(contextStackCursor$1.current); - var internalInstanceHandle = current$$1, - tag = allocateTag(), + var tag = allocateTag(), viewConfig = ReactNativeViewConfigRegistry.get(type); - invariant( - "RCTView" !== type || !current.isInAParentText, - "Nesting of within is not currently supported." - ); + if ("RCTView" === type && current.isInAParentText) + throw ReactError( + "Nesting of within is not currently supported." + ); var updatePayload = diffProperties( null, emptyObject, @@ -6082,7 +5758,7 @@ function completeUnitOfWork(workInProgress) { updatePayload ); viewConfig = new ReactNativeFiberHostComponent(tag, viewConfig); - instanceCache[tag] = internalInstanceHandle; + instanceCache[tag] = current$$1; instanceProps[tag] = newProps; appendAllChildren(viewConfig, current$$1, !1, !1); finalizeInitialChildren( @@ -6094,38 +5770,41 @@ function completeUnitOfWork(workInProgress) { ) && (current$$1.effectTag |= 4); current$$1.stateNode = viewConfig; null !== current$$1.ref && (current$$1.effectTag |= 128); - } else - invariant( - null !== current$$1.stateNode, + } else if (null === current$$1.stateNode) + throw ReactError( "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: - current && null != current$$1.stateNode - ? updateHostText$1( - current, - current$$1, - current.memoizedProps, - newProps - ) - : ("string" !== typeof newProps && - invariant( - null !== current$$1.stateNode, - "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)), - (type = requiredContext(contextStackCursor$1.current)), - (renderExpirationTime = current$$1), - invariant( - type.isInAParentText, + if (current && null != current$$1.stateNode) + updateHostText$1( + current, + current$$1, + current.memoizedProps, + newProps + ); + else { + if ("string" !== typeof newProps && null === current$$1.stateNode) + throw ReactError( + "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( "Text strings must be rendered within a component." - ), - (type = allocateTag()), - UIManager.createView(type, "RCTRawText", current, { - text: newProps - }), - (instanceCache[type] = current$$1), - (renderExpirationTime.stateNode = type)); + ); + renderExpirationTime = allocateTag(); + UIManager.createView( + renderExpirationTime, + "RCTRawText", + current, + { text: newProps } + ); + instanceCache[renderExpirationTime] = current$$1; + current$$1.stateNode = renderExpirationTime; + } break; case 11: break; @@ -6137,20 +5816,27 @@ function completeUnitOfWork(workInProgress) { break a; } newProps = null !== newProps; - renderExpirationTime = - null !== current && null !== current.memoizedState; + renderExpirationTime = !1; null !== current && - !newProps && - renderExpirationTime && - ((type = current.child.sibling), - null !== type && - ((current = current$$1.firstEffect), - null !== current - ? ((current$$1.firstEffect = type), - (type.nextEffect = current)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8))); + ((type = current.memoizedState), + (renderExpirationTime = null !== type), + newProps || + null === type || + ((type = type.fallbackExpirationTime), + type < mostRecentEventTime && (mostRecentEventTime = type), + (current = current.child.sibling), + null !== current && + ((type = current$$1.firstEffect), + null !== type + ? ((current$$1.firstEffect = current), + (current.nextEffect = type)) + : ((current$$1.firstEffect = current$$1.lastEffect = current), + (current.nextEffect = null)), + (current.effectTag = 8)))); + newProps && + !renderExpirationTime && + 0 !== (current$$1.mode & 1) && + (nextRenderDidSuspend = !0); if (newProps || renderExpirationTime) current$$1.effectTag |= 4; break; case 7: @@ -6175,9 +5861,12 @@ function completeUnitOfWork(workInProgress) { break; case 18: break; + case 19: + break; + case 20: + break; default: - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -6189,16 +5878,13 @@ function completeUnitOfWork(workInProgress) { 1 !== current$$1.childExpirationTime ) { newProps = 0; - for ( - renderExpirationTime = current$$1.child; - null !== renderExpirationTime; - - ) - (type = renderExpirationTime.expirationTime), - (current = renderExpirationTime.childExpirationTime), + for (current = current$$1.child; null !== current; ) + (renderExpirationTime = current.expirationTime), + (type = current.childExpirationTime), + renderExpirationTime > newProps && + (newProps = renderExpirationTime), type > newProps && (newProps = type), - current > newProps && (newProps = current), - (renderExpirationTime = renderExpirationTime.sibling); + (current = current.sibling); current$$1.childExpirationTime = newProps; } if (null !== nextUnitOfWork) return nextUnitOfWork; @@ -6241,11 +5927,11 @@ function performUnitOfWork(workInProgress) { return next; } function renderRoot(root$jscomp$0, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); - flushPassiveEffects(); + if (isWorking) + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + flushPassiveEffects$1(); isWorking = !0; var previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = ContextOnlyDispatcher; @@ -6268,7 +5954,7 @@ function renderRoot(root$jscomp$0, isYieldy) { do { try { if (isYieldy) - for (; null !== nextUnitOfWork && !(frameDeadline <= now$1()); ) + for (; null !== nextUnitOfWork && !shouldYield$1(); ) nextUnitOfWork = performUnitOfWork(nextUnitOfWork); else for (; null !== nextUnitOfWork; ) @@ -6279,15 +5965,16 @@ function renderRoot(root$jscomp$0, isYieldy) { resetHooks(), null === nextUnitOfWork) ) - (didFatal = !0), onUncaughtError(thrownValue); + (didFatal = !0), onUncaughtError$1(thrownValue); else { - invariant( - null !== nextUnitOfWork, - "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." - ); + if (null === nextUnitOfWork) + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); var sourceFiber = nextUnitOfWork, returnFiber = sourceFiber.return; - if (null === returnFiber) (didFatal = !0), onUncaughtError(thrownValue); + if (null === returnFiber) + (didFatal = !0), onUncaughtError$1(thrownValue); else { a: { var root = root$jscomp$0, @@ -6304,38 +5991,13 @@ function renderRoot(root$jscomp$0, isYieldy) { ) { var thenable = value; value = returnFiber$jscomp$0; - var earliestTimeoutMs = -1, - startTimeMs = -1; do { - if (13 === value.tag) { - var current$$1 = value.alternate; - if ( - null !== current$$1 && - ((current$$1 = current$$1.memoizedState), - null !== current$$1) - ) { - startTimeMs = 10 * (1073741822 - current$$1.timedOutAt); - break; - } - current$$1 = value.pendingProps.maxDuration; - if ("number" === typeof current$$1) - if (0 >= current$$1) earliestTimeoutMs = 0; - else if ( - -1 === earliestTimeoutMs || - current$$1 < earliestTimeoutMs - ) - earliestTimeoutMs = current$$1; - } - value = value.return; - } while (null !== value); - value = returnFiber$jscomp$0; - do { - if ((current$$1 = 13 === value.tag)) - current$$1 = - void 0 === value.memoizedProps.fallback - ? !1 - : null === value.memoizedState; - if (current$$1) { + if ( + 13 === value.tag && + (void 0 === value.memoizedProps.fallback + ? 0 + : null === value.memoizedState) + ) { returnFiber$jscomp$0 = value.updateQueue; null === returnFiber$jscomp$0 ? ((returnFiber$jscomp$0 = new Set()), @@ -6354,41 +6016,25 @@ function renderRoot(root$jscomp$0, isYieldy) { sourceFiber$jscomp$0.expirationTime = 1073741823; break a; } - sourceFiber$jscomp$0 = root; - returnFiber$jscomp$0 = returnFiber; - var pingCache = sourceFiber$jscomp$0.pingCache; + sourceFiber$jscomp$0 = returnFiber; + var pingCache = root.pingCache; null === pingCache - ? ((pingCache = sourceFiber$jscomp$0.pingCache = new PossiblyWeakMap()), - (current$$1 = new Set()), - pingCache.set(thenable, current$$1)) - : ((current$$1 = pingCache.get(thenable)), - void 0 === current$$1 && - ((current$$1 = new Set()), - pingCache.set(thenable, current$$1))); - current$$1.has(returnFiber$jscomp$0) || - (current$$1.add(returnFiber$jscomp$0), - (sourceFiber$jscomp$0 = pingSuspendedRoot.bind( + ? ((pingCache = root.pingCache = new PossiblyWeakMap()), + (returnFiber$jscomp$0 = new Set()), + pingCache.set(thenable, returnFiber$jscomp$0)) + : ((returnFiber$jscomp$0 = pingCache.get(thenable)), + void 0 === returnFiber$jscomp$0 && + ((returnFiber$jscomp$0 = new Set()), + pingCache.set(thenable, returnFiber$jscomp$0))); + returnFiber$jscomp$0.has(sourceFiber$jscomp$0) || + (returnFiber$jscomp$0.add(sourceFiber$jscomp$0), + (root = pingSuspendedRoot$$1.bind( null, - sourceFiber$jscomp$0, + root, thenable, - returnFiber$jscomp$0 + sourceFiber$jscomp$0 )), - thenable.then(sourceFiber$jscomp$0, sourceFiber$jscomp$0)); - -1 === earliestTimeoutMs - ? (root = 1073741823) - : (-1 === startTimeMs && - (startTimeMs = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root, - returnFiber - )) - - 5e3), - (root = startTimeMs + earliestTimeoutMs)); - 0 <= root && - nextLatestAbsoluteTimeoutMs < root && - (nextLatestAbsoluteTimeoutMs = root); + thenable.then(root, root)); value.effectTag |= 2048; value.expirationTime = returnFiber; break a; @@ -6415,25 +6061,24 @@ function renderRoot(root$jscomp$0, isYieldy) { break a; case 1: if ( - ((earliestTimeoutMs = value), - (startTimeMs = root.type), - (sourceFiber$jscomp$0 = root.stateNode), + ((sourceFiber$jscomp$0 = value), + (thenable = root.type), + (returnFiber$jscomp$0 = root.stateNode), 0 === (root.effectTag & 64) && ("function" === - typeof startTimeMs.getDerivedStateFromError || - (null !== sourceFiber$jscomp$0 && + typeof thenable.getDerivedStateFromError || + (null !== returnFiber$jscomp$0 && "function" === - typeof sourceFiber$jscomp$0.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has( - sourceFiber$jscomp$0 - ))))) + typeof returnFiber$jscomp$0.componentDidCatch && + !isAlreadyFailedLegacyErrorBoundary$$1( + returnFiber$jscomp$0 + )))) ) { root.effectTag |= 2048; root.expirationTime = returnFiber; returnFiber = createClassErrorUpdate( root, - earliestTimeoutMs, + sourceFiber$jscomp$0, returnFiber ); enqueueCapturedUpdate(root, returnFiber); @@ -6458,10 +6103,10 @@ function renderRoot(root$jscomp$0, isYieldy) { else if (null !== nextUnitOfWork) root$jscomp$0.finishedWork = null; else { previousDispatcher = root$jscomp$0.current.alternate; - invariant( - null !== previousDispatcher, - "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousDispatcher) + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); nextRoot = null; if (nextRenderDidError) { didFatal = root$jscomp$0.latestPendingTime; @@ -6496,19 +6141,11 @@ function renderRoot(root$jscomp$0, isYieldy) { return; } } - isYieldy && -1 !== nextLatestAbsoluteTimeoutMs + isYieldy && nextRenderDidSuspend && 1073741823 !== mostRecentEventTime ? (markSuspendedPriorityLevel(root$jscomp$0, expirationTime), (isYieldy = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root$jscomp$0, - expirationTime - ))), - isYieldy < nextLatestAbsoluteTimeoutMs && - (nextLatestAbsoluteTimeoutMs = isYieldy), - (isYieldy = 10 * (1073741822 - requestCurrentTime())), - (isYieldy = nextLatestAbsoluteTimeoutMs - isYieldy), + 10 * (1073741822 - mostRecentEventTime) - 5e3 + originalStartTimeMs), + (isYieldy = 150 - (now$1() - isYieldy)), onSuspend( root$jscomp$0, previousDispatcher, @@ -6520,7 +6157,7 @@ function renderRoot(root$jscomp$0, isYieldy) { (root$jscomp$0.finishedWork = previousDispatcher)); } } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { for (var fiber = sourceFiber.return; null !== fiber; ) { switch (fiber.tag) { case 1: @@ -6528,13 +6165,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( "function" === typeof fiber.type.getDerivedStateFromError || ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } break; @@ -6542,7 +6178,7 @@ function captureCommitPhaseError(sourceFiber, value) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createRootErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } fiber = fiber.return; @@ -6551,75 +6187,25 @@ function captureCommitPhaseError(sourceFiber, value) { ((fiber = createCapturedValue(value, sourceFiber)), (fiber = createRootErrorUpdate(sourceFiber, fiber, 1073741823)), enqueueUpdate(sourceFiber, fiber), - scheduleWork(sourceFiber, 1073741823)); + scheduleWork$1(sourceFiber, 1073741823)); } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(), - expirationTime = void 0; - if (0 === (fiber.mode & 1)) expirationTime = 1073741823; - else if (isWorking && !isCommitting$1) - expirationTime = nextRenderExpirationTime; - else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = 1073741823; - break; - case scheduler.unstable_UserBlockingPriority: - expirationTime = - 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1); - break; - case scheduler.unstable_NormalPriority: - expirationTime = - 1073741822 - 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = 1; - break; - default: - invariant( - !1, - "Unknown priority level. This error is likely caused by a bug in React. Please file an issue." - ); - } - null !== nextRoot && - expirationTime === nextRenderExpirationTime && - --expirationTime; - } - priorityLevel === scheduler.unstable_UserBlockingPriority && +function computeExpirationForFiber$1(currentTime, fiber) { + isWorking + ? (currentTime = isCommitting$1 ? 1073741823 : nextRenderExpirationTime) + : fiber.mode & 1 + ? ((currentTime = isBatchingInteractiveUpdates + ? 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1) + : 1073741822 - + 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1)), + null !== nextRoot && + currentTime === nextRenderExpirationTime && + --currentTime) + : (currentTime = 1073741823); + isBatchingInteractiveUpdates && (0 === lowestPriorityPendingInteractiveExpirationTime || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) && - (lowestPriorityPendingInteractiveExpirationTime = expirationTime); - return expirationTime; -} -function pingSuspendedRoot(root, thenable, pingTime) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(thenable); - if (null !== nextRoot && nextRenderExpirationTime === pingTime) - nextRoot = null; - else if ( - ((thenable = root.earliestSuspendedTime), - (pingCache = root.latestSuspendedTime), - 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) - ) { - root.didError = !1; - thenable = root.latestPingedTime; - if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; - findNextExpirationTimeToWorkOn(pingTime, root); - pingTime = root.expirationTime; - 0 !== pingTime && requestWork(root, pingTime); - } -} -function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = boundaryFiber.stateNode; - null !== retryCache && retryCache.delete(thenable); - thenable = requestCurrentTime(); - thenable = computeExpirationForFiber(thenable, boundaryFiber); - boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - (markPendingPriorityLevel(boundaryFiber, thenable), - (thenable = boundaryFiber.expirationTime), - 0 !== thenable && requestWork(boundaryFiber, thenable)); + currentTime < lowestPriorityPendingInteractiveExpirationTime) && + (lowestPriorityPendingInteractiveExpirationTime = currentTime); + return currentTime; } function scheduleWorkToRoot(fiber, expirationTime) { fiber.expirationTime < expirationTime && @@ -6647,9 +6233,10 @@ function scheduleWorkToRoot(fiber, expirationTime) { } return root; } -function scheduleWork(fiber, expirationTime) { +function scheduleWork$1(fiber, expirationTime) { fiber = scheduleWorkToRoot(fiber, expirationTime); - null !== fiber && + if ( + null !== fiber && (!isWorking && 0 !== nextRenderExpirationTime && expirationTime > nextRenderExpirationTime && @@ -6657,12 +6244,12 @@ function scheduleWork(fiber, expirationTime) { markPendingPriorityLevel(fiber, expirationTime), (isWorking && !isCommitting$1 && nextRoot === fiber) || requestWork(fiber, fiber.expirationTime), - nestedUpdateCount > NESTED_UPDATE_LIMIT && - ((nestedUpdateCount = 0), - invariant( - !1, - "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." - ))); + nestedUpdateCount > NESTED_UPDATE_LIMIT) + ) + throw ((nestedUpdateCount = 0), + ReactError( + "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." + )); } var firstScheduledRoot = null, lastScheduledRoot = null, @@ -6676,6 +6263,7 @@ var firstScheduledRoot = null, unhandledError = null, isBatchingUpdates = !1, isUnbatchingUpdates = !1, + isBatchingInteractiveUpdates = !1, completedBatches = null, originalStartTimeMs = now$1(), currentRendererTime = 1073741822 - ((originalStartTimeMs / 10) | 0), @@ -6690,13 +6278,14 @@ function recomputeCurrentRendererTime() { function scheduleCallbackWithExpirationTime(root, expirationTime) { if (0 !== callbackExpirationTime) { if (expirationTime < callbackExpirationTime) return; - null !== callbackID && - ((root = callbackID), (scheduledCallback = null), clearTimeout(root)); + null !== callbackID && cancelCallback$1(callbackID); } callbackExpirationTime = expirationTime; root = now$1() - originalStartTimeMs; - callbackID = scheduleDeferredCallback$1(performAsyncWork, { - timeout: 10 * (1073741822 - expirationTime) - root + expirationTime = 10 * (1073741822 - expirationTime) - root; + root = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(root, performAsyncWork, { + timeout: expirationTime }); } function onSuspend( @@ -6707,7 +6296,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - 0 !== msUntilTimeout || frameDeadline <= now$1() + 0 !== msUntilTimeout || shouldYield$1() ? 0 < msUntilTimeout && (root.timeoutHandle = scheduleTimeout( onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), @@ -6721,20 +6310,16 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { root.finishedWork = finishedWork; recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." - ); + if (isRendering) + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); nextFlushedRoot = root; nextFlushedExpirationTime = suspendedExpirationTime; performWorkOnRoot(root, suspendedExpirationTime, !1); - performWork(1073741823, !1); + performWork(1073741823); } -function onCommit(root, expirationTime) { - root.expirationTime = expirationTime; - root.finishedWork = null; -} -function requestCurrentTime() { +function requestCurrentTime$1() { if (isRendering) return currentSchedulerTime; findHighestPriorityRoot(); if (0 === nextFlushedExpirationTime || 1 === nextFlushedExpirationTime) @@ -6759,7 +6344,7 @@ function requestWork(root, expirationTime) { (nextFlushedExpirationTime = 1073741823), performWorkOnRoot(root, 1073741823, !1)) : 1073741823 === expirationTime - ? performWork(1073741823, !1) + ? performWork(1073741823) : scheduleCallbackWithExpirationTime(root, expirationTime)); } function findHighestPriorityRoot() { @@ -6773,10 +6358,10 @@ function findHighestPriorityRoot() { ) { var remainingExpirationTime = root.expirationTime; if (0 === remainingExpirationTime) { - invariant( - null !== previousScheduledRoot && null !== lastScheduledRoot, - "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousScheduledRoot || null === lastScheduledRoot) + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); if (root === root.nextScheduledRoot) { firstScheduledRoot = lastScheduledRoot = root.nextScheduledRoot = null; break; @@ -6819,58 +6404,57 @@ function performAsyncWork(didTimeout) { didTimeout = didTimeout.nextScheduledRoot; } while (didTimeout !== firstScheduledRoot); } - performWork(0, !0); -} -function performWork(minExpirationTime, isYieldy) { findHighestPriorityRoot(); - if (isYieldy) - for ( + recomputeCurrentRendererTime(); + for ( + currentSchedulerTime = currentRendererTime; + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime); + + ) + performWorkOnRoot( + nextFlushedRoot, + nextFlushedExpirationTime, + currentRendererTime > nextFlushedExpirationTime + ), + findHighestPriorityRoot(), recomputeCurrentRendererTime(), - currentSchedulerTime = currentRendererTime; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime && - !( - frameDeadline <= now$1() && - currentRendererTime > nextFlushedExpirationTime - ); - - ) - performWorkOnRoot( - nextFlushedRoot, - nextFlushedExpirationTime, - currentRendererTime > nextFlushedExpirationTime - ), - findHighestPriorityRoot(), - recomputeCurrentRendererTime(), - (currentSchedulerTime = currentRendererTime); - else - for ( - ; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime; - - ) - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), - findHighestPriorityRoot(); - isYieldy && ((callbackExpirationTime = 0), (callbackID = null)); + (currentSchedulerTime = currentRendererTime); + callbackExpirationTime = 0; + callbackID = null; 0 !== nextFlushedExpirationTime && scheduleCallbackWithExpirationTime( nextFlushedRoot, nextFlushedExpirationTime ); + finishRendering(); +} +function performWork(minExpirationTime) { + for ( + findHighestPriorityRoot(); + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + minExpirationTime <= nextFlushedExpirationTime; + + ) + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), + findHighestPriorityRoot(); + 0 !== nextFlushedExpirationTime && + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + finishRendering(); +} +function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; - if (null !== completedBatches) - for ( - minExpirationTime = completedBatches, - completedBatches = null, - isYieldy = 0; - isYieldy < minExpirationTime.length; - isYieldy++ - ) { - var batch = minExpirationTime[isYieldy]; + if (null !== completedBatches) { + var batches = completedBatches; + completedBatches = null; + for (var i = 0; i < batches.length; i++) { + var batch = batches[i]; try { batch._onComplete(); } catch (error) { @@ -6878,17 +6462,18 @@ function performWork(minExpirationTime, isYieldy) { ((hasUnhandledError = !0), (unhandledError = error)); } } + } if (hasUnhandledError) - throw ((minExpirationTime = unhandledError), + throw ((batches = unhandledError), (unhandledError = null), (hasUnhandledError = !1), - minExpirationTime); + batches); } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); + if (isRendering) + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); isRendering = !0; if (isYieldy) { var _finishedWork = root.finishedWork; @@ -6901,7 +6486,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { renderRoot(root, isYieldy), (_finishedWork = root.finishedWork), null !== _finishedWork && - (frameDeadline <= now$1() + (shouldYield$1() ? (root.finishedWork = _finishedWork) : completeRoot(root, _finishedWork, expirationTime))); } else @@ -6918,7 +6503,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { completeRoot(root, _finishedWork, expirationTime)); isRendering = !1; } -function completeRoot(root, finishedWork, expirationTime) { +function completeRoot(root, finishedWork$jscomp$0, expirationTime) { var firstBatch = root.firstBatch; if ( null !== firstBatch && @@ -6928,7 +6513,7 @@ function completeRoot(root, finishedWork, expirationTime) { : completedBatches.push(firstBatch), firstBatch._defer) ) { - root.finishedWork = finishedWork; + root.finishedWork = finishedWork$jscomp$0; root.expirationTime = 0; return; } @@ -6936,46 +6521,383 @@ function completeRoot(root, finishedWork, expirationTime) { root === lastCommittedRootDuringThisBatch ? nestedUpdateCount++ : ((lastCommittedRootDuringThisBatch = root), (nestedUpdateCount = 0)); - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); + isCommitting$1 = isWorking = !0; + if (root.current === finishedWork$jscomp$0) + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); + expirationTime = root.pendingCommitExpirationTime; + if (0 === expirationTime) + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); + root.pendingCommitExpirationTime = 0; + firstBatch = finishedWork$jscomp$0.expirationTime; + var childExpirationTimeBeforeCommit = + finishedWork$jscomp$0.childExpirationTime; + firstBatch = + childExpirationTimeBeforeCommit > firstBatch + ? childExpirationTimeBeforeCommit + : firstBatch; + root.didError = !1; + 0 === firstBatch + ? ((root.earliestPendingTime = 0), + (root.latestPendingTime = 0), + (root.earliestSuspendedTime = 0), + (root.latestSuspendedTime = 0), + (root.latestPingedTime = 0)) + : (firstBatch < root.latestPingedTime && (root.latestPingedTime = 0), + (childExpirationTimeBeforeCommit = root.latestPendingTime), + 0 !== childExpirationTimeBeforeCommit && + (childExpirationTimeBeforeCommit > firstBatch + ? (root.earliestPendingTime = root.latestPendingTime = 0) + : root.earliestPendingTime > firstBatch && + (root.earliestPendingTime = root.latestPendingTime)), + (childExpirationTimeBeforeCommit = root.earliestSuspendedTime), + 0 === childExpirationTimeBeforeCommit + ? markPendingPriorityLevel(root, firstBatch) + : firstBatch < root.latestSuspendedTime + ? ((root.earliestSuspendedTime = 0), + (root.latestSuspendedTime = 0), + (root.latestPingedTime = 0), + markPendingPriorityLevel(root, firstBatch)) + : firstBatch > childExpirationTimeBeforeCommit && + markPendingPriorityLevel(root, firstBatch)); + findNextExpirationTimeToWorkOn(0, root); + ReactCurrentOwner$2.current = null; + 1 < finishedWork$jscomp$0.effectTag + ? null !== finishedWork$jscomp$0.lastEffect + ? ((finishedWork$jscomp$0.lastEffect.nextEffect = finishedWork$jscomp$0), + (firstBatch = finishedWork$jscomp$0.firstEffect)) + : (firstBatch = finishedWork$jscomp$0) + : (firstBatch = finishedWork$jscomp$0.firstEffect); + for (nextEffect = firstBatch; null !== nextEffect; ) { + childExpirationTimeBeforeCommit = !1; + var error = void 0; + try { + for (; null !== nextEffect; ) { + if (nextEffect.effectTag & 256) { + var current$$1 = nextEffect.alternate, + finishedWork = nextEffect; + 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, + instance = finishedWork.stateNode, + snapshot = instance.getSnapshotBeforeUpdate( + finishedWork.elementType === finishedWork.type + ? prevProps + : resolveDefaultProps(finishedWork.type, prevProps), + prevState + ); + instance.__reactInternalSnapshotBeforeUpdate = snapshot; + } + break; + case 3: + case 5: + case 6: + case 4: + case 17: + case 20: + break; + default: + throw ReactError( + "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; + } + } catch (e) { + (childExpirationTimeBeforeCommit = !0), (error = e); } - ); + if (childExpirationTimeBeforeCommit) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + for (nextEffect = firstBatch; null !== nextEffect; ) { + current$$1 = !1; + prevProps = void 0; + try { + for (; 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; + null !== currentRef && + ("function" === typeof currentRef + ? currentRef(null) + : (currentRef.current = null)); + } + } + switch (effectTag & 14) { + case 2: + commitPlacement(nextEffect); + nextEffect.effectTag &= -3; + break; + case 6: + commitPlacement(nextEffect); + nextEffect.effectTag &= -3; + commitWork(nextEffect.alternate, nextEffect); + break; + case 4: + commitWork(nextEffect.alternate, nextEffect); + break; + case 8: + prevState = nextEffect; + unmountHostComponents(prevState); + prevState.return = null; + prevState.child = null; + prevState.memoizedState = null; + prevState.updateQueue = null; + var alternate = prevState.alternate; + null !== alternate && + ((alternate.return = null), + (alternate.child = null), + (alternate.memoizedState = null), + (alternate.updateQueue = null)); + } + nextEffect = nextEffect.nextEffect; + } + } catch (e) { + (current$$1 = !0), (prevProps = e); + } + if (current$$1) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, prevProps); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + root.current = finishedWork$jscomp$0; + for (nextEffect = firstBatch; null !== nextEffect; ) { + effectTag = !1; + current$$1$jscomp$0 = void 0; + try { + for ( + currentRef = root, alternate = expirationTime; + null !== nextEffect; + + ) { + var effectTag$jscomp$0 = nextEffect.effectTag; + if (effectTag$jscomp$0 & 36) { + var current$$1$jscomp$1 = nextEffect.alternate; + current$$1 = nextEffect; + prevProps = alternate; + switch (current$$1.tag) { + case 0: + case 11: + case 15: + commitHookEffectList(16, 32, current$$1); + break; + case 1: + var instance$jscomp$0 = current$$1.stateNode; + if (current$$1.effectTag & 4) + if (null === current$$1$jscomp$1) + instance$jscomp$0.componentDidMount(); + else { + var prevProps$jscomp$0 = + current$$1.elementType === current$$1.type + ? current$$1$jscomp$1.memoizedProps + : resolveDefaultProps( + current$$1.type, + current$$1$jscomp$1.memoizedProps + ); + instance$jscomp$0.componentDidUpdate( + prevProps$jscomp$0, + current$$1$jscomp$1.memoizedState, + instance$jscomp$0.__reactInternalSnapshotBeforeUpdate + ); + } + var updateQueue = current$$1.updateQueue; + null !== updateQueue && + commitUpdateQueue( + current$$1, + updateQueue, + instance$jscomp$0, + prevProps + ); + break; + case 3: + var _updateQueue = current$$1.updateQueue; + if (null !== _updateQueue) { + prevState = null; + if (null !== current$$1.child) + switch (current$$1.child.tag) { + case 5: + prevState = current$$1.child.stateNode; + break; + case 1: + prevState = current$$1.child.stateNode; + } + commitUpdateQueue( + current$$1, + _updateQueue, + prevState, + prevProps + ); + } + break; + case 5: + break; + case 6: + break; + case 4: + break; + case 12: + break; + case 13: + case 17: + case 20: + break; + default: + throw ReactError( + "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; + switch (nextEffect.tag) { + case 5: + current$$1 = instance$jscomp$1; + break; + default: + current$$1 = instance$jscomp$1; + } + "function" === typeof ref + ? ref(current$$1) + : (ref.current = current$$1); + } + } + effectTag$jscomp$0 & 512 && + (rootWithPendingPassiveEffects = currentRef); + nextEffect = nextEffect.nextEffect; + } + } catch (e) { + (effectTag = !0), (current$$1$jscomp$0 = e); + } + if (effectTag) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, current$$1$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } + } + null !== firstBatch && + null !== rootWithPendingPassiveEffects && + ((effectTag$jscomp$0 = commitPassiveEffects.bind(null, root, firstBatch)), + (passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + effectTag$jscomp$0 + )), + (passiveEffectCallback = effectTag$jscomp$0)); + isWorking = isCommitting$1 = !1; + "function" === typeof onCommitFiberRoot && + onCommitFiberRoot(finishedWork$jscomp$0.stateNode); + effectTag$jscomp$0 = finishedWork$jscomp$0.expirationTime; + finishedWork$jscomp$0 = finishedWork$jscomp$0.childExpirationTime; + finishedWork$jscomp$0 = + finishedWork$jscomp$0 > effectTag$jscomp$0 + ? finishedWork$jscomp$0 + : effectTag$jscomp$0; + 0 === finishedWork$jscomp$0 && + (legacyErrorBoundariesThatAlreadyFailed = null); + root.expirationTime = finishedWork$jscomp$0; + root.finishedWork = null; } -function onUncaughtError(error) { - invariant( - null !== nextFlushedRoot, - "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." - ); +function onUncaughtError$1(error) { + if (null === nextFlushedRoot) + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); nextFlushedRoot.expirationTime = 0; hasUnhandledError || ((hasUnhandledError = !0), (unhandledError = error)); } +Scheduler_now(); +var requestCurrentTime$$1 = requestCurrentTime$1, + computeExpirationForFiber$$1 = computeExpirationForFiber$1, + captureCommitPhaseError$$1 = captureCommitPhaseError$1, + onUncaughtError$$1 = onUncaughtError$1; +function pingSuspendedRoot$$1(root, thenable, pingTime) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(thenable); + if (null !== nextRoot && nextRenderExpirationTime === pingTime) + nextRoot = null; + else if ( + ((thenable = root.earliestSuspendedTime), + (pingCache = root.latestSuspendedTime), + 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) + ) { + root.didError = !1; + thenable = root.latestPingedTime; + if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; + findNextExpirationTimeToWorkOn(pingTime, root); + pingTime = root.expirationTime; + 0 !== pingTime && requestWork(root, pingTime); + } +} +function resolveRetryThenable$$1(boundaryFiber, thenable) { + var retryCache = boundaryFiber.stateNode; + null !== retryCache && retryCache.delete(thenable); + thenable = requestCurrentTime$1(); + thenable = computeExpirationForFiber$1(thenable, boundaryFiber); + boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); + null !== boundaryFiber && + (markPendingPriorityLevel(boundaryFiber, thenable), + (thenable = boundaryFiber.expirationTime), + 0 !== thenable && requestWork(boundaryFiber, thenable)); +} +var isAlreadyFailedLegacyErrorBoundary$$1 = isAlreadyFailedLegacyErrorBoundary$1, + scheduleWork$$1 = scheduleWork$1, + flushPassiveEffects$$1 = flushPassiveEffects$1; function findHostInstance(component) { var fiber = component._reactInternalFiber; - void 0 === fiber && - ("function" === typeof component.render - ? invariant(!1, "Unable to find node on an unmounted component.") - : invariant( - !1, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - )); + if (void 0 === fiber) { + if ("function" === typeof component.render) + throw ReactError("Unable to find node on an unmounted component."); + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } component = findCurrentHostFiber(fiber); return null === component ? null : component.stateNode; } function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, - currentTime = requestCurrentTime(); - current$$1 = computeExpirationForFiber(currentTime, current$$1); + currentTime = requestCurrentTime$$1(); + current$$1 = computeExpirationForFiber$$1(currentTime, current$$1); currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { - invariant( - 2 === isFiberMountedImpl(parentComponent) && 1 === parentComponent.tag, - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); + if ( + 2 !== isFiberMountedImpl(parentComponent) || + 1 !== parentComponent.tag + ) + throw ReactError( + "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 { switch (parentContext.tag) { @@ -6992,11 +6914,9 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - invariant( - !1, + throw ReactError( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); - parentContext = void 0; } if (1 === parentComponent.tag) { var Component = parentComponent.type; @@ -7019,9 +6939,9 @@ function updateContainer(element, container, parentComponent, callback) { callback.payload = { element: element }; container = void 0 === container ? null : container; null !== container && (callback.callback = container); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(currentTime, callback); - scheduleWork(currentTime, current$$1); + scheduleWork$$1(currentTime, current$$1); return current$$1; } function createPortal(children, containerInfo, implementation) { @@ -7056,7 +6976,9 @@ function _inherits(subClass, superClass) { } var getInspectorDataForViewTag = void 0; getInspectorDataForViewTag = function() { - invariant(!1, "getInspectorDataForViewTag() is not available in production"); + throw ReactError( + "getInspectorDataForViewTag() is not available in production" + ); }; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7079,13 +7001,13 @@ _batchedUpdatesImpl = function(fn, a) { } finally { (isBatchingUpdates = previousIsBatchingUpdates) || isRendering || - performWork(1073741823, !1); + performWork(1073741823); } }; _flushInteractiveUpdatesImpl = function() { isRendering || 0 === lowestPriorityPendingInteractiveExpirationTime || - (performWork(lowestPriorityPendingInteractiveExpirationTime, !1), + (performWork(lowestPriorityPendingInteractiveExpirationTime), (lowestPriorityPendingInteractiveExpirationTime = 0)); }; var roots = new Map(), @@ -7113,35 +7035,67 @@ var roots = new Map(), TextInputState.focusTextInput(findNodeHandle(this)); }; ReactNativeComponent.prototype.measure = function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }; ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7182,30 +7136,10 @@ var roots = new Map(), render: function(element, containerTag, callback) { var root = roots.get(containerTag); if (!root) { - root = createFiber(3, null, null, 0); - var root$jscomp$0 = { - current: root, - containerInfo: containerTag, - pendingChildren: null, - pingCache: null, - earliestPendingTime: 0, - latestPendingTime: 0, - earliestSuspendedTime: 0, - latestSuspendedTime: 0, - latestPingedTime: 0, - didError: !1, - pendingCommitExpirationTime: 0, - finishedWork: null, - timeoutHandle: -1, - context: null, - pendingContext: null, - hydrate: !1, - nextExpirationTimeToWorkOn: 0, - expirationTime: 0, - firstBatch: null, - nextScheduledRoot: null - }; - root = root.stateNode = root$jscomp$0; + root = new FiberRootNode(containerTag, !1); + var uninitializedFiber = createFiber(3, null, null, 0); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; roots.set(containerTag, root); } updateContainer(element, root, null, callback); @@ -7244,31 +7178,63 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }, setNativeProps: function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7306,7 +7272,10 @@ var roots = new Map(), var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: null, overrideProps: null, + setSuspenseHandler: null, + scheduleUpdate: null, currentDispatcherRef: ReactSharedInternals.ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { fiber = findCurrentHostFiber(fiber); @@ -7323,7 +7292,7 @@ var roots = new Map(), findFiberByHostInstance: getInstanceFromTag, getInspectorDataForViewTag: getInspectorDataForViewTag, bundleType: 0, - version: "16.8.3", + version: "16.8.6", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/oss/ReactNativeRenderer-profiling.js b/Libraries/Renderer/oss/ReactNativeRenderer-profiling.js index 3490e98d5f3..65b70bd7146 100644 --- a/Libraries/Renderer/oss/ReactNativeRenderer-profiling.js +++ b/Libraries/Renderer/oss/ReactNativeRenderer-profiling.js @@ -19,30 +19,94 @@ var ReactNativeViewConfigRegistry = require("ReactNativeViewConfigRegistry"), deepDiffer = require("deepDiffer"), flattenStyle = require("flattenStyle"), TextInputState = require("TextInputState"), + Scheduler = require("scheduler"), tracing = require("scheduler/tracing"), - scheduler = require("scheduler"), - ExceptionsManager = require("ExceptionsManager"); -function invariant(condition, format, a, b, c, d, e, f) { - if (!condition) { - condition = void 0; - if (void 0 === format) - condition = Error( - "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings." - ); - else { - var args = [a, b, c, d, e, f], - argIndex = 0; - condition = Error( - format.replace(/%s/g, function() { - return args[argIndex++]; - }) - ); - condition.name = "Invariant Violation"; - } - condition.framesToPop = 1; - throw condition; - } + ExceptionsManager = require("ExceptionsManager"), + FabricUIManager = require("FabricUIManager"); +function ReactError(message) { + message = Error(message); + message.name = "Invariant Violation"; + return message; } +var eventPluginOrder = null, + namesToPlugins = {}; +function recomputePluginOrdering() { + if (eventPluginOrder) + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName], + pluginIndex = eventPluginOrder.indexOf(pluginName); + if (!(-1 < pluginIndex)) + throw ReactError( + "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + + pluginName + + "`." + ); + if (!plugins[pluginIndex]) { + if (!pluginModule.extractEvents) + throw ReactError( + "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + + pluginName + + "` does not." + ); + plugins[pluginIndex] = pluginModule; + pluginIndex = pluginModule.eventTypes; + for (var eventName in pluginIndex) { + var JSCompiler_inline_result = void 0; + var dispatchConfig = pluginIndex[eventName], + pluginModule$jscomp$0 = pluginModule, + eventName$jscomp$0 = eventName; + if (eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0)) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same event name, `" + + eventName$jscomp$0 + + "`." + ); + eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + if (phasedRegistrationNames) { + for (JSCompiler_inline_result in phasedRegistrationNames) + phasedRegistrationNames.hasOwnProperty( + JSCompiler_inline_result + ) && + publishRegistrationName( + phasedRegistrationNames[JSCompiler_inline_result], + pluginModule$jscomp$0, + eventName$jscomp$0 + ); + JSCompiler_inline_result = !0; + } else + dispatchConfig.registrationName + ? (publishRegistrationName( + dispatchConfig.registrationName, + pluginModule$jscomp$0, + eventName$jscomp$0 + ), + (JSCompiler_inline_result = !0)) + : (JSCompiler_inline_result = !1); + if (!JSCompiler_inline_result) + throw ReactError( + "EventPluginRegistry: Failed to publish event `" + + eventName + + "` for plugin `" + + pluginName + + "`." + ); + } + } + } +} +function publishRegistrationName(registrationName, pluginModule) { + if (registrationNameModules[registrationName]) + throw ReactError( + "EventPluginHub: More than one plugin attempted to publish the same registration name, `" + + registrationName + + "`." + ); + registrationNameModules[registrationName] = pluginModule; +} +var plugins = [], + eventNameDispatchConfigs = {}, + registrationNameModules = {}; function invokeGuardedCallbackImpl(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { @@ -84,88 +148,13 @@ function invokeGuardedCallbackAndCatchFirstError( hasError = !1; caughtError = null; } else - invariant( - !1, + throw ReactError( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." - ), - (error = void 0); + ); hasRethrowError || ((hasRethrowError = !0), (rethrowError = error)); } } -var eventPluginOrder = null, - namesToPlugins = {}; -function recomputePluginOrdering() { - if (eventPluginOrder) - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName], - pluginIndex = eventPluginOrder.indexOf(pluginName); - invariant( - -1 < pluginIndex, - "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", - pluginName - ); - if (!plugins[pluginIndex]) { - invariant( - pluginModule.extractEvents, - "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", - pluginName - ); - plugins[pluginIndex] = pluginModule; - pluginIndex = pluginModule.eventTypes; - for (var eventName in pluginIndex) { - var JSCompiler_inline_result = void 0; - var dispatchConfig = pluginIndex[eventName], - pluginModule$jscomp$0 = pluginModule, - eventName$jscomp$0 = eventName; - invariant( - !eventNameDispatchConfigs.hasOwnProperty(eventName$jscomp$0), - "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", - eventName$jscomp$0 - ); - eventNameDispatchConfigs[eventName$jscomp$0] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (JSCompiler_inline_result in phasedRegistrationNames) - phasedRegistrationNames.hasOwnProperty( - JSCompiler_inline_result - ) && - publishRegistrationName( - phasedRegistrationNames[JSCompiler_inline_result], - pluginModule$jscomp$0, - eventName$jscomp$0 - ); - JSCompiler_inline_result = !0; - } else - dispatchConfig.registrationName - ? (publishRegistrationName( - dispatchConfig.registrationName, - pluginModule$jscomp$0, - eventName$jscomp$0 - ), - (JSCompiler_inline_result = !0)) - : (JSCompiler_inline_result = !1); - invariant( - JSCompiler_inline_result, - "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", - eventName, - pluginName - ); - } - } - } -} -function publishRegistrationName(registrationName, pluginModule) { - invariant( - !registrationNameModules[registrationName], - "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", - registrationName - ); - registrationNameModules[registrationName] = pluginModule; -} -var plugins = [], - eventNameDispatchConfigs = {}, - registrationNameModules = {}, - getFiberCurrentPropsFromNode = null, +var getFiberCurrentPropsFromNode = null, getInstanceFromNode = null, getNodeFromInstance = null; function executeDispatch(event, listener, inst) { @@ -177,10 +166,8 @@ function executeDispatch(event, listener, inst) { function executeDirectDispatch(event) { var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; - invariant( - !Array.isArray(dispatchListener), - "executeDirectDispatch(...): Invalid `event`." - ); + if (Array.isArray(dispatchListener)) + throw ReactError("executeDirectDispatch(...): Invalid `event`."); event.currentTarget = dispatchListener ? getNodeFromInstance(dispatchInstance) : null; @@ -191,10 +178,10 @@ function executeDirectDispatch(event) { return dispatchListener; } function accumulateInto(current, next) { - invariant( - null != next, - "accumulateInto(...): Accumulated items must not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulateInto(...): Accumulated items must not be null or undefined." + ); if (null == current) return next; if (Array.isArray(current)) { if (Array.isArray(next)) return current.push.apply(current, next), current; @@ -228,10 +215,10 @@ function executeDispatchesAndReleaseTopLevel(e) { } var injection = { injectEventPluginOrder: function(injectedEventPluginOrder) { - invariant( - !eventPluginOrder, - "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." - ); + if (eventPluginOrder) + throw ReactError( + "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,15 +228,19 @@ var injection = { for (pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { var pluginModule = injectedNamesToPlugins[pluginName]; - (namesToPlugins.hasOwnProperty(pluginName) && - namesToPlugins[pluginName] === pluginModule) || - (invariant( - !namesToPlugins[pluginName], - "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", - pluginName - ), - (namesToPlugins[pluginName] = pluginModule), - (isOrderingDirty = !0)); + if ( + !namesToPlugins.hasOwnProperty(pluginName) || + namesToPlugins[pluginName] !== pluginModule + ) { + if (namesToPlugins[pluginName]) + throw ReactError( + "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + + pluginName + + "`." + ); + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = !0; + } } isOrderingDirty && recomputePluginOrdering(); } @@ -285,12 +276,14 @@ function getListener(inst, registrationName) { inst = !1; } if (inst) return null; - invariant( - !listener || "function" === typeof listener, - "Expected `%s` listener to be a function, instead got a value of `%s` type.", - registrationName, - typeof listener - ); + if (listener && "function" !== typeof listener) + throw ReactError( + "Expected `" + + registrationName + + "` listener to be a function, instead got a value of `" + + typeof listener + + "` type." + ); return listener; } function getParent(inst) { @@ -451,10 +444,10 @@ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { return new this(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { - invariant( - event instanceof this, - "Trying to release an event instance into a pool of a different type." - ); + if (!(event instanceof this)) + throw ReactError( + "Trying to release an event instance into a pool of a different type." + ); event.destructor(); 10 > this.eventPool.length && this.eventPool.push(event); } @@ -489,7 +482,7 @@ function timestampForTouch(touch) { } function getTouchIdentifier(_ref) { _ref = _ref.identifier; - invariant(null != _ref, "Touch object is missing identifier."); + if (null == _ref) throw ReactError("Touch object is missing identifier."); return _ref; } function recordTouchStart(touch) { @@ -602,10 +595,10 @@ var ResponderTouchHistoryStore = { touchHistory: touchHistory }; function accumulate(current, next) { - invariant( - null != next, - "accumulate(...): Accumulated items must be not be null or undefined." - ); + if (null == next) + throw ReactError( + "accumulate(...): Accumulated items must be not be null or undefined." + ); return null == current ? next : Array.isArray(current) @@ -970,11 +963,10 @@ var eventTypes$1 = { ReactNativeViewConfigRegistry.customBubblingEventTypes[topLevelType], directDispatchConfig = ReactNativeViewConfigRegistry.customDirectEventTypes[topLevelType]; - invariant( - bubbleDispatchConfig || directDispatchConfig, - 'Unsupported top level event type "%s" dispatched', - topLevelType - ); + if (!bubbleDispatchConfig && !directDispatchConfig) + throw ReactError( + 'Unsupported top level event type "' + topLevelType + '" dispatched' + ); topLevelType = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, @@ -1005,14 +997,10 @@ function getInstanceFromTag(tag) { var restoreTarget = null, restoreQueue = null; function restoreStateOfTarget(target) { - if ((target = getInstanceFromNode(target))) { - invariant( - !1, + if (getInstanceFromNode(target)) + throw ReactError( "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(target.stateNode); - null(target.stateNode, target.type, props); - } } function _batchedUpdatesImpl(fn, bookkeeping) { return fn(bookkeeping); @@ -1060,19 +1048,18 @@ function _receiveRootNodeIDEvent(rootNodeID, topLevelType, nativeEventParam) { null !== events && (eventQueue = accumulateInto(eventQueue, events)); events = eventQueue; eventQueue = null; - if ( - events && - (forEachAccumulated(events, executeDispatchesAndReleaseTopLevel), - invariant( - !eventQueue, - "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." - ), - hasRethrowError) - ) - throw ((events = rethrowError), - (hasRethrowError = !1), - (rethrowError = null), - events); + if (events) { + forEachAccumulated(events, executeDispatchesAndReleaseTopLevel); + if (eventQueue) + throw ReactError( + "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." + ); + if (hasRethrowError) + throw ((events = rethrowError), + (hasRethrowError = !1), + (rethrowError = null), + events); + } }); } RCTEventEmitter.register({ @@ -1119,7 +1106,7 @@ getInstanceFromNode = getInstanceFromTag; getNodeFromInstance = function(inst) { var tag = inst.stateNode._nativeTag; void 0 === tag && (tag = inst.stateNode.canonical._nativeTag); - invariant(tag, "All native instances should have a tag."); + if (!tag) throw ReactError("All native instances should have a tag."); return tag; }; ResponderEventPlugin.injection.injectGlobalResponderHandler({ @@ -1148,6 +1135,15 @@ var hasSymbol = "function" === typeof Symbol && Symbol.for, REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113, REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115, REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116, + REACT_EVENT_COMPONENT_TYPE = hasSymbol + ? Symbol.for("react.event_component") + : 60117, + REACT_EVENT_TARGET_TYPE = hasSymbol + ? Symbol.for("react.event_target") + : 60118, + REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol + ? Symbol.for("react.event_target.touch_hit") + : 60119, MAYBE_ITERATOR_SYMBOL = "function" === typeof Symbol && Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; @@ -1192,6 +1188,15 @@ function getComponentName(type) { case REACT_LAZY_TYPE: if ((type = 1 === type._status ? type._result : null)) return getComponentName(type); + break; + case REACT_EVENT_COMPONENT_TYPE: + type = type.displayName; + if (void 0 !== type) return type; + break; + case REACT_EVENT_TARGET_TYPE: + if (type.type === REACT_EVENT_TARGET_TOUCH_HIT) return "TouchHitTarget"; + type = type.displayName; + if (void 0 !== type) return type; } return null; } @@ -1206,80 +1211,83 @@ function isFiberMountedImpl(fiber) { return 3 === node.tag ? 2 : 3; } function assertIsMounted(fiber) { - invariant( - 2 === isFiberMountedImpl(fiber), - "Unable to find node on an unmounted component." - ); + if (2 !== isFiberMountedImpl(fiber)) + throw ReactError("Unable to find node on an unmounted component."); } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; - if (!alternate) - return ( - (alternate = isFiberMountedImpl(fiber)), - invariant( - 3 !== alternate, - "Unable to find node on an unmounted component." - ), - 1 === alternate ? null : fiber - ); + if (!alternate) { + alternate = isFiberMountedImpl(fiber); + if (3 === alternate) + throw ReactError("Unable to find node on an unmounted component."); + return 1 === alternate ? null : fiber; + } for (var a = fiber, b = alternate; ; ) { - var parentA = a.return, - parentB = parentA ? parentA.alternate : null; - if (!parentA || !parentB) break; - if (parentA.child === parentB.child) { - for (var child = parentA.child; child; ) { - if (child === a) return assertIsMounted(parentA), fiber; - if (child === b) return assertIsMounted(parentA), alternate; - child = child.sibling; + var parentA = a.return; + if (null === parentA) break; + var parentB = parentA.alternate; + if (null === parentB) { + b = parentA.return; + if (null !== b) { + a = b; + continue; } - invariant(!1, "Unable to find node on an unmounted component."); + break; + } + if (parentA.child === parentB.child) { + for (parentB = parentA.child; parentB; ) { + if (parentB === a) return assertIsMounted(parentA), fiber; + if (parentB === b) return assertIsMounted(parentA), alternate; + parentB = parentB.sibling; + } + throw ReactError("Unable to find node on an unmounted component."); } if (a.return !== b.return) (a = parentA), (b = parentB); else { - child = !1; - for (var _child = parentA.child; _child; ) { + for (var didFindChild = !1, _child = parentA.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentA; b = parentB; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentA; a = parentB; break; } _child = _child.sibling; } - if (!child) { + if (!didFindChild) { for (_child = parentB.child; _child; ) { if (_child === a) { - child = !0; + didFindChild = !0; a = parentB; b = parentA; break; } if (_child === b) { - child = !0; + didFindChild = !0; b = parentB; a = parentA; break; } _child = _child.sibling; } - invariant( - child, - "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 ReactError( + "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." + ); } } - invariant( - a.alternate === b, - "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." - ); + if (a.alternate !== b) + throw ReactError( + "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." + ); } - invariant(3 === a.tag, "Unable to find node on an unmounted component."); + if (3 !== a.tag) + throw ReactError("Unable to find node on an unmounted component."); return a.stateNode.current === a ? fiber : alternate; } function findCurrentHostFiber(parent) { @@ -1528,86 +1536,72 @@ 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() { - TextInputState.blurTextInput(this._nativeTag); - }; - ReactNativeFiberHostComponent.prototype.focus = function() { - TextInputState.focusTextInput(this._nativeTag); - }; - ReactNativeFiberHostComponent.prototype.measure = function(callback) { - UIManager.measure( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - ReactNativeFiberHostComponent.prototype.measureInWindow = function( - callback - ) { - UIManager.measureInWindow( - this._nativeTag, - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); - }; - ReactNativeFiberHostComponent.prototype.measureLayout = function( - relativeToNativeNode, - onSuccess, - onFail - ) { + 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() { + TextInputState.blurTextInput(this._nativeTag); + }; + ReactNativeFiberHostComponent.prototype.focus = function() { + TextInputState.focusTextInput(this._nativeTag); + }; + ReactNativeFiberHostComponent.prototype.measure = function(callback) { + UIManager.measure( + this._nativeTag, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ); + }; + ReactNativeFiberHostComponent.prototype.measureInWindow = function(callback) { + 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); + null != relativeNode && UIManager.measureLayout( this._nativeTag, - relativeToNativeNode, + relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) ); - }; - ReactNativeFiberHostComponent.prototype.setNativeProps = function( - nativeProps - ) { - nativeProps = diffProperties( - null, - emptyObject, - nativeProps, - this.viewConfig.validAttributes + }; + ReactNativeFiberHostComponent.prototype.setNativeProps = function( + nativeProps + ) { + nativeProps = diffProperties( + null, + emptyObject, + nativeProps, + this.viewConfig.validAttributes + ); + null != nativeProps && + UIManager.updateView( + this._nativeTag, + this.viewConfig.uiViewClassName, + nativeProps ); - null != nativeProps && - UIManager.updateView( - this._nativeTag, - this.viewConfig.uiViewClassName, - nativeProps - ); - }; - return ReactNativeFiberHostComponent; - })(), - now$1 = - "object" === typeof performance && "function" === typeof performance.now - ? function() { - return performance.now(); - } - : function() { - return Date.now(); - }, - scheduledCallback = null, - frameDeadline = 0; -function setTimeoutCallback() { - frameDeadline = now$1() + 5; - var callback = scheduledCallback; - scheduledCallback = null; - null !== callback && callback(); -} -function scheduleDeferredCallback$1(callback) { - scheduledCallback = callback; - return setTimeout(setTimeoutCallback, 1); -} + }; + return ReactNativeFiberHostComponent; +})(); function shim$1() { - invariant( - !1, + throw ReactError( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." ); } @@ -1638,24 +1632,8 @@ function finalizeInitialChildren(parentInstance) { return !1; } var scheduleTimeout = setTimeout, - cancelTimeout = clearTimeout; -function commitUpdate(instance, updatePayloadTODO, type, oldProps, newProps) { - updatePayloadTODO = instance.viewConfig; - instanceProps[instance._nativeTag] = newProps; - oldProps = diffProperties( - null, - oldProps, - newProps, - updatePayloadTODO.validAttributes - ); - null != oldProps && - UIManager.updateView( - instance._nativeTag, - updatePayloadTODO.uiViewClassName, - oldProps - ); -} -var BEFORE_SLASH_RE = /^(.*)[\\\/]/; + cancelTimeout = clearTimeout, + BEFORE_SLASH_RE = /^(.*)[\\\/]/; function getStackByFiberInDevAndProd(workInProgress) { var info = ""; do { @@ -1739,10 +1717,10 @@ function popTopLevelContextObject(fiber) { pop(contextStackCursor, fiber); } function pushTopLevelContextObject(fiber, context, didChange) { - invariant( - contextStackCursor.current === emptyContextObject, - "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." - ); + if (contextStackCursor.current !== emptyContextObject) + throw ReactError( + "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); } @@ -1752,12 +1730,13 @@ function processChildContext(fiber, type, parentContext) { if ("function" !== typeof instance.getChildContext) return parentContext; instance = instance.getChildContext(); for (var contextKey in instance) - invariant( - contextKey in fiber, - '%s.getChildContext(): key "%s" is not defined in childContextTypes.', - getComponentName(type) || "Unknown", - contextKey - ); + if (!(contextKey in fiber)) + throw ReactError( + (getComponentName(type) || "Unknown") + + '.getChildContext(): key "' + + contextKey + + '" is not defined in childContextTypes.' + ); return Object.assign({}, parentContext, instance); } function pushContextProvider(workInProgress) { @@ -1776,10 +1755,10 @@ function pushContextProvider(workInProgress) { } function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; - invariant( - instance, - "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 ReactError( + "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)), (instance.__reactInternalMemoizedMergedChildContext = type), @@ -1814,6 +1793,7 @@ function injectInternals(internals) { } catch (err) {} return !0; } +var Scheduler_now = Scheduler.unstable_now; function FiberNode(tag, pendingProps, key, mode) { this.tag = tag; this.key = key; @@ -1944,11 +1924,10 @@ function createFiberFromTypeAndProps( owner = null; break a; } - invariant( - !1, - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", - null == type ? type : typeof type, - "" + throw ReactError( + "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); @@ -1990,6 +1969,24 @@ function createFiberFromPortal(portal, mode, expirationTime) { }; return mode; } +function FiberRootNode(containerInfo, hydrate) { + this.current = null; + this.containerInfo = containerInfo; + this.pingCache = this.pendingChildren = null; + this.pendingCommitExpirationTime = 0; + this.finishedWork = null; + this.timeoutHandle = -1; + this.pendingContext = this.context = null; + this.hydrate = hydrate; + this.firstBatch = null; + this.latestPingedTime = this.latestSuspendedTime = this.earliestSuspendedTime = this.latestPendingTime = this.earliestPendingTime = 0; + this.didError = !1; + this.expirationTime = this.nextExpirationTimeToWorkOn = 0; + this.nextScheduledRoot = null; + this.interactionThreadID = tracing.unstable_getThreadID(); + this.memoizedInteractions = new Set(); + this.pendingInteractionMap = new Map(); +} function markPendingPriorityLevel(root, expirationTime) { root.didError = !1; var earliestPendingTime = root.earliestPendingTime; @@ -2064,14 +2061,6 @@ function markSuspendedPriorityLevel(root, suspendedTime) { (root.latestSuspendedTime = suspendedTime); findNextExpirationTimeToWorkOn(suspendedTime, root); } -function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { - var earliestPendingTime = root.earliestPendingTime; - root = root.earliestSuspendedTime; - earliestPendingTime > renderExpirationTime && - (renderExpirationTime = earliestPendingTime); - root > renderExpirationTime && (renderExpirationTime = root); - return renderExpirationTime; -} function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { var earliestSuspendedTime = root.earliestSuspendedTime, latestSuspendedTime = root.latestSuspendedTime, @@ -2186,37 +2175,37 @@ var classComponentUpdater = { }, enqueueSetState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueReplaceState: function(inst, payload, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ReplaceState; update.payload = payload; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); }, enqueueForceUpdate: function(inst, callback) { inst = inst._reactInternalFiber; - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, inst); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, inst); var update = createUpdate(currentTime); update.tag = ForceUpdate; void 0 !== callback && null !== callback && (update.callback = callback); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(inst, update); - scheduleWork(inst, currentTime); + scheduleWork$$1(inst, currentTime); } }; function checkShouldComponentUpdate( @@ -2341,17 +2330,19 @@ function coerceRef(returnFiber, current$$1, element) { if (element._owner) { element = element._owner; var inst = void 0; - element && - (invariant( - 1 === element.tag, - "Function components cannot have refs. Did you mean to use React.forwardRef()?" - ), - (inst = element.stateNode)); - invariant( - inst, - "Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.", - returnFiber - ); + if (element) { + if (1 !== element.tag) + throw ReactError( + "Function components cannot have refs. Did you mean to use React.forwardRef()?" + ); + inst = element.stateNode; + } + if (!inst) + throw ReactError( + "Missing owner for string ref " + + returnFiber + + ". This error is likely caused by a bug in React. Please file an issue." + ); var stringRef = "" + returnFiber; if ( null !== current$$1 && @@ -2368,27 +2359,27 @@ function coerceRef(returnFiber, current$$1, element) { current$$1._stringRef = stringRef; return current$$1; } - invariant( - "string" === typeof returnFiber, - "Expected ref to be a function, a string, an object returned by React.createRef(), or null." - ); - invariant( - element._owner, - "Element ref was specified as a string (%s) 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.", - returnFiber - ); + if ("string" !== typeof returnFiber) + throw ReactError( + "Expected ref to be a function, a string, an object returned by React.createRef(), or null." + ); + if (!element._owner) + throw ReactError( + "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) { - "textarea" !== returnFiber.type && - invariant( - !1, - "Objects are not valid as a React child (found: %s).%s", - "[object Object]" === Object.prototype.toString.call(newChild) - ? "object with keys {" + Object.keys(newChild).join(", ") + "}" - : newChild, - "" + if ("textarea" !== returnFiber.type) + throw ReactError( + "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) { @@ -2787,15 +2778,13 @@ function ChildReconciler(shouldTrackSideEffects) { expirationTime ) { var iteratorFn = getIteratorFn(newChildrenIterable); - invariant( - "function" === typeof iteratorFn, - "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." - ); + if ("function" !== typeof iteratorFn) + throw ReactError( + "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." + ); newChildrenIterable = iteratorFn.call(newChildrenIterable); - invariant( - null != newChildrenIterable, - "An iterable object provided no iterator." - ); + if (null == newChildrenIterable) + throw ReactError("An iterable object provided no iterator."); for ( var previousNewFiber = (iteratorFn = null), oldFiber = currentFirstChild, @@ -2887,7 +2876,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== isUnkeyedTopLevelFragment; ) { - if (isUnkeyedTopLevelFragment.key === isObject) + if (isUnkeyedTopLevelFragment.key === isObject) { if ( 7 === isUnkeyedTopLevelFragment.tag ? newChild.type === REACT_FRAGMENT_TYPE @@ -2912,14 +2901,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren( - returnFiber, - isUnkeyedTopLevelFragment - ); - break; } - else deleteChild(returnFiber, isUnkeyedTopLevelFragment); + deleteRemainingChildren(returnFiber, isUnkeyedTopLevelFragment); + break; + } else deleteChild(returnFiber, isUnkeyedTopLevelFragment); isUnkeyedTopLevelFragment = isUnkeyedTopLevelFragment.sibling; } newChild.type === REACT_FRAGMENT_TYPE @@ -2955,7 +2940,7 @@ function ChildReconciler(shouldTrackSideEffects) { null !== currentFirstChild; ) { - if (currentFirstChild.key === isUnkeyedTopLevelFragment) + if (currentFirstChild.key === isUnkeyedTopLevelFragment) { if ( 4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === @@ -2975,11 +2960,10 @@ function ChildReconciler(shouldTrackSideEffects) { currentFirstChild.return = returnFiber; returnFiber = currentFirstChild; break a; - } else { - deleteRemainingChildren(returnFiber, currentFirstChild); - break; } - else deleteChild(returnFiber, currentFirstChild); + deleteRemainingChildren(returnFiber, currentFirstChild); + break; + } else deleteChild(returnFiber, currentFirstChild); currentFirstChild = currentFirstChild.sibling; } currentFirstChild = createFiberFromPortal( @@ -3033,12 +3017,11 @@ function ChildReconciler(shouldTrackSideEffects) { switch (returnFiber.tag) { case 1: case 0: - (expirationTime = returnFiber.type), - invariant( - !1, - "%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.", - expirationTime.displayName || expirationTime.name || "Component" - ); + throw ((returnFiber = returnFiber.type), + ReactError( + (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); }; @@ -3050,10 +3033,10 @@ var reconcileChildFibers = ChildReconciler(!0), contextFiberStackCursor = { current: NO_CONTEXT }, rootInstanceStackCursor = { current: NO_CONTEXT }; function requiredContext(c) { - invariant( - c !== NO_CONTEXT, - "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." - ); + if (c === NO_CONTEXT) + throw ReactError( + "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." + ); return c; } function pushHostContainer(fiber, nextRootInstance) { @@ -3090,15 +3073,7 @@ function popHostContext(fiber) { contextFiberStackCursor.current === fiber && (pop(contextStackCursor$1, fiber), pop(contextFiberStackCursor, fiber)); } -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 = 0, currentlyRenderingFiber$1 = null, currentHook = null, @@ -3113,9 +3088,8 @@ var NoEffect$1 = 0, renderPhaseUpdates = null, numberOfReRenders = 0; function throwInvalidHookError() { - invariant( - !1, - "Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)" + throw ReactError( + "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) { @@ -3163,10 +3137,10 @@ function renderWithHooks( remainingExpirationTime = 0; componentUpdateQueue = null; sideEffectTag = 0; - invariant( - !current, - "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - ); + if (current) + throw ReactError( + "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." + ); return workInProgress; } function resetHooks() { @@ -3200,10 +3174,8 @@ function updateWorkInProgressHook() { (currentHook = nextCurrentHook), (nextCurrentHook = null !== currentHook ? currentHook.next : null); else { - invariant( - null !== nextCurrentHook, - "Rendered more hooks than during the previous render." - ); + if (null === nextCurrentHook) + throw ReactError("Rendered more hooks than during the previous render."); currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, @@ -3226,10 +3198,11 @@ function basicStateReducer(state, action) { function updateReducer(reducer) { var hook = updateWorkInProgressHook(), queue = hook.queue; - invariant( - null !== queue, - "Should have a queue. This is likely a bug in React. Please file an issue." - ); + if (null === queue) + throw ReactError( + "Should have a queue. This is likely a bug in React. Please file an issue." + ); + queue.lastRenderedReducer = reducer; if (0 < numberOfReRenders) { var _dispatch = queue.dispatch; if (null !== renderPhaseUpdates) { @@ -3244,8 +3217,7 @@ function updateReducer(reducer) { is(newState, hook.memoizedState) || (didReceiveUpdate = !0); hook.memoizedState = newState; hook.baseUpdate === queue.last && (hook.baseState = newState); - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; return [newState, _dispatch]; } } @@ -3271,10 +3243,12 @@ function updateReducer(reducer) { (firstRenderPhaseUpdate = newState)), updateExpirationTime > remainingExpirationTime && (remainingExpirationTime = updateExpirationTime)) - : (newState = + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (newState = _update.eagerReducer === reducer ? _update.eagerState - : reducer(newState, _update.action)); + : reducer(newState, _update.action))); baseUpdate = _update; _update = _update.next; } while (null !== _update && _update !== _dispatch); @@ -3284,8 +3258,7 @@ function updateReducer(reducer) { hook.memoizedState = newState; hook.baseUpdate = newBaseUpdate; hook.baseState = firstRenderPhaseUpdate; - queue.eagerReducer = reducer; - queue.eagerState = newState; + queue.lastRenderedState = newState; } return [hook.memoizedState, queue.dispatch]; } @@ -3321,7 +3294,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; } } @@ -3348,10 +3321,10 @@ function imperativeHandleEffect(create, ref) { } function mountDebugValue() {} function dispatchAction(fiber, queue, action) { - invariant( - 25 > numberOfReRenders, - "Too many re-renders. React limits the number of renders to prevent an infinite loop." - ); + if (!(25 > numberOfReRenders)) + throw ReactError( + "Too many re-renders. React limits the number of renders to prevent an infinite loop." + ); var alternate = fiber.alternate; if ( fiber === currentlyRenderingFiber$1 || @@ -3376,9 +3349,9 @@ function dispatchAction(fiber, queue, action) { queue.next = fiber; } else { - flushPassiveEffects(); - var currentTime = requestCurrentTime(); - currentTime = computeExpirationForFiber(currentTime, fiber); + flushPassiveEffects$$1(); + var currentTime = requestCurrentTime$$1(); + currentTime = computeExpirationForFiber$$1(currentTime, fiber); var _update2 = { expirationTime: currentTime, action: action, @@ -3397,10 +3370,10 @@ function dispatchAction(fiber, queue, action) { if ( 0 === fiber.expirationTime && (null === alternate || 0 === alternate.expirationTime) && - ((alternate = queue.eagerReducer), null !== alternate) + ((alternate = queue.lastRenderedReducer), null !== alternate) ) try { - var currentState = queue.eagerState, + var currentState = queue.lastRenderedState, _eagerState = alternate(currentState, action); _update2.eagerReducer = alternate; _update2.eagerState = _eagerState; @@ -3408,7 +3381,7 @@ function dispatchAction(fiber, queue, action) { } catch (error) { } finally { } - scheduleWork(fiber, currentTime); + scheduleWork$$1(fiber, currentTime); } } var ContextOnlyDispatcher = { @@ -3435,19 +3408,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(); @@ -3463,8 +3436,8 @@ var ContextOnlyDispatcher = { reducer = hook.queue = { last: null, dispatch: null, - eagerReducer: reducer, - eagerState: initialArg + lastRenderedReducer: reducer, + lastRenderedState: initialArg }; reducer = reducer.dispatch = dispatchAction.bind( null, @@ -3485,8 +3458,8 @@ var ContextOnlyDispatcher = { initialState = hook.queue = { last: null, dispatch: null, - eagerReducer: basicStateReducer, - eagerState: initialState + lastRenderedReducer: basicStateReducer, + lastRenderedState: initialState }; initialState = initialState.dispatch = dispatchAction.bind( null, @@ -3514,19 +3487,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(); @@ -3551,11 +3524,12 @@ var ContextOnlyDispatcher = { }, useDebugValue: mountDebugValue }, + now$2 = Scheduler.unstable_now, commitTime = 0, profilerStartTime = -1; function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (0 <= profilerStartTime) { - var elapsedTime = now$1() - profilerStartTime; + var elapsedTime = now$2() - profilerStartTime; fiber.actualDuration += elapsedTime; overrideBaseTime && (fiber.selfBaseDuration = elapsedTime); profilerStartTime = -1; @@ -4116,7 +4090,10 @@ function updateSuspenseComponent( nextState = null; var nextDidTimeout = !1; } else - (nextState = { timedOutAt: null !== nextState ? nextState.timedOutAt : 0 }), + (nextState = { + fallbackExpirationTime: + null !== nextState ? nextState.fallbackExpirationTime : 0 + }), (nextDidTimeout = !0), (workInProgress.effectTag &= -65); if (null === current$$1) @@ -4246,10 +4223,8 @@ function bailoutOnAlreadyFinishedWork( (workInProgress.contextDependencies = current$$1.contextDependencies); profilerStartTime = -1; if (workInProgress.childExpirationTime < renderExpirationTime) return null; - invariant( - null === current$$1 || workInProgress.child === current$$1.child, - "Resuming work not yet implemented." - ); + if (null !== current$$1 && workInProgress.child !== current$$1.child) + throw ReactError("Resuming work not yet implemented."); if (null !== workInProgress.child) { current$$1 = workInProgress.child; renderExpirationTime = createWorkInProgress( @@ -4417,59 +4392,57 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ((current$$1.alternate = null), (workInProgress.alternate = null), (workInProgress.effectTag |= 2)); - hasContext = workInProgress.pendingProps; - current$$1 = readLazyComponentType(context); - workInProgress.type = current$$1; - context = workInProgress.tag = resolveLazyComponentTag(current$$1); - hasContext = resolveDefaultProps(current$$1, hasContext); - getDerivedStateFromProps = void 0; - switch (context) { + current$$1 = workInProgress.pendingProps; + context = readLazyComponentType(context); + workInProgress.type = context; + hasContext = workInProgress.tag = resolveLazyComponentTag(context); + current$$1 = resolveDefaultProps(context, current$$1); + switch (hasContext) { case 0: - getDerivedStateFromProps = updateFunctionComponent( + workInProgress = updateFunctionComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 1: - getDerivedStateFromProps = updateClassComponent( + workInProgress = updateClassComponent( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 11: - getDerivedStateFromProps = updateForwardRef( + workInProgress = updateForwardRef( null, workInProgress, + context, current$$1, - hasContext, renderExpirationTime ); break; case 14: - getDerivedStateFromProps = updateMemoComponent( + workInProgress = updateMemoComponent( null, workInProgress, - current$$1, - resolveDefaultProps(current$$1.type, hasContext), + context, + resolveDefaultProps(context.type, current$$1), updateExpirationTime, renderExpirationTime ); break; default: - invariant( - !1, - "Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s", - current$$1, - "" + throw ReactError( + "Element type is invalid. Received a promise that resolves to: " + + context + + ". Lazy element type must resolve to a class or function." ); } - return getDerivedStateFromProps; + return workInProgress; case 0: return ( (updateExpirationTime = workInProgress.type), @@ -4503,38 +4476,36 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); case 3: - return ( - pushHostRootContext(workInProgress), - (updateExpirationTime = workInProgress.updateQueue), - invariant( - null !== updateExpirationTime, + pushHostRootContext(workInProgress); + updateExpirationTime = workInProgress.updateQueue; + if (null === updateExpirationTime) + throw ReactError( "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." - ), - (context = workInProgress.memoizedState), - (context = null !== context ? context.element : null), - processUpdateQueue( - workInProgress, - updateExpirationTime, - workInProgress.pendingProps, - null, - renderExpirationTime - ), - (updateExpirationTime = workInProgress.memoizedState.element), - updateExpirationTime === context - ? (workInProgress = bailoutOnAlreadyFinishedWork( - current$$1, - workInProgress, - renderExpirationTime - )) - : (reconcileChildren( - current$$1, - workInProgress, - updateExpirationTime, - renderExpirationTime - ), - (workInProgress = workInProgress.child)), - workInProgress + ); + context = workInProgress.memoizedState; + context = null !== context ? context.element : null; + processUpdateQueue( + workInProgress, + updateExpirationTime, + workInProgress.pendingProps, + null, + renderExpirationTime ); + updateExpirationTime = workInProgress.memoizedState.element; + updateExpirationTime === context + ? (workInProgress = bailoutOnAlreadyFinishedWork( + current$$1, + workInProgress, + renderExpirationTime + )) + : (reconcileChildren( + current$$1, + workInProgress, + updateExpirationTime, + renderExpirationTime + ), + (workInProgress = workInProgress.child)); + return workInProgress; case 5: return ( pushHostContext(workInProgress), @@ -4547,8 +4518,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { updateExpirationTime, renderExpirationTime ), - (workInProgress = workInProgress.child), - workInProgress + workInProgress.child ); case 6: return ( @@ -4827,8 +4797,7 @@ function beginWork(current$$1, workInProgress, renderExpirationTime) { ) ); } - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -4864,17 +4833,17 @@ function readContext(context, observedBits) { if ("number" !== typeof observedBits || 1073741823 === observedBits) (lastContextWithAllBitsObserved = context), (observedBits = 1073741823); observedBits = { context: context, observedBits: observedBits, next: null }; - null === lastContextDependency - ? (invariant( - null !== currentlyRenderingFiber, + if (null === lastContextDependency) { + if (null === currentlyRenderingFiber) + throw ReactError( "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.contextDependencies = { - first: observedBits, - expirationTime: 0 - })) - : (lastContextDependency = lastContextDependency.next = observedBits); + ); + lastContextDependency = observedBits; + currentlyRenderingFiber.contextDependencies = { + first: observedBits, + expirationTime: 0 + }; + } else lastContextDependency = lastContextDependency.next = observedBits; } return context._currentValue; } @@ -5027,7 +4996,9 @@ function processUpdateQueue( ((newFirstUpdate = update), (newBaseState = resultState)), newExpirationTime < updateExpirationTime && (newExpirationTime = updateExpirationTime)) - : ((resultState = getStateFromUpdate( + : (updateExpirationTime < mostRecentEventTime && + (mostRecentEventTime = updateExpirationTime), + (resultState = getStateFromUpdate( workInProgress, queue, update, @@ -5100,11 +5071,11 @@ function commitUpdateEffects(effect, instance) { if (null !== _callback3) { effect.callback = null; var context = instance; - invariant( - "function" === typeof _callback3, - "Invalid argument passed as callback. Expected a function. Instead received: %s", - _callback3 - ); + if ("function" !== typeof _callback3) + throw ReactError( + "Invalid argument passed as callback. Expected a function. Instead received: " + + _callback3 + ); _callback3.call(context); } effect = effect.nextEffect; @@ -5204,22 +5175,56 @@ function safelyDetachRef(current$$1) { try { ref(null); } catch (refError) { - captureCommitPhaseError(current$$1, refError); + captureCommitPhaseError$$1(current$$1, refError); } 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: + case 20: + break; + default: + throw ReactError( + "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); @@ -5304,7 +5309,7 @@ function commitUnmount(current$$1$jscomp$0) { try { destroy(); } catch (error) { - captureCommitPhaseError(current$$1, error); + captureCommitPhaseError$$1(current$$1, error); } } effect = effect.next; @@ -5320,7 +5325,7 @@ function commitUnmount(current$$1$jscomp$0) { (updateQueue.state = current$$1$jscomp$0.memoizedState), updateQueue.componentWillUnmount(); } catch (unmountError) { - captureCommitPhaseError(current$$1$jscomp$0, unmountError); + captureCommitPhaseError$$1(current$$1$jscomp$0, unmountError); } break; case 5: @@ -5342,17 +5347,14 @@ function commitPlacement(finishedWork) { } parent = parent.return; } - invariant( - !1, + throw ReactError( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." ); - parentFiber = void 0; } - var isContainer = (parent = void 0); switch (parentFiber.tag) { case 5: parent = parentFiber.stateNode; - isContainer = !1; + var isContainer = !1; break; case 3: parent = parentFiber.stateNode.containerInfo; @@ -5363,8 +5365,7 @@ function commitPlacement(finishedWork) { isContainer = !0; break; default: - invariant( - !1, + throw ReactError( "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." ); } @@ -5395,23 +5396,23 @@ function commitPlacement(finishedWork) { } } for (var node = finishedWork; ; ) { - if (5 === node.tag || 6 === node.tag) + if (5 === node.tag || 6 === node.tag) { + var stateNode = node.stateNode; if (parentFiber) - if (isContainer) - invariant( - "number" !== typeof parent, - "Container does not support insertBefore operation" - ); - else { + if (isContainer) { + if ("number" === typeof parent) + throw ReactError( + "Container does not support insertBefore operation" + ); + } else { var parentInstance = parent, - child = node.stateNode, beforeChild = parentFiber, children = parentInstance._children, - index = children.indexOf(child); + index = children.indexOf(stateNode); 0 <= index ? (children.splice(index, 1), (beforeChild = children.indexOf(beforeChild)), - children.splice(beforeChild, 0, child), + children.splice(beforeChild, 0, stateNode), UIManager.manageChildren( parentInstance._nativeTag, [index], @@ -5421,32 +5422,33 @@ function commitPlacement(finishedWork) { [] )) : ((index = children.indexOf(beforeChild)), - children.splice(index, 0, child), + children.splice(index, 0, stateNode), UIManager.manageChildren( parentInstance._nativeTag, [], [], - ["number" === typeof child ? child : child._nativeTag], + [ + "number" === typeof stateNode + ? stateNode + : stateNode._nativeTag + ], [index], [] )); } else isContainer - ? ((parentInstance = node.stateNode), - UIManager.setChildren(parent, [ - "number" === typeof parentInstance - ? parentInstance - : parentInstance._nativeTag - ])) + ? UIManager.setChildren(parent, [ + "number" === typeof stateNode ? stateNode : stateNode._nativeTag + ]) : ((parentInstance = parent), - (child = node.stateNode), - (children = "number" === typeof child ? child : child._nativeTag), + (children = + "number" === typeof stateNode ? stateNode : stateNode._nativeTag), (index = parentInstance._children), - (beforeChild = index.indexOf(child)), + (beforeChild = index.indexOf(stateNode)), 0 <= beforeChild ? (index.splice(beforeChild, 1), - index.push(child), + index.push(stateNode), UIManager.manageChildren( parentInstance._nativeTag, [beforeChild], @@ -5455,7 +5457,7 @@ function commitPlacement(finishedWork) { [], [] )) - : (index.push(child), + : (index.push(stateNode), UIManager.manageChildren( parentInstance._nativeTag, [], @@ -5464,7 +5466,7 @@ function commitPlacement(finishedWork) { [index.length - 1], [] ))); - else if (4 !== node.tag && null !== node.child) { + } else if (4 !== node.tag && null !== node.child) { node.child.return = node; node = node.child; continue; @@ -5490,10 +5492,10 @@ function unmountHostComponents(current$$1) { if (!currentParentIsValid) { currentParentIsValid = node.return; a: for (;;) { - invariant( - null !== currentParentIsValid, - "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === currentParentIsValid) + throw ReactError( + "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." + ); switch (currentParentIsValid.tag) { case 5: currentParent = currentParentIsValid.stateNode; @@ -5572,7 +5574,7 @@ function commitWork(current$$1, finishedWork) { case 11: case 14: case 15: - commitHookEffectList(UnmountMutation, MountMutation, finishedWork); + commitHookEffectList(4, 8, finishedWork); break; case 1: break; @@ -5581,67 +5583,77 @@ function commitWork(current$$1, finishedWork) { if (null != instance) { var newProps = finishedWork.memoizedProps; current$$1 = null !== current$$1 ? current$$1.memoizedProps : newProps; - var type = finishedWork.type, - updatePayload = finishedWork.updateQueue; + var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; null !== updatePayload && - commitUpdate( - instance, - updatePayload, - type, + ((finishedWork = instance.viewConfig), + (instanceProps[instance._nativeTag] = newProps), + (newProps = diffProperties( + null, current$$1, newProps, - finishedWork - ); + finishedWork.validAttributes + )), + null != newProps && + UIManager.updateView( + instance._nativeTag, + finishedWork.uiViewClassName, + newProps + )); } break; case 6: - invariant( - null !== finishedWork.stateNode, - "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === finishedWork.stateNode) + throw ReactError( + "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." + ); UIManager.updateView(finishedWork.stateNode, "RCTRawText", { text: finishedWork.memoizedProps }); break; + case 20: + break; case 3: break; case 12: break; case 13: - instance = finishedWork.memoizedState; - newProps = void 0; - current$$1 = finishedWork; - null === instance - ? (newProps = !1) - : ((newProps = !0), - (current$$1 = finishedWork.child), - 0 === instance.timedOutAt && - (instance.timedOutAt = requestCurrentTime())); - null !== current$$1 && hideOrUnhideAllChildren(current$$1, newProps); - instance = finishedWork.updateQueue; - if (null !== instance) { - finishedWork.updateQueue = null; - var retryCache = finishedWork.stateNode; - null === retryCache && - (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); - instance.forEach(function(thenable) { - var retry = resolveRetryThenable.bind(null, finishedWork, thenable); - retry = tracing.unstable_wrap(retry); - retryCache.has(thenable) || - (retryCache.add(thenable), thenable.then(retry, retry)); - }); - } + commitSuspenseComponent(finishedWork); break; case 17: break; default: - invariant( - !1, + throw ReactError( "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, + newDidTimeout = void 0, + primaryChildParent = finishedWork; + null === newState + ? (newDidTimeout = !1) + : ((newDidTimeout = !0), + (primaryChildParent = finishedWork.child), + 0 === newState.fallbackExpirationTime && + (newState.fallbackExpirationTime = requestCurrentTime$$1() - 500)); + null !== primaryChildParent && + hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); + newState = finishedWork.updateQueue; + if (null !== newState) { + finishedWork.updateQueue = null; + var retryCache = finishedWork.stateNode; + null === retryCache && + (retryCache = finishedWork.stateNode = new PossiblyWeakSet$1()); + newState.forEach(function(thenable) { + var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable); + retry = tracing.unstable_wrap(retry); + retryCache.has(thenable) || + (retryCache.add(thenable), thenable.then(retry, retry)); + }); + } +} var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime = createUpdate(expirationTime); @@ -5649,7 +5661,7 @@ function createRootErrorUpdate(fiber, errorInfo, expirationTime) { expirationTime.payload = { element: null }; var error = errorInfo.value; expirationTime.callback = function() { - onUncaughtError(error); + onUncaughtError$$1(error); logError(fiber, errorInfo); }; return expirationTime; @@ -5697,34 +5709,13 @@ function throwException( ) { var thenable = value; value = returnFiber; - var earliestTimeoutMs = -1, - startTimeMs = -1; do { - if (13 === value.tag) { - var current$$1 = value.alternate; - if ( - null !== current$$1 && - ((current$$1 = current$$1.memoizedState), null !== current$$1) - ) { - startTimeMs = 10 * (1073741822 - current$$1.timedOutAt); - break; - } - current$$1 = value.pendingProps.maxDuration; - if ("number" === typeof current$$1) - if (0 >= current$$1) earliestTimeoutMs = 0; - else if (-1 === earliestTimeoutMs || current$$1 < earliestTimeoutMs) - earliestTimeoutMs = current$$1; - } - value = value.return; - } while (null !== value); - value = returnFiber; - do { - if ((current$$1 = 13 === value.tag)) - current$$1 = - void 0 === value.memoizedProps.fallback - ? !1 - : null === value.memoizedState; - if (current$$1) { + if ( + 13 === value.tag && + (void 0 === value.memoizedProps.fallback + ? 0 + : null === value.memoizedState) + ) { returnFiber = value.updateQueue; null === returnFiber ? ((returnFiber = new Set()), @@ -5744,40 +5735,26 @@ function throwException( return; } sourceFiber = root; - returnFiber = renderExpirationTime; + root = renderExpirationTime; var pingCache = sourceFiber.pingCache; null === pingCache ? ((pingCache = sourceFiber.pingCache = new PossiblyWeakMap()), - (current$$1 = new Set()), - pingCache.set(thenable, current$$1)) - : ((current$$1 = pingCache.get(thenable)), - void 0 === current$$1 && - ((current$$1 = new Set()), pingCache.set(thenable, current$$1))); - current$$1.has(returnFiber) || - (current$$1.add(returnFiber), - (sourceFiber = pingSuspendedRoot.bind( + (returnFiber = new Set()), + pingCache.set(thenable, returnFiber)) + : ((returnFiber = pingCache.get(thenable)), + void 0 === returnFiber && + ((returnFiber = new Set()), + pingCache.set(thenable, returnFiber))); + returnFiber.has(root) || + (returnFiber.add(root), + (sourceFiber = pingSuspendedRoot$$1.bind( null, sourceFiber, thenable, - returnFiber + root )), (sourceFiber = tracing.unstable_wrap(sourceFiber)), thenable.then(sourceFiber, sourceFiber)); - -1 === earliestTimeoutMs - ? (root = 1073741823) - : (-1 === startTimeMs && - (startTimeMs = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel( - root, - renderExpirationTime - )) - - 5e3), - (root = startTimeMs + earliestTimeoutMs)); - 0 <= root && - nextLatestAbsoluteTimeoutMs < root && - (nextLatestAbsoluteTimeoutMs = root); value.effectTag |= 2048; value.expirationTime = renderExpirationTime; return; @@ -5792,44 +5769,43 @@ function throwException( } nextRenderDidError = !0; value = createCapturedValue(value, sourceFiber); - root = returnFiber; + sourceFiber = returnFiber; do { - switch (root.tag) { + switch (sourceFiber.tag) { case 3: - root.effectTag |= 2048; - root.expirationTime = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.expirationTime = renderExpirationTime; renderExpirationTime = createRootErrorUpdate( - root, + sourceFiber, value, renderExpirationTime ); - enqueueCapturedUpdate(root, renderExpirationTime); + enqueueCapturedUpdate(sourceFiber, renderExpirationTime); return; case 1: if ( - ((earliestTimeoutMs = value), - (startTimeMs = root.type), - (sourceFiber = root.stateNode), - 0 === (root.effectTag & 64) && - ("function" === typeof startTimeMs.getDerivedStateFromError || - (null !== sourceFiber && - "function" === typeof sourceFiber.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(sourceFiber))))) + ((thenable = value), + (root = sourceFiber.type), + (returnFiber = sourceFiber.stateNode), + 0 === (sourceFiber.effectTag & 64) && + ("function" === typeof root.getDerivedStateFromError || + (null !== returnFiber && + "function" === typeof returnFiber.componentDidCatch && + !isAlreadyFailedLegacyErrorBoundary$$1(returnFiber)))) ) { - root.effectTag |= 2048; - root.expirationTime = renderExpirationTime; + sourceFiber.effectTag |= 2048; + sourceFiber.expirationTime = renderExpirationTime; renderExpirationTime = createClassErrorUpdate( - root, - earliestTimeoutMs, + sourceFiber, + thenable, renderExpirationTime ); - enqueueCapturedUpdate(root, renderExpirationTime); + enqueueCapturedUpdate(sourceFiber, renderExpirationTime); return; } } - root = root.return; - } while (null !== root); + sourceFiber = sourceFiber.return; + } while (null !== sourceFiber); } function unwindWork(workInProgress) { switch (workInProgress.tag) { @@ -5841,17 +5817,15 @@ function unwindWork(workInProgress) { workInProgress) : null; case 3: - return ( - popHostContainer(workInProgress), - popTopLevelContextObject(workInProgress), - (effectTag = workInProgress.effectTag), - invariant( - 0 === (effectTag & 64), + popHostContainer(workInProgress); + popTopLevelContextObject(workInProgress); + effectTag = workInProgress.effectTag; + if (0 !== (effectTag & 64)) + throw ReactError( "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 - ); + ); + workInProgress.effectTag = (effectTag & -2049) | 64; + return workInProgress; case 5: return popHostContext(workInProgress), null; case 13: @@ -5868,22 +5842,34 @@ function unwindWork(workInProgress) { return popHostContainer(workInProgress), null; case 10: return popProvider(workInProgress), null; + case 19: + case 20: + return null; default: return null; } } -var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, +var scheduleCallback$1 = Scheduler.unstable_scheduleCallback, + cancelCallback$1 = Scheduler.unstable_cancelCallback, + shouldYield$1 = Scheduler.unstable_shouldYield, + now$1 = Scheduler.unstable_now, + getCurrentPriorityLevel$1 = Scheduler.unstable_getCurrentPriorityLevel, + NormalPriority$1 = Scheduler.unstable_NormalPriority, + ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; -invariant( - null != tracing.__interactionsRef && - null != tracing.__interactionsRef.current, - "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 ( + null == tracing.__interactionsRef || + null == tracing.__interactionsRef.current +) + throw ReactError( + "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 isWorking = !1, nextUnitOfWork = null, nextRoot = null, nextRenderExpirationTime = 0, - nextLatestAbsoluteTimeoutMs = -1, + mostRecentEventTime = 1073741823, + nextRenderDidSuspend = !1, nextRenderDidError = !1, nextEffect = null, isCommitting$1 = !1, @@ -5924,8 +5910,8 @@ function resetStack() { } nextRoot = null; nextRenderExpirationTime = 0; - nextLatestAbsoluteTimeoutMs = -1; - nextRenderDidError = !1; + mostRecentEventTime = 1073741823; + nextRenderDidError = nextRenderDidSuspend = !1; nextUnitOfWork = null; } function commitAllHostEffects() { @@ -5970,48 +5956,6 @@ function commitAllHostEffects() { nextEffect = nextEffect.nextEffect; } } -function commitBeforeMutationLifecycles() { - for (; null !== nextEffect; ) { - if (nextEffect.effectTag & 256) - a: { - var current$$1 = nextEffect.alternate, - finishedWork = nextEffect; - switch (finishedWork.tag) { - case 0: - case 11: - case 15: - commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); - break a; - 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 a; - case 3: - case 5: - case 6: - case 4: - case 17: - break a; - default: - invariant( - !1, - "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; - } -} function commitAllLifeCycles( finishedRoot$jscomp$0, committedExpirationTime$jscomp$0 @@ -6027,7 +5971,7 @@ function commitAllLifeCycles( case 0: case 11: case 15: - commitHookEffectList(UnmountLayout, MountLayout, finishedWork); + commitHookEffectList(16, 32, finishedWork); break; case 1: finishedRoot = finishedWork.stateNode; @@ -6095,12 +6039,11 @@ function commitAllLifeCycles( ); break; case 13: - break; case 17: + case 20: break; default: - invariant( - !1, + throw ReactError( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." ); } @@ -6126,39 +6069,44 @@ function commitPassiveEffects(root, firstEffect) { error = void 0; try { var finishedWork = firstEffect; - commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork); - commitHookEffectList(NoEffect$1, MountPassive, finishedWork); + commitHookEffectList(128, 0, finishedWork); + commitHookEffectList(0, 64, finishedWork); } catch (e) { (didError = !0), (error = e); } - didError && captureCommitPhaseError(firstEffect, error); + didError && captureCommitPhaseError$1(firstEffect, error); } firstEffect = firstEffect.nextEffect; } while (null !== firstEffect); isRendering = previousIsRendering; previousIsRendering = root.expirationTime; 0 !== previousIsRendering && requestWork(root, previousIsRendering); - isBatchingUpdates || isRendering || performWork(1073741823, !1); + isBatchingUpdates || isRendering || performWork(1073741823); } -function flushPassiveEffects() { - if (null !== passiveEffectCallbackHandle) { - var callbackID = passiveEffectCallbackHandle; - scheduledCallback = null; - clearTimeout(callbackID); - } +function isAlreadyFailedLegacyErrorBoundary$1(instance) { + return ( + null !== legacyErrorBoundariesThatAlreadyFailed && + legacyErrorBoundariesThatAlreadyFailed.has(instance) + ); +} +function flushPassiveEffects$1() { + var didFlushEffects = null !== passiveEffectCallback; + null !== passiveEffectCallbackHandle && + cancelCallback$1(passiveEffectCallbackHandle); null !== passiveEffectCallback && passiveEffectCallback(); + return didFlushEffects; } function commitRoot(root, finishedWork) { isCommitting$1 = isWorking = !0; - invariant( - root.current !== finishedWork, - "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." - ); + if (root.current === finishedWork) + throw ReactError( + "Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue." + ); var committedExpirationTime = root.pendingCommitExpirationTime; - invariant( - 0 !== committedExpirationTime, - "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." - ); + if (0 === committedExpirationTime) + throw ReactError( + "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." + ); root.pendingCommitExpirationTime = 0; var updateExpirationTimeBeforeCommit = finishedWork.expirationTime, childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; @@ -6183,19 +6131,23 @@ function commitRoot(root, finishedWork) { var didError = !1, error$jscomp$0 = void 0; try { - commitBeforeMutationLifecycles(); + for (; null !== nextEffect; ) + nextEffect.effectTag & 256 && + commitBeforeMutationLifeCycles(nextEffect.alternate, nextEffect), + (nextEffect = nextEffect.nextEffect); } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } - commitTime = now$1(); + commitTime = now$2(); for (nextEffect = childExpirationTimeBeforeCommit; null !== nextEffect; ) { didError = !1; error$jscomp$0 = void 0; @@ -6204,13 +6156,14 @@ function commitRoot(root, finishedWork) { } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } root.current = finishedWork; for (nextEffect = childExpirationTimeBeforeCommit; null !== nextEffect; ) { @@ -6221,32 +6174,30 @@ function commitRoot(root, finishedWork) { } catch (e) { (didError = !0), (error$jscomp$0 = e); } - didError && - (invariant( - null !== nextEffect, - "Should have next effect. This error is likely caused by a bug in React. Please file an issue." - ), - captureCommitPhaseError(nextEffect, error$jscomp$0), - null !== nextEffect && (nextEffect = nextEffect.nextEffect)); + if (didError) { + if (null === nextEffect) + throw ReactError( + "Should have next effect. This error is likely caused by a bug in React. Please file an issue." + ); + captureCommitPhaseError$1(nextEffect, error$jscomp$0); + null !== nextEffect && (nextEffect = nextEffect.nextEffect); + } } - if ( - null !== childExpirationTimeBeforeCommit && - null !== rootWithPendingPassiveEffects - ) { - var callback = commitPassiveEffects.bind( + null !== childExpirationTimeBeforeCommit && + null !== rootWithPendingPassiveEffects && + ((childExpirationTimeBeforeCommit = commitPassiveEffects.bind( null, root, childExpirationTimeBeforeCommit - ); - callback = tracing.unstable_wrap(callback); - passiveEffectCallbackHandle = scheduler.unstable_runWithPriority( - scheduler.unstable_NormalPriority, - function() { - return scheduleDeferredCallback$1(callback); - } - ); - passiveEffectCallback = callback; - } + )), + (childExpirationTimeBeforeCommit = tracing.unstable_wrap( + childExpirationTimeBeforeCommit + )), + (passiveEffectCallbackHandle = scheduleCallback$1( + NormalPriority$1, + childExpirationTimeBeforeCommit + )), + (passiveEffectCallback = childExpirationTimeBeforeCommit)); isWorking = isCommitting$1 = !1; "function" === typeof onCommitFiberRoot && onCommitFiberRoot(finishedWork.stateNode); @@ -6302,8 +6253,8 @@ function completeUnitOfWork(workInProgress) { nextUnitOfWork = workInProgress; if (workInProgress.mode & 4) { var fiber = workInProgress; - profilerStartTime = now$1(); - 0 > fiber.actualStartTime && (fiber.actualStartTime = now$1()); + profilerStartTime = now$2(); + 0 > fiber.actualStartTime && (fiber.actualStartTime = now$2()); } a: { var current = current$$1; @@ -6349,13 +6300,12 @@ function completeUnitOfWork(workInProgress) { current.ref !== current$$1.ref && (current$$1.effectTag |= 128); else if (fiber) { current = requiredContext(contextStackCursor$1.current); - var internalInstanceHandle = current$$1, - tag = allocateTag(), + var tag = allocateTag(), viewConfig = ReactNativeViewConfigRegistry.get(type); - invariant( - "RCTView" !== type || !current.isInAParentText, - "Nesting of within is not currently supported." - ); + if ("RCTView" === type && current.isInAParentText) + throw ReactError( + "Nesting of within is not currently supported." + ); var updatePayload = diffProperties( null, emptyObject, @@ -6369,7 +6319,7 @@ function completeUnitOfWork(workInProgress) { updatePayload ); viewConfig = new ReactNativeFiberHostComponent(tag, viewConfig); - instanceCache[tag] = internalInstanceHandle; + instanceCache[tag] = current$$1; instanceProps[tag] = fiber; appendAllChildren(viewConfig, current$$1, !1, !1); finalizeInitialChildren( @@ -6381,38 +6331,41 @@ function completeUnitOfWork(workInProgress) { ) && (current$$1.effectTag |= 4); current$$1.stateNode = viewConfig; null !== current$$1.ref && (current$$1.effectTag |= 128); - } else - invariant( - null !== current$$1.stateNode, + } else if (null === current$$1.stateNode) + throw ReactError( "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: - current && null != current$$1.stateNode - ? updateHostText$1( - current, - current$$1, - current.memoizedProps, - fiber - ) - : ("string" !== typeof fiber && - invariant( - null !== current$$1.stateNode, - "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)), - (type = requiredContext(contextStackCursor$1.current)), - (renderExpirationTime = current$$1), - invariant( - type.isInAParentText, + if (current && null != current$$1.stateNode) + updateHostText$1( + current, + current$$1, + current.memoizedProps, + fiber + ); + else { + if ("string" !== typeof fiber && null === current$$1.stateNode) + throw ReactError( + "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( "Text strings must be rendered within a component." - ), - (type = allocateTag()), - UIManager.createView(type, "RCTRawText", current, { - text: fiber - }), - (instanceCache[type] = current$$1), - (renderExpirationTime.stateNode = type)); + ); + renderExpirationTime = allocateTag(); + UIManager.createView( + renderExpirationTime, + "RCTRawText", + current, + { text: fiber } + ); + instanceCache[renderExpirationTime] = current$$1; + current$$1.stateNode = renderExpirationTime; + } break; case 11: break; @@ -6424,20 +6377,27 @@ function completeUnitOfWork(workInProgress) { break a; } fiber = null !== fiber; - renderExpirationTime = - null !== current && null !== current.memoizedState; + renderExpirationTime = !1; null !== current && - !fiber && - renderExpirationTime && - ((type = current.child.sibling), - null !== type && - ((current = current$$1.firstEffect), - null !== current - ? ((current$$1.firstEffect = type), - (type.nextEffect = current)) - : ((current$$1.firstEffect = current$$1.lastEffect = type), - (type.nextEffect = null)), - (type.effectTag = 8))); + ((type = current.memoizedState), + (renderExpirationTime = null !== type), + fiber || + null === type || + ((type = type.fallbackExpirationTime), + type < mostRecentEventTime && (mostRecentEventTime = type), + (current = current.child.sibling), + null !== current && + ((type = current$$1.firstEffect), + null !== type + ? ((current$$1.firstEffect = current), + (current.nextEffect = type)) + : ((current$$1.firstEffect = current$$1.lastEffect = current), + (current.nextEffect = null)), + (current.effectTag = 8)))); + fiber && + !renderExpirationTime && + 0 !== (current$$1.mode & 1) && + (nextRenderDidSuspend = !0); if (fiber || renderExpirationTime) current$$1.effectTag |= 4; break; case 7: @@ -6462,9 +6422,12 @@ function completeUnitOfWork(workInProgress) { break; case 18: break; + case 19: + break; + case 20: + break; default: - invariant( - !1, + throw ReactError( "Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue." ); } @@ -6479,37 +6442,28 @@ function completeUnitOfWork(workInProgress) { ) { fiber = 0; if (current$$1.mode & 4) { - renderExpirationTime = current$$1.actualDuration; - type = current$$1.selfBaseDuration; - current = + current = current$$1.actualDuration; + renderExpirationTime = current$$1.selfBaseDuration; + type = null === current$$1.alternate || current$$1.child !== current$$1.alternate.child; - for ( - internalInstanceHandle = current$$1.child; - null !== internalInstanceHandle; - - ) - (tag = internalInstanceHandle.expirationTime), - (viewConfig = internalInstanceHandle.childExpirationTime), - tag > fiber && (fiber = tag), + for (tag = current$$1.child; null !== tag; ) + (viewConfig = tag.expirationTime), + (updatePayload = tag.childExpirationTime), viewConfig > fiber && (fiber = viewConfig), - current && - (renderExpirationTime += internalInstanceHandle.actualDuration), - (type += internalInstanceHandle.treeBaseDuration), - (internalInstanceHandle = internalInstanceHandle.sibling); - current$$1.actualDuration = renderExpirationTime; - current$$1.treeBaseDuration = type; + updatePayload > fiber && (fiber = updatePayload), + type && (current += tag.actualDuration), + (renderExpirationTime += tag.treeBaseDuration), + (tag = tag.sibling); + current$$1.actualDuration = current; + current$$1.treeBaseDuration = renderExpirationTime; } else - for ( - renderExpirationTime = current$$1.child; - null !== renderExpirationTime; - - ) - (type = renderExpirationTime.expirationTime), - (current = renderExpirationTime.childExpirationTime), + for (current = current$$1.child; null !== current; ) + (renderExpirationTime = current.expirationTime), + (type = current.childExpirationTime), + renderExpirationTime > fiber && (fiber = renderExpirationTime), type > fiber && (fiber = type), - current > fiber && (fiber = current), - (renderExpirationTime = renderExpirationTime.sibling); + (current = current.sibling); current$$1.childExpirationTime = fiber; } if (null !== nextUnitOfWork) return nextUnitOfWork; @@ -6550,9 +6504,9 @@ function completeUnitOfWork(workInProgress) { function performUnitOfWork(workInProgress) { var current$$1 = workInProgress.alternate; workInProgress.mode & 4 && - ((profilerStartTime = now$1()), + ((profilerStartTime = now$2()), 0 > workInProgress.actualStartTime && - (workInProgress.actualStartTime = now$1())); + (workInProgress.actualStartTime = now$2())); current$$1 = beginWork(current$$1, workInProgress, nextRenderExpirationTime); workInProgress.memoizedProps = workInProgress.pendingProps; workInProgress.mode & 4 && @@ -6562,11 +6516,11 @@ function performUnitOfWork(workInProgress) { return current$$1; } function renderRoot(root, isYieldy) { - invariant( - !isWorking, - "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); - flushPassiveEffects(); + if (isWorking) + throw ReactError( + "renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); + flushPassiveEffects$1(); isWorking = !0; var previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = ContextOnlyDispatcher; @@ -6616,7 +6570,7 @@ function renderRoot(root, isYieldy) { do { try { if (isYieldy) - for (; null !== nextUnitOfWork && !(frameDeadline <= now$1()); ) + for (; null !== nextUnitOfWork && !shouldYield$1(); ) nextUnitOfWork = performUnitOfWork(nextUnitOfWork); else for (; null !== nextUnitOfWork; ) @@ -6627,17 +6581,18 @@ function renderRoot(root, isYieldy) { resetHooks(), null === nextUnitOfWork) ) - (threadID = !0), onUncaughtError(thrownValue); + (threadID = !0), onUncaughtError$1(thrownValue); else { nextUnitOfWork.mode & 4 && stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, !0); - invariant( - null !== nextUnitOfWork, - "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." - ); + if (null === nextUnitOfWork) + throw ReactError( + "Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it." + ); var sourceFiber = nextUnitOfWork, returnFiber = sourceFiber.return; - if (null === returnFiber) (threadID = !0), onUncaughtError(thrownValue); + if (null === returnFiber) + (threadID = !0), onUncaughtError$1(thrownValue); else { throwException( root, @@ -6662,10 +6617,10 @@ function renderRoot(root, isYieldy) { else if (null !== nextUnitOfWork) root.finishedWork = null; else { previousDispatcher = root.current.alternate; - invariant( - null !== previousDispatcher, - "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousDispatcher) + throw ReactError( + "Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue." + ); nextRoot = null; if (nextRenderDidError) { if (hasLowerPriorityWork(root, expirationTime)) { @@ -6687,16 +6642,11 @@ function renderRoot(root, isYieldy) { return; } } - isYieldy && -1 !== nextLatestAbsoluteTimeoutMs + isYieldy && nextRenderDidSuspend && 1073741823 !== mostRecentEventTime ? (markSuspendedPriorityLevel(root, expirationTime), (isYieldy = - 10 * - (1073741822 - - findEarliestOutstandingPriorityLevel(root, expirationTime))), - isYieldy < nextLatestAbsoluteTimeoutMs && - (nextLatestAbsoluteTimeoutMs = isYieldy), - (isYieldy = 10 * (1073741822 - requestCurrentTime())), - (isYieldy = nextLatestAbsoluteTimeoutMs - isYieldy), + 10 * (1073741822 - mostRecentEventTime) - 5e3 + originalStartTimeMs), + (isYieldy = 150 - (now$1() - isYieldy)), onSuspend( root, previousDispatcher, @@ -6707,7 +6657,7 @@ function renderRoot(root, isYieldy) { : onComplete(root, previousDispatcher, expirationTime); } } -function captureCommitPhaseError(sourceFiber, value) { +function captureCommitPhaseError$1(sourceFiber, value) { for (var fiber = sourceFiber.return; null !== fiber; ) { switch (fiber.tag) { case 1: @@ -6715,13 +6665,12 @@ function captureCommitPhaseError(sourceFiber, value) { if ( "function" === typeof fiber.type.getDerivedStateFromError || ("function" === typeof instance.componentDidCatch && - (null === legacyErrorBoundariesThatAlreadyFailed || - !legacyErrorBoundariesThatAlreadyFailed.has(instance))) + !isAlreadyFailedLegacyErrorBoundary$1(instance)) ) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createClassErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } break; @@ -6729,7 +6678,7 @@ function captureCommitPhaseError(sourceFiber, value) { sourceFiber = createCapturedValue(value, sourceFiber); sourceFiber = createRootErrorUpdate(fiber, sourceFiber, 1073741823); enqueueUpdate(fiber, sourceFiber); - scheduleWork(fiber, 1073741823); + scheduleWork$1(fiber, 1073741823); return; } fiber = fiber.return; @@ -6738,75 +6687,25 @@ function captureCommitPhaseError(sourceFiber, value) { ((fiber = createCapturedValue(value, sourceFiber)), (fiber = createRootErrorUpdate(sourceFiber, fiber, 1073741823)), enqueueUpdate(sourceFiber, fiber), - scheduleWork(sourceFiber, 1073741823)); + scheduleWork$1(sourceFiber, 1073741823)); } -function computeExpirationForFiber(currentTime, fiber) { - var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(), - expirationTime = void 0; - if (0 === (fiber.mode & 1)) expirationTime = 1073741823; - else if (isWorking && !isCommitting$1) - expirationTime = nextRenderExpirationTime; - else { - switch (priorityLevel) { - case scheduler.unstable_ImmediatePriority: - expirationTime = 1073741823; - break; - case scheduler.unstable_UserBlockingPriority: - expirationTime = - 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1); - break; - case scheduler.unstable_NormalPriority: - expirationTime = - 1073741822 - 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1); - break; - case scheduler.unstable_LowPriority: - case scheduler.unstable_IdlePriority: - expirationTime = 1; - break; - default: - invariant( - !1, - "Unknown priority level. This error is likely caused by a bug in React. Please file an issue." - ); - } - null !== nextRoot && - expirationTime === nextRenderExpirationTime && - --expirationTime; - } - priorityLevel === scheduler.unstable_UserBlockingPriority && +function computeExpirationForFiber$1(currentTime, fiber) { + isWorking + ? (currentTime = isCommitting$1 ? 1073741823 : nextRenderExpirationTime) + : fiber.mode & 1 + ? ((currentTime = isBatchingInteractiveUpdates + ? 1073741822 - 10 * ((((1073741822 - currentTime + 15) / 10) | 0) + 1) + : 1073741822 - + 25 * ((((1073741822 - currentTime + 500) / 25) | 0) + 1)), + null !== nextRoot && + currentTime === nextRenderExpirationTime && + --currentTime) + : (currentTime = 1073741823); + isBatchingInteractiveUpdates && (0 === lowestPriorityPendingInteractiveExpirationTime || - expirationTime < lowestPriorityPendingInteractiveExpirationTime) && - (lowestPriorityPendingInteractiveExpirationTime = expirationTime); - return expirationTime; -} -function pingSuspendedRoot(root, thenable, pingTime) { - var pingCache = root.pingCache; - null !== pingCache && pingCache.delete(thenable); - if (null !== nextRoot && nextRenderExpirationTime === pingTime) - nextRoot = null; - else if ( - ((thenable = root.earliestSuspendedTime), - (pingCache = root.latestSuspendedTime), - 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) - ) { - root.didError = !1; - thenable = root.latestPingedTime; - if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; - findNextExpirationTimeToWorkOn(pingTime, root); - pingTime = root.expirationTime; - 0 !== pingTime && requestWork(root, pingTime); - } -} -function resolveRetryThenable(boundaryFiber, thenable) { - var retryCache = boundaryFiber.stateNode; - null !== retryCache && retryCache.delete(thenable); - thenable = requestCurrentTime(); - thenable = computeExpirationForFiber(thenable, boundaryFiber); - boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); - null !== boundaryFiber && - (markPendingPriorityLevel(boundaryFiber, thenable), - (thenable = boundaryFiber.expirationTime), - 0 !== thenable && requestWork(boundaryFiber, thenable)); + currentTime < lowestPriorityPendingInteractiveExpirationTime) && + (lowestPriorityPendingInteractiveExpirationTime = currentTime); + return currentTime; } function scheduleWorkToRoot(fiber, expirationTime) { fiber.expirationTime < expirationTime && @@ -6856,9 +6755,10 @@ function scheduleWorkToRoot(fiber, expirationTime) { } return root; } -function scheduleWork(fiber, expirationTime) { +function scheduleWork$1(fiber, expirationTime) { fiber = scheduleWorkToRoot(fiber, expirationTime); - null !== fiber && + if ( + null !== fiber && (!isWorking && 0 !== nextRenderExpirationTime && expirationTime > nextRenderExpirationTime && @@ -6866,12 +6766,12 @@ function scheduleWork(fiber, expirationTime) { markPendingPriorityLevel(fiber, expirationTime), (isWorking && !isCommitting$1 && nextRoot === fiber) || requestWork(fiber, fiber.expirationTime), - nestedUpdateCount > NESTED_UPDATE_LIMIT && - ((nestedUpdateCount = 0), - invariant( - !1, - "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." - ))); + nestedUpdateCount > NESTED_UPDATE_LIMIT) + ) + throw ((nestedUpdateCount = 0), + ReactError( + "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." + )); } var firstScheduledRoot = null, lastScheduledRoot = null, @@ -6885,6 +6785,7 @@ var firstScheduledRoot = null, unhandledError = null, isBatchingUpdates = !1, isUnbatchingUpdates = !1, + isBatchingInteractiveUpdates = !1, completedBatches = null, originalStartTimeMs = now$1(), currentRendererTime = 1073741822 - ((originalStartTimeMs / 10) | 0), @@ -6899,13 +6800,14 @@ function recomputeCurrentRendererTime() { function scheduleCallbackWithExpirationTime(root, expirationTime) { if (0 !== callbackExpirationTime) { if (expirationTime < callbackExpirationTime) return; - null !== callbackID && - ((root = callbackID), (scheduledCallback = null), clearTimeout(root)); + null !== callbackID && cancelCallback$1(callbackID); } callbackExpirationTime = expirationTime; root = now$1() - originalStartTimeMs; - callbackID = scheduleDeferredCallback$1(performAsyncWork, { - timeout: 10 * (1073741822 - expirationTime) - root + expirationTime = 10 * (1073741822 - expirationTime) - root; + root = getCurrentPriorityLevel$1(); + callbackID = scheduleCallback$1(root, performAsyncWork, { + timeout: expirationTime }); } function onComplete(root, finishedWork, expirationTime) { @@ -6920,7 +6822,7 @@ function onSuspend( msUntilTimeout ) { root.expirationTime = rootExpirationTime; - 0 !== msUntilTimeout || frameDeadline <= now$1() + 0 !== msUntilTimeout || shouldYield$1() ? 0 < msUntilTimeout && (root.timeoutHandle = scheduleTimeout( onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), @@ -6934,20 +6836,20 @@ function onTimeout(root, finishedWork, suspendedExpirationTime) { root.finishedWork = finishedWork; recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; - invariant( - !isRendering, - "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." - ); + if (isRendering) + throw ReactError( + "work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method." + ); nextFlushedRoot = root; nextFlushedExpirationTime = suspendedExpirationTime; performWorkOnRoot(root, suspendedExpirationTime, !1); - performWork(1073741823, !1); + performWork(1073741823); } function onCommit(root, expirationTime) { root.expirationTime = expirationTime; root.finishedWork = null; } -function requestCurrentTime() { +function requestCurrentTime$1() { if (isRendering) return currentSchedulerTime; findHighestPriorityRoot(); if (0 === nextFlushedExpirationTime || 1 === nextFlushedExpirationTime) @@ -6972,7 +6874,7 @@ function requestWork(root, expirationTime) { (nextFlushedExpirationTime = 1073741823), performWorkOnRoot(root, 1073741823, !1)) : 1073741823 === expirationTime - ? performWork(1073741823, !1) + ? performWork(1073741823) : scheduleCallbackWithExpirationTime(root, expirationTime)); } function findHighestPriorityRoot() { @@ -6986,10 +6888,10 @@ function findHighestPriorityRoot() { ) { var remainingExpirationTime = root.expirationTime; if (0 === remainingExpirationTime) { - invariant( - null !== previousScheduledRoot && null !== lastScheduledRoot, - "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." - ); + if (null === previousScheduledRoot || null === lastScheduledRoot) + throw ReactError( + "Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue." + ); if (root === root.nextScheduledRoot) { firstScheduledRoot = lastScheduledRoot = root.nextScheduledRoot = null; break; @@ -7032,58 +6934,57 @@ function performAsyncWork(didTimeout) { didTimeout = didTimeout.nextScheduledRoot; } while (didTimeout !== firstScheduledRoot); } - performWork(0, !0); -} -function performWork(minExpirationTime, isYieldy) { findHighestPriorityRoot(); - if (isYieldy) - for ( + recomputeCurrentRendererTime(); + for ( + currentSchedulerTime = currentRendererTime; + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime); + + ) + performWorkOnRoot( + nextFlushedRoot, + nextFlushedExpirationTime, + currentRendererTime > nextFlushedExpirationTime + ), + findHighestPriorityRoot(), recomputeCurrentRendererTime(), - currentSchedulerTime = currentRendererTime; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime && - !( - frameDeadline <= now$1() && - currentRendererTime > nextFlushedExpirationTime - ); - - ) - performWorkOnRoot( - nextFlushedRoot, - nextFlushedExpirationTime, - currentRendererTime > nextFlushedExpirationTime - ), - findHighestPriorityRoot(), - recomputeCurrentRendererTime(), - (currentSchedulerTime = currentRendererTime); - else - for ( - ; - null !== nextFlushedRoot && - 0 !== nextFlushedExpirationTime && - minExpirationTime <= nextFlushedExpirationTime; - - ) - performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), - findHighestPriorityRoot(); - isYieldy && ((callbackExpirationTime = 0), (callbackID = null)); + (currentSchedulerTime = currentRendererTime); + callbackExpirationTime = 0; + callbackID = null; 0 !== nextFlushedExpirationTime && scheduleCallbackWithExpirationTime( nextFlushedRoot, nextFlushedExpirationTime ); + finishRendering(); +} +function performWork(minExpirationTime) { + for ( + findHighestPriorityRoot(); + null !== nextFlushedRoot && + 0 !== nextFlushedExpirationTime && + minExpirationTime <= nextFlushedExpirationTime; + + ) + performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, !1), + findHighestPriorityRoot(); + 0 !== nextFlushedExpirationTime && + scheduleCallbackWithExpirationTime( + nextFlushedRoot, + nextFlushedExpirationTime + ); + finishRendering(); +} +function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; - if (null !== completedBatches) - for ( - minExpirationTime = completedBatches, - completedBatches = null, - isYieldy = 0; - isYieldy < minExpirationTime.length; - isYieldy++ - ) { - var batch = minExpirationTime[isYieldy]; + if (null !== completedBatches) { + var batches = completedBatches; + completedBatches = null; + for (var i = 0; i < batches.length; i++) { + var batch = batches[i]; try { batch._onComplete(); } catch (error) { @@ -7091,17 +6992,18 @@ function performWork(minExpirationTime, isYieldy) { ((hasUnhandledError = !0), (unhandledError = error)); } } + } if (hasUnhandledError) - throw ((minExpirationTime = unhandledError), + throw ((batches = unhandledError), (unhandledError = null), (hasUnhandledError = !1), - minExpirationTime); + batches); } function performWorkOnRoot(root, expirationTime, isYieldy) { - invariant( - !isRendering, - "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." - ); + if (isRendering) + throw ReactError( + "performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue." + ); isRendering = !0; if (isYieldy) { var _finishedWork = root.finishedWork; @@ -7114,7 +7016,7 @@ function performWorkOnRoot(root, expirationTime, isYieldy) { renderRoot(root, isYieldy), (_finishedWork = root.finishedWork), null !== _finishedWork && - (frameDeadline <= now$1() + (shouldYield$1() ? (root.finishedWork = _finishedWork) : completeRoot(root, _finishedWork, expirationTime))); } else @@ -7149,46 +7051,81 @@ function completeRoot(root, finishedWork, expirationTime) { root === lastCommittedRootDuringThisBatch ? nestedUpdateCount++ : ((lastCommittedRootDuringThisBatch = root), (nestedUpdateCount = 0)); - scheduler.unstable_runWithPriority( - scheduler.unstable_ImmediatePriority, - function() { - commitRoot(root, finishedWork); - } - ); + commitRoot(root, finishedWork); } -function onUncaughtError(error) { - invariant( - null !== nextFlushedRoot, - "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." - ); +function onUncaughtError$1(error) { + if (null === nextFlushedRoot) + throw ReactError( + "Should be working on a root. This error is likely caused by a bug in React. Please file an issue." + ); nextFlushedRoot.expirationTime = 0; hasUnhandledError || ((hasUnhandledError = !0), (unhandledError = error)); } +Scheduler_now(); +var requestCurrentTime$$1 = requestCurrentTime$1, + computeExpirationForFiber$$1 = computeExpirationForFiber$1, + captureCommitPhaseError$$1 = captureCommitPhaseError$1, + onUncaughtError$$1 = onUncaughtError$1; +function pingSuspendedRoot$$1(root, thenable, pingTime) { + var pingCache = root.pingCache; + null !== pingCache && pingCache.delete(thenable); + if (null !== nextRoot && nextRenderExpirationTime === pingTime) + nextRoot = null; + else if ( + ((thenable = root.earliestSuspendedTime), + (pingCache = root.latestSuspendedTime), + 0 !== thenable && pingTime <= thenable && pingTime >= pingCache) + ) { + root.didError = !1; + thenable = root.latestPingedTime; + if (0 === thenable || thenable > pingTime) root.latestPingedTime = pingTime; + findNextExpirationTimeToWorkOn(pingTime, root); + pingTime = root.expirationTime; + 0 !== pingTime && requestWork(root, pingTime); + } +} +function resolveRetryThenable$$1(boundaryFiber, thenable) { + var retryCache = boundaryFiber.stateNode; + null !== retryCache && retryCache.delete(thenable); + thenable = requestCurrentTime$1(); + thenable = computeExpirationForFiber$1(thenable, boundaryFiber); + boundaryFiber = scheduleWorkToRoot(boundaryFiber, thenable); + null !== boundaryFiber && + (markPendingPriorityLevel(boundaryFiber, thenable), + (thenable = boundaryFiber.expirationTime), + 0 !== thenable && requestWork(boundaryFiber, thenable)); +} +var isAlreadyFailedLegacyErrorBoundary$$1 = isAlreadyFailedLegacyErrorBoundary$1, + scheduleWork$$1 = scheduleWork$1, + flushPassiveEffects$$1 = flushPassiveEffects$1; function findHostInstance(component) { var fiber = component._reactInternalFiber; - void 0 === fiber && - ("function" === typeof component.render - ? invariant(!1, "Unable to find node on an unmounted component.") - : invariant( - !1, - "Argument appears to not be a ReactComponent. Keys: %s", - Object.keys(component) - )); + if (void 0 === fiber) { + if ("function" === typeof component.render) + throw ReactError("Unable to find node on an unmounted component."); + throw ReactError( + "Argument appears to not be a ReactComponent. Keys: " + + Object.keys(component) + ); + } component = findCurrentHostFiber(fiber); return null === component ? null : component.stateNode; } function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current, - currentTime = requestCurrentTime(); - current$$1 = computeExpirationForFiber(currentTime, current$$1); + currentTime = requestCurrentTime$$1(); + current$$1 = computeExpirationForFiber$$1(currentTime, current$$1); currentTime = container.current; a: if (parentComponent) { parentComponent = parentComponent._reactInternalFiber; b: { - invariant( - 2 === isFiberMountedImpl(parentComponent) && 1 === parentComponent.tag, - "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." - ); + if ( + 2 !== isFiberMountedImpl(parentComponent) || + 1 !== parentComponent.tag + ) + throw ReactError( + "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 { switch (parentContext.tag) { @@ -7205,11 +7142,9 @@ function updateContainer(element, container, parentComponent, callback) { } parentContext = parentContext.return; } while (null !== parentContext); - invariant( - !1, + throw ReactError( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." ); - parentContext = void 0; } if (1 === parentComponent.tag) { var Component = parentComponent.type; @@ -7232,9 +7167,9 @@ function updateContainer(element, container, parentComponent, callback) { callback.payload = { element: element }; container = void 0 === container ? null : container; null !== container && (callback.callback = container); - flushPassiveEffects(); + flushPassiveEffects$$1(); enqueueUpdate(currentTime, callback); - scheduleWork(currentTime, current$$1); + scheduleWork$$1(currentTime, current$$1); return current$$1; } function createPortal(children, containerInfo, implementation) { @@ -7269,7 +7204,9 @@ function _inherits(subClass, superClass) { } var getInspectorDataForViewTag = void 0; getInspectorDataForViewTag = function() { - invariant(!1, "getInspectorDataForViewTag() is not available in production"); + throw ReactError( + "getInspectorDataForViewTag() is not available in production" + ); }; function findNodeHandle(componentOrHandle) { if (null == componentOrHandle) return null; @@ -7292,13 +7229,13 @@ _batchedUpdatesImpl = function(fn, a) { } finally { (isBatchingUpdates = previousIsBatchingUpdates) || isRendering || - performWork(1073741823, !1); + performWork(1073741823); } }; _flushInteractiveUpdatesImpl = function() { isRendering || 0 === lowestPriorityPendingInteractiveExpirationTime || - (performWork(lowestPriorityPendingInteractiveExpirationTime, !1), + (performWork(lowestPriorityPendingInteractiveExpirationTime), (lowestPriorityPendingInteractiveExpirationTime = 0)); }; var roots = new Map(), @@ -7326,35 +7263,67 @@ var roots = new Map(), TextInputState.focusTextInput(findNodeHandle(this)); }; ReactNativeComponent.prototype.measure = function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureInWindow = function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }; ReactNativeComponent.prototype.measureLayout = function( relativeToNativeNode, onSuccess, onFail ) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }; ReactNativeComponent.prototype.setNativeProps = function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7395,35 +7364,12 @@ var roots = new Map(), render: function(element, containerTag, callback) { var root = roots.get(containerTag); if (!root) { - root = 0; - isDevToolsPresent && (root |= 4); - root = createFiber(3, null, null, root); - var root$jscomp$0 = { - current: root, - containerInfo: containerTag, - pendingChildren: null, - earliestPendingTime: 0, - latestPendingTime: 0, - earliestSuspendedTime: 0, - latestSuspendedTime: 0, - latestPingedTime: 0, - pingCache: null, - didError: !1, - pendingCommitExpirationTime: 0, - finishedWork: null, - timeoutHandle: -1, - context: null, - pendingContext: null, - hydrate: !1, - nextExpirationTimeToWorkOn: 0, - expirationTime: 0, - firstBatch: null, - nextScheduledRoot: null, - interactionThreadID: tracing.unstable_getThreadID(), - memoizedInteractions: new Set(), - pendingInteractionMap: new Map() - }; - root = root.stateNode = root$jscomp$0; + root = new FiberRootNode(containerTag, !1); + var uninitializedFiber = 0; + isDevToolsPresent && (uninitializedFiber |= 4); + uninitializedFiber = createFiber(3, null, null, uninitializedFiber); + root.current = uninitializedFiber; + uninitializedFiber.stateNode = root; roots.set(containerTag, root); } updateContainer(element, root, null, callback); @@ -7462,31 +7408,63 @@ var roots = new Map(), NativeMethodsMixin: (function(findNodeHandle, findHostInstance) { return { measure: function(callback) { - UIManager.measure( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measure( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measure( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureInWindow: function(callback) { - UIManager.measureInWindow( - findNodeHandle(this), - mountSafeCallback_NOT_REALLY_SAFE(this, callback) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null != maybeInstance && + (maybeInstance.canonical + ? FabricUIManager.measureInWindow( + maybeInstance.node, + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + ) + : UIManager.measureInWindow( + findNodeHandle(this), + mountSafeCallback_NOT_REALLY_SAFE(this, callback) + )); }, measureLayout: function(relativeToNativeNode, onSuccess, onFail) { - UIManager.measureLayout( - findNodeHandle(this), - relativeToNativeNode, - mountSafeCallback_NOT_REALLY_SAFE(this, onFail), - mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) - ); + var maybeInstance = void 0; + try { + maybeInstance = findHostInstance(this); + } catch (error) {} + null == maybeInstance || + maybeInstance.canonical || + ((maybeInstance = void 0), + "number" === typeof relativeToNativeNode + ? (maybeInstance = relativeToNativeNode) + : relativeToNativeNode._nativeTag && + (maybeInstance = relativeToNativeNode._nativeTag), + null != maybeInstance && + UIManager.measureLayout( + findNodeHandle(this), + maybeInstance, + mountSafeCallback_NOT_REALLY_SAFE(this, onFail), + mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess) + )); }, setNativeProps: function(nativeProps) { var maybeInstance = void 0; try { maybeInstance = findHostInstance(this); } catch (error) {} - if (null != maybeInstance) { + if (null != maybeInstance && !maybeInstance.canonical) { var nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; maybeInstance = @@ -7524,7 +7502,10 @@ var roots = new Map(), var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; return injectInternals( Object.assign({}, devToolsConfig, { + overrideHookState: null, overrideProps: null, + setSuspenseHandler: null, + scheduleUpdate: null, currentDispatcherRef: ReactSharedInternals.ReactCurrentDispatcher, findHostInstanceByFiber: function(fiber) { fiber = findCurrentHostFiber(fiber); @@ -7541,7 +7522,7 @@ var roots = new Map(), findFiberByHostInstance: getInstanceFromTag, getInspectorDataForViewTag: getInspectorDataForViewTag, bundleType: 0, - version: "16.8.3", + version: "16.8.6", rendererPackageName: "react-native-renderer" }); var ReactNativeRenderer$2 = { default: ReactNativeRenderer }, diff --git a/Libraries/Renderer/shims/ReactNativeTypes.js b/Libraries/Renderer/shims/ReactNativeTypes.js index 1e145ed5e1d..3e777114db2 100644 --- a/Libraries/Renderer/shims/ReactNativeTypes.js +++ b/Libraries/Renderer/shims/ReactNativeTypes.js @@ -89,7 +89,7 @@ class ReactNativeComponent extends React.Component { measure(callback: MeasureOnSuccessCallback): void {} measureInWindow(callback: MeasureInWindowOnSuccessCallback): void {} measureLayout( - relativeToNativeNode: number, + relativeToNativeNode: number | Object, onSuccess: MeasureLayoutOnSuccessCallback, onFail?: () => void, ): void {} @@ -106,7 +106,7 @@ export type NativeMethodsMixinType = { measure(callback: MeasureOnSuccessCallback): void, measureInWindow(callback: MeasureInWindowOnSuccessCallback): void, measureLayout( - relativeToNativeNode: number, + relativeToNativeNode: number | Object, onSuccess: MeasureLayoutOnSuccessCallback, onFail: () => void, ): void, diff --git a/Libraries/Renderer/shims/ReactTypes.js b/Libraries/Renderer/shims/ReactTypes.js index f09207928ce..7b5f2d1c66c 100644 --- a/Libraries/Renderer/shims/ReactTypes.js +++ b/Libraries/Renderer/shims/ReactTypes.js @@ -13,7 +13,9 @@ export type ReactNode = | ReactText | ReactFragment | ReactProvider - | ReactConsumer; + | ReactConsumer + | ReactEventComponent + | ReactEventTarget; export type ReactEmpty = null | void | boolean; @@ -78,3 +80,93 @@ export type ReactPortal = { export type RefObject = {| current: any, |}; + +export type ReactEventResponderEventType = + | string + | {name: string, passive?: boolean, capture?: boolean}; + +export type ReactEventResponder = { + targetEventTypes: Array, + createInitialState?: (props: null | Object) => Object, + onEvent: ( + event: ReactResponderEvent, + context: ReactResponderContext, + props: null | Object, + state: null | Object, + ) => void, + onUnmount: ( + context: ReactResponderContext, + props: null | Object, + state: null | Object, + ) => void, + onOwnershipChange: ( + context: ReactResponderContext, + props: null | Object, + state: null | Object, + ) => void, +}; + +export type ReactEventComponentInstance = {| + context: null | Object, + props: null | Object, + responder: ReactEventResponder, + rootInstance: mixed, + state: null | Object, +|}; + +export type ReactEventComponent = {| + $$typeof: Symbol | number, + displayName?: string, + props: null | Object, + responder: ReactEventResponder, +|}; + +export type ReactEventTarget = {| + $$typeof: Symbol | number, + displayName?: string, + type: Symbol | number, +|}; + +type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch; + +export type ReactResponderEvent = { + nativeEvent: AnyNativeEvent, + target: Element | Document, + type: string, + passive: boolean, + passiveSupported: boolean, +}; + +export type ReactResponderDispatchEventOptions = { + capture?: boolean, + discrete?: boolean, + stopPropagation?: boolean, +}; + +export type ReactResponderContext = { + dispatchEvent: ( + eventObject: Object, + otpions: ReactResponderDispatchEventOptions, + ) => void, + isTargetWithinElement: ( + childTarget: Element | Document, + parentTarget: Element | Document, + ) => boolean, + isTargetWithinEventComponent: (Element | Document) => boolean, + isPositionWithinTouchHitTarget: ( + doc: Document, + x: number, + y: number, + ) => boolean, + addRootEventTypes: ( + document: Document, + rootEventTypes: Array, + ) => void, + removeRootEventTypes: ( + rootEventTypes: Array, + ) => void, + hasOwnership: () => boolean, + requestOwnership: () => boolean, + releaseOwnership: () => boolean, + setTimeout: (func: () => void, timeout: number) => TimeoutID, +}; diff --git a/package.json b/package.json index 43f0f1edbbb..8dd4e1b40c7 100644 --- a/package.json +++ b/package.json @@ -155,7 +155,7 @@ "test-ios-e2e": "detox test -c ios.sim.release" }, "peerDependencies": { - "react": "16.8.3" + "react": "16.8.6" }, "dependencies": { "@babel/runtime": "^7.0.0", @@ -231,10 +231,10 @@ "jest": "24.1.0", "jest-junit": "5.2.0", "jscodeshift": "^0.6.2", - "prettier": "1.13.6", - "react": "16.8.3", + "prettier": "1.16.4", + "react": "16.8.6", "react-native-dummy": "0.2.0", - "react-test-renderer": "16.8.3", + "react-test-renderer": "16.8.6", "shelljs": "^0.7.8" }, "detox": { @@ -256,4 +256,4 @@ } } } -} \ No newline at end of file +} diff --git a/yarn.lock b/yarn.lock index 523d513ec27..3acb9e5726e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6371,10 +6371,10 @@ preserve@^0.2.0: resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks= -prettier@1.13.6: - version "1.13.6" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.13.6.tgz#00ae0b777ad92f81a9e7a1df2f0470b6dab0cb44" - integrity sha512-p5eqCNiohWZN++7aJXUVj0JgLqHCPLf9GLIcLBHGNWs4Y9FJOPs6+KNO2WT0udJIQJTbeZFrJkjzjcb8fkAYYQ== +prettier@1.16.4: + version "1.16.4" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.16.4.tgz#73e37e73e018ad2db9c76742e2647e21790c9717" + integrity sha512-ZzWuos7TI5CKUeQAtFd6Zhm2s6EpAD/ZLApIhsF9pRvRtM1RFo61dM/4MSRUA0SuLugA/zgrZD8m0BaY46Og7g== pretty-format@24.0.0-alpha.6: version "24.0.0-alpha.6" @@ -6533,16 +6533,16 @@ react-devtools-core@^3.6.0: shell-quote "^1.6.1" ws "^3.3.1" -react-is@^16.8.3: - version "16.8.3" - resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.3.tgz#4ad8b029c2a718fc0cfc746c8d4e1b7221e5387d" - integrity sha512-Y4rC1ZJmsxxkkPuMLwvKvlL1Zfpbcu+Bf4ZigkHup3v9EfdYhAlWAaVyA19olXq2o2mGn0w+dFKvk3pVVlYcIA== - react-is@^16.8.4: version "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.8.6: + version "16.8.6" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" + integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== + react-native-dummy@0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/react-native-dummy/-/react-native-dummy-0.2.0.tgz#fbf0ff7607506882648f1b07f76e57951b7b8f8a" @@ -6556,15 +6556,15 @@ react-proxy@^1.1.7: lodash "^4.6.1" react-deep-force-update "^1.0.0" -react-test-renderer@16.8.3: - version "16.8.3" - resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-16.8.3.tgz#230006af264cc46aeef94392e04747c21839e05e" - integrity sha512-rjJGYebduKNZH0k1bUivVrRLX04JfIQ0FKJLPK10TAb06XWhfi4gTobooF9K/DEFNW98iGac3OSxkfIJUN9Mdg== +react-test-renderer@16.8.6: + version "16.8.6" + resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-16.8.6.tgz#188d8029b8c39c786f998aa3efd3ffe7642d5ba1" + integrity sha512-H2srzU5IWYT6cZXof6AhUcx/wEyJddQ8l7cLM/F7gDXYyPr4oq+vCIxJYXVGhId1J706sqziAjuOEjyNkfgoEw== dependencies: object-assign "^4.1.1" prop-types "^15.6.2" - react-is "^16.8.3" - scheduler "^0.13.3" + react-is "^16.8.6" + scheduler "^0.13.6" react-transform-hmr@^1.0.4: version "1.0.4" @@ -6574,15 +6574,15 @@ react-transform-hmr@^1.0.4: global "^4.3.0" react-proxy "^1.1.7" -react@16.8.3: - version "16.8.3" - resolved "https://registry.yarnpkg.com/react/-/react-16.8.3.tgz#c6f988a2ce895375de216edcfaedd6b9a76451d9" - integrity sha512-3UoSIsEq8yTJuSu0luO1QQWYbgGEILm+eJl2QN/VLDi7hL+EN18M3q3oVZwmVzzBJ3DkM7RMdRwBmZZ+b4IzSA== +react@16.8.6: + version "16.8.6" + resolved "https://registry.yarnpkg.com/react/-/react-16.8.6.tgz#ad6c3a9614fd3a4e9ef51117f54d888da01f2bbe" + integrity sha512-pC0uMkhLaHm11ZSJULfOBqV4tIZkx87ZLvbbQYunNixAAvjnC+snJCg0XQXn9VIsttVsbZP/H/ewzgsd5fxKXw== dependencies: loose-envify "^1.1.0" object-assign "^4.1.1" prop-types "^15.6.2" - scheduler "^0.13.3" + scheduler "^0.13.6" read-pkg-up@^1.0.1: version "1.0.1" @@ -7021,10 +7021,10 @@ sax@~1.1.1: resolved "https://registry.yarnpkg.com/sax/-/sax-1.1.6.tgz#5d616be8a5e607d54e114afae55b7eaf2fcc3240" integrity sha1-XWFr6KXmB9VOEUr65Vt+ry/MMkA= -scheduler@^0.13.3: - version "0.13.3" - resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.13.3.tgz#bed3c5850f62ea9c716a4d781f9daeb9b2a58896" - integrity sha512-UxN5QRYWtpR1egNWzJcVLk8jlegxAugswQc984lD3kU7NuobsO37/sRfbpTdBjtnD5TBNFA2Q2oLV5+UmPSmEQ== +scheduler@^0.13.6: + version "0.13.6" + resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.13.6.tgz#466a4ec332467b31a91b9bf74e5347072e4cd889" + integrity sha512-IWnObHt413ucAYKsD9J1QShUKkbKLQQHdxRyw73sw4FN26iWr3DY/H34xGPe4nmL1DwXyWmSWmMrA9TfQbE/XQ== dependencies: loose-envify "^1.1.0" object-assign "^4.1.1"