diff --git a/wp-includes/js/dist/vendor/react-dom.js b/wp-includes/js/dist/vendor/react-dom.js index 2bc860246f..b4eb3bf3f3 100644 --- a/wp-includes/js/dist/vendor/react-dom.js +++ b/wp-includes/js/dist/vendor/react-dom.js @@ -1,4 +1,4 @@ -/** @license React v16.13.1 +/** @license React v17.0.1 * react-dom.development.js * * Copyright (c) Facebook, Inc. and its affiliates. @@ -6,30 +6,13 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ - -'use strict'; - (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory(global.ReactDOM = {}, global.React)); }(this, (function (exports, React) { 'use strict'; - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. - // Current owner and dispatcher used to share the same ref, - // but PR #14548 split them out to better support the react-debug-tools package. - - if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { - ReactSharedInternals.ReactCurrentDispatcher = { - current: null - }; - } - - if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { - ReactSharedInternals.ReactCurrentBatchConfig = { - suspense: null - }; - } + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // by calls to these methods by a Babel plugin. // @@ -59,16 +42,12 @@ // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { - var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); - if (!hasExistingStack) { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { @@ -80,17 +59,6 @@ // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); - - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - var argIndex = 0; - var message = 'Warning: ' + format.replace(/%s/g, function () { - return args[argIndex++]; - }); - throw new Error(message); - } catch (x) {} } } @@ -100,318 +68,6 @@ } } - var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) { - var funcArgs = Array.prototype.slice.call(arguments, 3); - - try { - func.apply(context, funcArgs); - } catch (error) { - this.onError(error); - } - }; - - { - // In DEV mode, we swap out invokeGuardedCallback for a special version - // that plays more nicely with the browser's DevTools. The idea is to preserve - // "Pause on exceptions" behavior. Because React wraps all user-provided - // functions in invokeGuardedCallback, and the production version of - // invokeGuardedCallback uses a try-catch, all user exceptions are treated - // like caught exceptions, and the DevTools won't pause unless the developer - // takes the extra step of enabling pause on caught exceptions. This is - // unintuitive, though, because even though React has caught the error, from - // the developer's perspective, the error is uncaught. - // - // To preserve the expected "Pause on exceptions" behavior, we don't use a - // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake - // DOM node, and call the user-provided callback from inside an event handler - // for that fake event. If the callback throws, the error is "captured" using - // a global event handler. But because the error happens in a different - // event loop context, it does not interrupt the normal program flow. - // Effectively, this gives us try-catch behavior without actually using - // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special - // DEV version of invokeGuardedCallback - if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { - var fakeNode = document.createElement('react'); - - var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) { - // If document doesn't exist we know for sure we will crash in this method - // 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. - if (!(typeof document !== 'undefined')) { - { - throw Error( "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." ); - } - } - - var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We - // set this to true at the beginning, then set it to false right after - // calling the function. If the function errors, `didError` will never be - // set to false. This strategy works even if the browser is flaky and - // fails to call our global error handler, because it doesn't rely on - // the error event at all. - - var didError = true; // Keeps track of the value of window.event so that we can reset it - // during the callback to let user code access window.event in the - // browsers that support it. - - var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event - // dispatching: https://github.com/facebook/react/issues/13688 - - var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously - // dispatch our fake event using `dispatchEvent`. Inside the handler, we - // call the user-provided callback. - - var funcArgs = Array.prototype.slice.call(arguments, 3); - - function callCallback() { - // We immediately remove the callback from event listeners so that - // nested `invokeGuardedCallback` calls do not clash. Otherwise, a - // nested call would trigger the fake event handlers of any call higher - // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the - // window.event assignment in both IE <= 10 as they throw an error - // "Member not found" in strict mode, and in Firefox which does not - // support window.event. - - if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { - window.event = windowEvent; - } - - func.apply(context, funcArgs); - didError = false; - } // Create a global error event handler. We use this to capture the value - // that was thrown. It's possible that this error handler will fire more - // than once; for example, if non-React code also calls `dispatchEvent` - // and a handler for that event throws. We should be resilient to most of - // those cases. Even if our error event handler fires more than once, the - // last error event is always used. If the callback actually does error, - // we know that the last error event is the correct one, because it's not - // possible for anything else to have happened in between our callback - // erroring and the code that follows the `dispatchEvent` call below. If - // the callback doesn't error, but the error event was fired, we know to - // ignore it because `didError` will be false, as described above. - - - var error; // Use this to track whether the error event is ever called. - - var didSetError = false; - var isCrossOriginError = false; - - function handleWindowError(event) { - error = event.error; - didSetError = true; - - if (error === null && event.colno === 0 && event.lineno === 0) { - isCrossOriginError = true; - } - - if (event.defaultPrevented) { - // Some other error handler has prevented default. - // Browsers silence the error report if this happens. - // We'll remember this to later decide whether to log it or not. - if (error != null && typeof error === 'object') { - try { - error._suppressLogging = true; - } catch (inner) {// Ignore. - } - } - } - } // Create a fake event type. - - - var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - - window.addEventListener('error', handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function - // errors, it will trigger our global error handler. - - evt.initEvent(evtType, false, false); - fakeNode.dispatchEvent(evt); - - if (windowEventDescriptor) { - Object.defineProperty(window, 'event', windowEventDescriptor); - } - - if (didError) { - if (!didSetError) { - // The callback errored, but the error event never fired. - error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); - } else if (isCrossOriginError) { - error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); - } - - this.onError(error); - } // Remove our event listeners - - - window.removeEventListener('error', handleWindowError); - }; - - invokeGuardedCallbackImpl = invokeGuardedCallbackDev; - } - } - - var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; - - var hasError = false; - var caughtError = null; // Used by event system to capture/rethrow the first error. - - var hasRethrowError = false; - var rethrowError = null; - var reporter = { - onError: function (error) { - hasError = true; - caughtError = error; - } - }; - /** - * Call a function while guarding against errors that happens within it. - * Returns an error if it throws, otherwise null. - * - * In production, this is implemented using a try-catch. The reason we don't - * use a try-catch directly is so that we can swap out a different - * implementation in DEV mode. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { - hasError = false; - caughtError = null; - invokeGuardedCallbackImpl$1.apply(reporter, arguments); - } - /** - * Same as invokeGuardedCallback, but instead of returning an error, it stores - * it in a global so it can be rethrown by `rethrowCaughtError` later. - * TODO: See if caughtError and rethrowError can be unified. - * - * @param {String} name of the guard to use for logging or debugging - * @param {Function} func The function to invoke - * @param {*} context The context to use when calling the function - * @param {...*} args Arguments for function - */ - - function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { - invokeGuardedCallback.apply(this, arguments); - - if (hasError) { - var error = clearCaughtError(); - - if (!hasRethrowError) { - hasRethrowError = true; - rethrowError = error; - } - } - } - /** - * During execution of guarded functions we will capture the first error which - * we will rethrow to be handled by the top level error handler. - */ - - function rethrowCaughtError() { - if (hasRethrowError) { - var error = rethrowError; - hasRethrowError = false; - rethrowError = null; - throw error; - } - } - function hasCaughtError() { - return hasError; - } - function clearCaughtError() { - if (hasError) { - var error = caughtError; - hasError = false; - caughtError = null; - return error; - } else { - { - { - throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); - } - } - } - } - - var getFiberCurrentPropsFromNode = null; - var getInstanceFromNode = null; - var getNodeFromInstance = null; - function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) { - getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; - getInstanceFromNode = getInstanceFromNodeImpl; - getNodeFromInstance = getNodeFromInstanceImpl; - - { - if (!getNodeFromInstance || !getInstanceFromNode) { - error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.'); - } - } - } - var validateEventDispatches; - - { - validateEventDispatches = function (event) { - var dispatchListeners = event._dispatchListeners; - var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); - var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); - var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - - if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) { - error('EventPluginUtils: Invalid `event`.'); - } - }; - } - /** - * Dispatch the event to the listener. - * @param {SyntheticEvent} event SyntheticEvent to handle - * @param {function} listener Application-level callback - * @param {*} inst Internal component instance - */ - - - function executeDispatch(event, listener, inst) { - var type = event.type || 'unknown-event'; - event.currentTarget = getNodeFromInstance(inst); - invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); - event.currentTarget = null; - } - /** - * Standard/simple iteration through an event's collected dispatches. - */ - - function executeDispatchesInOrder(event) { - var dispatchListeners = event._dispatchListeners; - var dispatchInstances = event._dispatchInstances; - - { - validateEventDispatches(event); - } - - if (Array.isArray(dispatchListeners)) { - for (var i = 0; i < dispatchListeners.length; i++) { - if (event.isPropagationStopped()) { - break; - } // Listeners and Instances are two parallel arrays that are always in sync. - - - executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); - } - } else if (dispatchListeners) { - executeDispatch(event, dispatchListeners, dispatchInstances); - } - - event._dispatchListeners = null; - event._dispatchInstances = null; - } - var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class @@ -438,148 +94,23 @@ var FundamentalComponent = 20; var ScopeComponent = 21; var Block = 22; + var OffscreenComponent = 23; + var LegacyHiddenComponent = 24; - /** - * Injectable ordering of event plugins. - */ - var eventPluginOrder = null; - /** - * Injectable mapping from names to event plugin modules. - */ + // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. - var namesToPlugins = {}; - /** - * Recomputes the plugin list using the injected plugins and plugin ordering. - * - * @private - */ + var enableProfilerTimer = true; // Record durations for commit and passive effects phases. - function recomputePluginOrdering() { - if (!eventPluginOrder) { - // Wait until an `eventPluginOrder` is injected. - return; - } + var enableFundamentalAPI = false; // Experimental Scope support. + var enableNewReconciler = false; // Errors that are thrown while unmounting (or after in the case of passive effects) + var warnAboutStringRefs = false; - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName]; - var pluginIndex = eventPluginOrder.indexOf(pluginName); - - if (!(pluginIndex > -1)) { - { - throw Error( "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`." ); - } - } - - if (plugins[pluginIndex]) { - continue; - } - - if (!pluginModule.extractEvents) { - { - throw Error( "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not." ); - } - } - - plugins[pluginIndex] = pluginModule; - var publishedEvents = pluginModule.eventTypes; - - for (var eventName in publishedEvents) { - if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) { - { - throw Error( "EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`." ); - } - } - } - } - } - /** - * Publishes an event so that it can be dispatched by the supplied plugin. - * - * @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) { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - { - throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same event name, `" + eventName + "`." ); - } - } - - eventNameDispatchConfigs[eventName] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - - if (phasedRegistrationNames) { - for (var phaseName in phasedRegistrationNames) { - if (phasedRegistrationNames.hasOwnProperty(phaseName)) { - 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) { - if (!!registrationNameModules[registrationName]) { - { - throw Error( "EventPluginRegistry: 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(); - possibleRegistrationNames[lowerCasedName] = registrationName; - - if (registrationName === 'onDoubleClick') { - possibleRegistrationNames.ondblclick = registrationName; - } - } - } - /** - * Registers plugins so that they can extract and dispatch events. - */ - - /** - * 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 = {}; + var allNativeEvents = new Set(); /** * Mapping from registration name to event name */ + var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, @@ -590,278 +121,39 @@ var possibleRegistrationNames = {} ; // 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 - */ - - function injectEventPluginOrder(injectedEventPluginOrder) { - if (!!eventPluginOrder) { - { - throw Error( "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); - } - } // Clone the ordering so it cannot be dynamically mutated. - - - eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); - recomputePluginOrdering(); + function registerTwoPhaseEvent(registrationName, dependencies) { + registerDirectEvent(registrationName, dependencies); + registerDirectEvent(registrationName + 'Capture', dependencies); } - /** - * Injects plugins to be used by plugin event system. 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 - */ - - 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) { - if (!!namesToPlugins[pluginName]) { - { - throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`." ); - } - } - - namesToPlugins[pluginName] = pluginModule; - isOrderingDirty = true; + function registerDirectEvent(registrationName, dependencies) { + { + if (registrationNameDependencies[registrationName]) { + error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName); } } - if (isOrderingDirty) { - recomputePluginOrdering(); + registrationNameDependencies[registrationName] = dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + + if (registrationName === 'onDoubleClick') { + possibleRegistrationNames.ondblclick = registrationName; + } + } + + for (var i = 0; i < dependencies.length; i++) { + allNativeEvents.add(dependencies[i]); } } var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); - var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var _assign = ReactInternals.assign; - - var PLUGIN_EVENT_SYSTEM = 1; - var IS_REPLAYED = 1 << 5; - var IS_FIRST_ANCESTOR = 1 << 6; - - var restoreImpl = null; - var restoreTarget = null; - var restoreQueue = null; - - function restoreStateOfTarget(target) { - // We perform this translation at the end of the event loop so that we - // always receive the correct fiber here - var internalInstance = getInstanceFromNode(target); - - if (!internalInstance) { - // Unmounted - return; - } - - if (!(typeof restoreImpl === 'function')) { - { - throw Error( "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." ); - } - } - - var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. - - if (stateNode) { - var _props = getFiberCurrentPropsFromNode(stateNode); - - restoreImpl(internalInstance.stateNode, internalInstance.type, _props); - } - } - - function setRestoreImplementation(impl) { - restoreImpl = impl; - } - function enqueueStateRestore(target) { - if (restoreTarget) { - if (restoreQueue) { - restoreQueue.push(target); - } else { - restoreQueue = [target]; - } - } else { - restoreTarget = target; - } - } - function needsStateRestore() { - return restoreTarget !== null || restoreQueue !== null; - } - function restoreStateIfNeeded() { - if (!restoreTarget) { - return; - } - - var target = restoreTarget; - var queuedTargets = restoreQueue; - restoreTarget = null; - restoreQueue = null; - restoreStateOfTarget(target); - - if (queuedTargets) { - for (var i = 0; i < queuedTargets.length; i++) { - restoreStateOfTarget(queuedTargets[i]); - } - } - } - - var enableProfilerTimer = true; // Trace which interactions trigger each commit. - - var enableDeprecatedFlareAPI = false; // Experimental Host Component support. - - var enableFundamentalAPI = false; // Experimental Scope support. - var warnAboutStringRefs = false; - - // the renderer. Such as when we're dispatching events or if third party - // libraries need to call batchedUpdates. Eventually, this API will go away when - // everything is batched by default. We'll then have a similar API to opt-out of - // scheduled work and instead do synchronous work. - // Defaults - - var batchedUpdatesImpl = function (fn, bookkeeping) { - return fn(bookkeeping); - }; - - var discreteUpdatesImpl = function (fn, a, b, c, d) { - return fn(a, b, c, d); - }; - - var flushDiscreteUpdatesImpl = function () {}; - - var batchedEventUpdatesImpl = batchedUpdatesImpl; - var isInsideEventHandler = false; - var isBatchingEventUpdates = false; - - function finishEventHandler() { - // Here we wait until all updates have propagated, which is important - // when using controlled components within layers: - // https://github.com/facebook/react/issues/1698 - // Then we restore state of any controlled component. - var controlledComponentsHavePendingUpdates = needsStateRestore(); - - if (controlledComponentsHavePendingUpdates) { - // If a controlled event was fired, we may need to restore the state of - // the DOM node back to the controlled value. This is necessary when React - // bails out of the update without touching the DOM. - flushDiscreteUpdatesImpl(); - restoreStateIfNeeded(); - } - } - - function batchedUpdates(fn, bookkeeping) { - if (isInsideEventHandler) { - // If we are currently inside another batch, we need to wait until it - // fully completes before restoring state. - return fn(bookkeeping); - } - - isInsideEventHandler = true; - - try { - return batchedUpdatesImpl(fn, bookkeeping); - } finally { - isInsideEventHandler = false; - finishEventHandler(); - } - } - function batchedEventUpdates(fn, a, b) { - if (isBatchingEventUpdates) { - // If we are currently inside another batch, we need to wait until it - // fully completes before restoring state. - return fn(a, b); - } - - isBatchingEventUpdates = true; - - try { - return batchedEventUpdatesImpl(fn, a, b); - } finally { - isBatchingEventUpdates = false; - finishEventHandler(); - } - } // This is for the React Flare event system - function discreteUpdates(fn, a, b, c, d) { - var prevIsInsideEventHandler = isInsideEventHandler; - isInsideEventHandler = true; - - try { - return discreteUpdatesImpl(fn, a, b, c, d); - } finally { - isInsideEventHandler = prevIsInsideEventHandler; - - if (!isInsideEventHandler) { - finishEventHandler(); - } - } - } - function flushDiscreteUpdatesIfNeeded(timeStamp) { - // event.timeStamp isn't overly reliable due to inconsistencies in - // how different browsers have historically provided the time stamp. - // Some browsers provide high-resolution time stamps for all events, - // some provide low-resolution time stamps for all events. FF < 52 - // even mixes both time stamps together. Some browsers even report - // negative time stamps or time stamps that are 0 (iOS9) in some cases. - // Given we are only comparing two time stamps with equality (!==), - // we are safe from the resolution differences. If the time stamp is 0 - // we bail-out of preventing the flush, which can affect semantics, - // such as if an earlier flush removes or adds event listeners that - // are fired in the subsequent flush. However, this is the same - // behaviour as we had before this change, so the risks are low. - if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) { - flushDiscreteUpdatesImpl(); - } - } - function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) { - batchedUpdatesImpl = _batchedUpdatesImpl; - discreteUpdatesImpl = _discreteUpdatesImpl; - flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl; - batchedEventUpdatesImpl = _batchedEventUpdatesImpl; - } - - var DiscreteEvent = 0; - var UserBlockingEvent = 1; - var ContinuousEvent = 2; - - var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var _ReactInternals$Sched = ReactInternals$1.Scheduler, - unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback, - unstable_now = _ReactInternals$Sched.unstable_now, - unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback, - unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield, - unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint, - unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode, - unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority, - unstable_next = _ReactInternals$Sched.unstable_next, - unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution, - unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution, - unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel, - unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority, - unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority, - unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority, - unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority, - unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority, - unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate, - unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting; - // A reserved attribute. // It is handled by React separately and shouldn't be written to the DOM. var RESERVED = 0; // A simple string attribute. - // Attributes that aren't in the whitelist are presumed to have this type. + // Attributes that aren't in the filter are presumed to have this type. var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called // "enumerated" attributes with "true" and "false" as possible values. @@ -976,6 +268,7 @@ } if (propertyInfo !== null) { + switch (propertyInfo.type) { case BOOLEAN: return !value; @@ -997,7 +290,7 @@ return properties.hasOwnProperty(name) ? properties[name] : null; } - function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) { + function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; @@ -1005,6 +298,7 @@ this.propertyName = name; this.type = type; this.sanitizeURL = sanitizeURL; + this.removeEmptyString = removeEmptyString; } // When adding attributes to this list, be sure to also add them to // the `possibleStandardNames` module to ensure casing and incorrect // name warnings. @@ -1016,11 +310,11 @@ // elements (not just inputs). Now that ReactDOMInput assigns to the // defaultValue property -- do we need this? 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; - reservedProps.forEach(function (name) { properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty name, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // A few React string attributes have a different name. // This is a mapping from React prop names to the attribute names. @@ -1031,6 +325,7 @@ properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are "enumerated" HTML attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically @@ -1040,6 +335,7 @@ properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are "enumerated" SVG attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically @@ -1050,16 +346,18 @@ properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are HTML boolean attributes. ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). - 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata + 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata 'itemScope'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are the few React props that we set as DOM properties // rather than attributes. These are all booleans. @@ -1073,6 +371,7 @@ properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty name, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are HTML attributes that are "overloaded booleans": they behave like // booleans, but can also accept a string value. @@ -1084,6 +383,7 @@ properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty name, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are HTML attributes that must be positive numbers. @@ -1094,6 +394,7 @@ properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty name, // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These are HTML attributes that must be numbers. @@ -1101,6 +402,7 @@ properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); var CAMELIZE = /[\-\:]([a-z])/g; @@ -1109,7 +411,7 @@ return token[1].toUpperCase(); }; // This is a list of all SVG attributes that need special casing, namespacing, // or boolean value assignment. Regular attributes that just accept strings - // and have the same names are omitted, just like in the HTML whitelist. + // and have the same names are omitted, just like in the HTML attribute filter. // Some of these attributes can be hard to find. This list was created by // scraping the MDN documentation. @@ -1121,6 +423,7 @@ var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, null, // attributeNamespace + false, // sanitizeURL false); }); // String SVG attributes with the xlink namespace. @@ -1130,7 +433,8 @@ ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/1999/xlink', false); + attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL + false); }); // String SVG attributes with the xml namespace. ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, @@ -1139,7 +443,8 @@ ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty - attributeName, 'http://www.w3.org/XML/1998/namespace', false); + attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL + false); }); // These attribute exists both in HTML and SVG. // The attribute name is case-sensitive in SVG so we can't just use // the React name like we do for attributes that exist only in HTML. @@ -1148,25 +453,23 @@ properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace + false, // sanitizeURL false); }); // These attributes accept URLs. These must not allow javascript: URLS. // These will also need to accept Trusted Types object in the future. var xlinkHref = 'xlinkHref'; properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty - 'xlink:href', 'http://www.w3.org/1999/xlink', true); + 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL + false); ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace + true, // sanitizeURL true); }); - var ReactDebugCurrentFrame = null; - - { - ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - } // A javascript: URL can contain leading C0 control or \u0020 SPACE, // and any newline or tab are filtered out as if they're not part of the URL. // https://url.spec.whatwg.org/#url-parsing // Tab or newline are defined as \r\n\t: @@ -1177,7 +480,6 @@ /* eslint-disable max-len */ - var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; @@ -1270,6 +572,13 @@ { if (!isAttributeNameSafe(name)) { return; + } // If the object is an opaque reference ID, it's expected that + // the next prop is different than the server value, so just return + // expected + + + if (isOpaqueHydratingObject(expected)) { + return expected; } if (!node.hasAttribute(name)) { @@ -1370,56 +679,59 @@ } } - var BEFORE_SLASH_RE = /^(.*)[\\\/]/; - function describeComponentFrame (name, source, ownerName) { - var sourceInfo = ''; - - if (source) { - var path = source.fileName; - var fileName = path.replace(BEFORE_SLASH_RE, ''); - - { - // In DEV, include code for a common special case: - // prefer "folder/index.js" instead of just "index.js". - if (/^index\./.test(fileName)) { - var match = path.match(BEFORE_SLASH_RE); - - if (match) { - var pathBeforeSlash = match[1]; - - if (pathBeforeSlash) { - var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); - fileName = folderName + '/' + fileName; - } - } - } - } - - sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; - } else if (ownerName) { - sourceInfo = ' (created by ' + ownerName + ')'; - } - - return '\n in ' + (name || 'Unknown') + sourceInfo; - } + var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + var _assign = ReactInternals.assign; + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. - var hasSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; - var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; - var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; - var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; - var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; - var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; - var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary - var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; - var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; - var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; - var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; - var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; - var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; - var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; + var REACT_ELEMENT_TYPE = 0xeac7; + var REACT_PORTAL_TYPE = 0xeaca; + var REACT_FRAGMENT_TYPE = 0xeacb; + var REACT_STRICT_MODE_TYPE = 0xeacc; + var REACT_PROFILER_TYPE = 0xead2; + var REACT_PROVIDER_TYPE = 0xeacd; + var REACT_CONTEXT_TYPE = 0xeace; + var REACT_FORWARD_REF_TYPE = 0xead0; + var REACT_SUSPENSE_TYPE = 0xead1; + var REACT_SUSPENSE_LIST_TYPE = 0xead8; + var REACT_MEMO_TYPE = 0xead3; + var REACT_LAZY_TYPE = 0xead4; + var REACT_BLOCK_TYPE = 0xead9; + var REACT_SERVER_BLOCK_TYPE = 0xeada; + var REACT_FUNDAMENTAL_TYPE = 0xead5; + var REACT_SCOPE_TYPE = 0xead7; + var REACT_OPAQUE_ID_TYPE = 0xeae0; + var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; + var REACT_OFFSCREEN_TYPE = 0xeae2; + var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; + + if (typeof Symbol === 'function' && Symbol.for) { + var symbolFor = Symbol.for; + REACT_ELEMENT_TYPE = symbolFor('react.element'); + REACT_PORTAL_TYPE = symbolFor('react.portal'); + REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); + REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); + REACT_PROFILER_TYPE = symbolFor('react.profiler'); + REACT_PROVIDER_TYPE = symbolFor('react.provider'); + REACT_CONTEXT_TYPE = symbolFor('react.context'); + REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); + REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); + REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); + REACT_MEMO_TYPE = symbolFor('react.memo'); + REACT_LAZY_TYPE = symbolFor('react.lazy'); + REACT_BLOCK_TYPE = symbolFor('react.block'); + REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); + REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); + REACT_SCOPE_TYPE = symbolFor('react.scope'); + REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); + REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); + REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); + REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); + } + var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { @@ -1436,38 +748,397 @@ return null; } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function refineResolvedLazyComponent(lazyComponent) { - return lazyComponent._status === Resolved ? lazyComponent._result : null; - } - function initializeLazyComponentType(lazyComponent) { - if (lazyComponent._status === Uninitialized) { - lazyComponent._status = Pending; - var ctor = lazyComponent._ctor; - var thenable = ctor(); - lazyComponent._result = thenable; - thenable.then(function (moduleObject) { - if (lazyComponent._status === Pending) { - var defaultExport = moduleObject.default; + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; - { - if (defaultExport === undefined) { - error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); - } + function disabledLog() {} + + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: _assign({}, props, { + value: prevLog + }), + info: _assign({}, props, { + value: prevInfo + }), + warn: _assign({}, props, { + value: prevWarn + }), + error: _assign({}, props, { + value: prevError + }), + group: _assign({}, props, { + value: prevGroup + }), + groupCollapsed: _assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: _assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } + } + + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; } - lazyComponent._status = Resolved; - lazyComponent._result = defaultExport; + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); } - }, function (error) { - if (lazyComponent._status === Pending) { - lazyComponent._status = Rejected; - lazyComponent._result = error; + } else { + try { + throw Error(); + } catch (x) { + control = x; } - }); + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; + } + + function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_BLOCK_TYPE: + return describeFunctionComponentFrame(type._render); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; + } + + function describeFiber(fiber) { + var owner = fiber._debugOwner ? fiber._debugOwner.type : null ; + var source = fiber._debugSource ; + + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); + + case LazyComponent: + return describeBuiltInComponentFrame('Lazy'); + + case SuspenseComponent: + return describeBuiltInComponentFrame('Suspense'); + + case SuspenseListComponent: + return describeBuiltInComponentFrame('SuspenseList'); + + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); + + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); + + case Block: + return describeFunctionComponentFrame(fiber.type._render); + + case ClassComponent: + return describeClassComponentFrame(fiber.type); + + default: + return ''; + } + } + + function getStackByFiberInDevAndProd(workInProgress) { + try { + var info = ''; + var node = workInProgress; + + do { + info += describeFiber(node); + node = node.return; + } while (node); + + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; } } @@ -1476,6 +1147,10 @@ return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } + function getContextName(type) { + return type.displayName || 'Context'; + } + function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. @@ -1504,7 +1179,7 @@ return 'Portal'; case REACT_PROFILER_TYPE: - return "Profiler"; + return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; @@ -1519,10 +1194,12 @@ if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: - return 'Context.Consumer'; + var context = type; + return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: - return 'Context.Provider'; + var provider = type; + return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); @@ -1531,18 +1208,19 @@ return getComponentName(type.type); case REACT_BLOCK_TYPE: - return getComponentName(type.render); + return getComponentName(type._render); case REACT_LAZY_TYPE: { - var thenable = type; - var resolvedThenable = refineResolvedLazyComponent(thenable); + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; - if (resolvedThenable) { - return getComponentName(resolvedThenable); + try { + return getComponentName(init(payload)); + } catch (x) { + return null; } - - break; } } } @@ -1550,43 +1228,7 @@ return null; } - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - - function describeFiber(fiber) { - switch (fiber.tag) { - case HostRoot: - case HostPortal: - case HostText: - case Fragment: - case ContextProvider: - case ContextConsumer: - return ''; - - default: - var owner = fiber._debugOwner; - var source = fiber._debugSource; - var name = getComponentName(fiber.type); - var ownerName = null; - - if (owner) { - ownerName = getComponentName(owner.type); - } - - return describeComponentFrame(name, source, ownerName); - } - } - - function getStackByFiberInDevAndProd(workInProgress) { - var info = ''; - var node = workInProgress; - - do { - info += describeFiber(node); - node = node.return; - } while (node); - - return info; - } + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { @@ -1604,6 +1246,7 @@ return null; } + function getCurrentFiberStackInDev() { { if (current === null) { @@ -1615,16 +1258,17 @@ return getStackByFiberInDevAndProd(current); } } + function resetCurrentFiber() { { - ReactDebugCurrentFrame$1.getCurrentStack = null; + ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; + ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; current = fiber; isRendering = false; } @@ -1634,6 +1278,11 @@ isRendering = rendering; } } + function getIsRendering() { + { + return isRendering; + } + } // Flow does not allow string concatenation of most non-string types. To work // around this limitation, we use an opaque type that can only be obtained by @@ -1656,153 +1305,27 @@ } } - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; - - var ReactPropTypesSecret_1 = ReactPropTypesSecret; - - var printWarning$1 = function() {}; - - { - var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; - var loggedTypeFailures = {}; - var has = Function.call.bind(Object.prototype.hasOwnProperty); - - printWarning$1 = function(text) { - var message = 'Warning: ' + text; - if (typeof console !== 'undefined') { - console.error(message); - } - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - throw new Error(message); - } catch (x) {} - }; - } - - /** - * Assert that the values match with the type specs. - * Error messages are memorized and will only be shown once. - * - * @param {object} typeSpecs Map of name to a ReactPropType - * @param {object} values Runtime values that need to be type-checked - * @param {string} location e.g. "prop", "context", "child context" - * @param {string} componentName Name of the component for error messages. - * @param {?Function} getStack Returns the component stack. - * @private - */ - function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + function checkControlledValueProps(tagName, props) { { - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error; - // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - var err = Error( - (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' - ); - err.name = 'Invariant Violation'; - throw err; - } - error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); - } catch (ex) { - error = ex; - } - if (error && !(error instanceof Error)) { - printWarning$1( - (componentName || 'React class') + ': type specification of ' + - location + ' `' + typeSpecName + '` is invalid; the type checker ' + - 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + - 'You may have forgotten to pass an argument to the type checker ' + - 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + - 'shape all require an argument).' - ); - } - if (error instanceof Error && !(error.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error.message] = true; + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } - var stack = getStack ? getStack() : ''; - - printWarning$1( - 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') - ); - } - } + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); } } } - /** - * Resets warning cache when testing. - * - * @private - */ - checkPropTypes.resetWarningCache = function() { - { - loggedTypeFailures = {}; - } - }; - - var checkPropTypes_1 = checkPropTypes; - - var ReactDebugCurrentFrame$2 = null; - var ReactControlledValuePropTypes = { - checkPropTypes: null - }; - - { - ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame; - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - var propTypes = { - value: function (props, propName, componentName) { - if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { - return null; - } - - return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - }, - checked: function (props, propName, componentName) { - if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { - return null; - } - - return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); - } - }; - /** - * Provide a linked `value` attribute for controlled forms. You should not use - * this outside of the ReactDOM controlled form components. - */ - - ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) { - checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum); - }; - } - function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; @@ -1910,6 +1433,20 @@ return false; } + function getActiveElement(doc) { + doc = doc || (typeof document !== 'undefined' ? document : undefined); + + if (typeof doc === 'undefined') { + return null; + } + + try { + return doc.activeElement || doc.body; + } catch (e) { + return doc.body; + } + } + var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; @@ -1952,16 +1489,16 @@ } function initWrapperState(element, props) { { - ReactControlledValuePropTypes.checkPropTypes('input', props); + checkControlledValueProps('input', props); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { - error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { - error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnValueDefaultValue = true; } @@ -1990,13 +1527,13 @@ var controlled = isControlled(props); if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { - error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnUncontrolledToControlled = true; } if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { - error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnControlledToUncontrolled = true; } @@ -2144,7 +1681,7 @@ // mixing React radio buttons with non-React ones. - var otherProps = getFiberCurrentPropsFromNode$1(otherNode); + var otherProps = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { { @@ -2173,7 +1710,7 @@ function setDefaultValue(node, type, value) { if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js - type !== 'number' || node.ownerDocument.activeElement !== node) { + type !== 'number' || getActiveElement(node.ownerDocument) !== node) { if (value == null) { node.defaultValue = toString(node._wrapperState.initialValue); } else if (node.defaultValue !== toString(value)) { @@ -2199,7 +1736,7 @@ content += child; // Note: we don't warn about invalid children here. // Instead, this is done separately below so that - // it happens during the hydration codepath too. + // it happens during the hydration code path too. }); return content; } @@ -2210,7 +1747,7 @@ function validateProps(element, props) { { - // This mirrors the codepath above, but runs for hydration too. + // This mirrors the code path above, but runs for hydration too. // Warn about invalid children here so that client and hydration are consistent. // TODO: this seems like it could cause a DEV-only throw for hydration // if children contains a non-element object. We should try to avoid that. @@ -2287,7 +1824,7 @@ function checkSelectPropTypes(props) { { - ReactControlledValuePropTypes.checkPropTypes('select', props); + checkControlledValueProps('select', props); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; @@ -2393,7 +1930,7 @@ { if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) { - error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); + error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components'); didWarnValueDefaultValue$1 = true; } @@ -2481,10 +2018,10 @@ var node = element; { - ReactControlledValuePropTypes.checkPropTypes('textarea', props); + checkControlledValueProps('textarea', props); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { - error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component'); + error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component'); didWarnValDefaultVal = true; } @@ -2696,1704 +2233,6 @@ node.textContent = text; }; - // Do not use the below two methods directly! - // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM. - // (It is the only module that is allowed to access these methods.) - function unsafeCastStringToDOMTopLevelType(topLevelType) { - return topLevelType; - } - function unsafeCastDOMTopLevelTypeToString(topLevelType) { - return topLevelType; - } - - /** - * Generate a mapping of standard vendor prefixes using the defined style property and event name. - * - * @param {string} styleProp - * @param {string} eventName - * @returns {object} - */ - - function makePrefixMap(styleProp, eventName) { - var prefixes = {}; - prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); - prefixes['Webkit' + styleProp] = 'webkit' + eventName; - prefixes['Moz' + styleProp] = 'moz' + eventName; - return prefixes; - } - /** - * A list of event names to a configurable list of vendor prefixes. - */ - - - var vendorPrefixes = { - animationend: makePrefixMap('Animation', 'AnimationEnd'), - animationiteration: makePrefixMap('Animation', 'AnimationIteration'), - animationstart: makePrefixMap('Animation', 'AnimationStart'), - transitionend: makePrefixMap('Transition', 'TransitionEnd') - }; - /** - * Event names that have already been detected and prefixed (if applicable). - */ - - var prefixedEventNames = {}; - /** - * Element to check for prefixes on. - */ - - var style = {}; - /** - * Bootstrap if a DOM exists. - */ - - if (canUseDOM) { - style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, - // the un-prefixed "animation" and "transition" properties are defined on the - // style object but the events that fire will still be prefixed, so we need - // to check if the un-prefixed events are usable, and if not remove them from the map. - - if (!('AnimationEvent' in window)) { - delete vendorPrefixes.animationend.animation; - delete vendorPrefixes.animationiteration.animation; - delete vendorPrefixes.animationstart.animation; - } // Same as above - - - if (!('TransitionEvent' in window)) { - delete vendorPrefixes.transitionend.transition; - } - } - /** - * Attempts to determine the correct vendor prefixed event name. - * - * @param {string} eventName - * @returns {string} - */ - - - function getVendorPrefixedEventName(eventName) { - if (prefixedEventNames[eventName]) { - return prefixedEventNames[eventName]; - } else if (!vendorPrefixes[eventName]) { - return eventName; - } - - var prefixMap = vendorPrefixes[eventName]; - - for (var styleProp in prefixMap) { - if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { - return prefixedEventNames[eventName] = prefixMap[styleProp]; - } - } - - return eventName; - } - - /** - * To identify top level events in ReactDOM, we use constants defined by this - * module. This is the only module that uses the unsafe* methods to express - * that the constants actually correspond to the browser event names. This lets - * us save some bundle size by avoiding a top level type -> event name map. - * The rest of ReactDOM code should import top level types from this file. - */ - - var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort'); - var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend')); - var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration')); - var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart')); - var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur'); - var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay'); - var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough'); - var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel'); - var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change'); - var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click'); - var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close'); - var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend'); - var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart'); - var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate'); - var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu'); - var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy'); - var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut'); - var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick'); - var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick'); - var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag'); - var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend'); - var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter'); - var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit'); - var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave'); - var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover'); - var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart'); - var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop'); - var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange'); - var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied'); - var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted'); - var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended'); - var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error'); - var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus'); - var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture'); - var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input'); - var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid'); - var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown'); - var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress'); - var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup'); - var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load'); - var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart'); - var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata'); - var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata'); - var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture'); - var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown'); - var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove'); - var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout'); - var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover'); - var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup'); - var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste'); - var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause'); - var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play'); - var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing'); - var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel'); - var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown'); - var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove'); - var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout'); - var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover'); - var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup'); - var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress'); - var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange'); - var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset'); - var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll'); - var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked'); - var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking'); - var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange'); - var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled'); - var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit'); - var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend'); - var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput'); - var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate'); - var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle'); - var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel'); - var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend'); - var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove'); - var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart'); - var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend')); - var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange'); - var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting'); - var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements. - // Note that events in this list will *not* be listened to at the top level - // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`. - - var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING]; - function getRawEventName(topLevelType) { - return unsafeCastDOMTopLevelTypeToString(topLevelType); - } - - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // prettier-ignore - - var elementListenerMap = new PossiblyWeakMap(); - function getListenerMapForElement(element) { - var listenerMap = elementListenerMap.get(element); - - if (listenerMap === undefined) { - listenerMap = new Map(); - elementListenerMap.set(element, listenerMap); - } - - return listenerMap; - } - - /** - * `ReactInstanceMap` maintains a mapping from a public facing stateful - * instance (key) and the internal representation (value). This allows public - * methods to accept the user facing instance as an argument and map them back - * to internal methods. - * - * Note that this module is currently shared and assumed to be stateless. - * If this becomes an actual Map, that will break. - */ - function get(key) { - return key._reactInternalFiber; - } - function has$1(key) { - return key._reactInternalFiber !== undefined; - } - function set(key, value) { - key._reactInternalFiber = value; - } - - // Don't change these two values. They're used by React Dev Tools. - var NoEffect = - /* */ - 0; - var PerformedWork = - /* */ - 1; // You can change the rest (and add more). - - var Placement = - /* */ - 2; - var Update = - /* */ - 4; - var PlacementAndUpdate = - /* */ - 6; - var Deletion = - /* */ - 8; - var ContentReset = - /* */ - 16; - var Callback = - /* */ - 32; - var DidCapture = - /* */ - 64; - var Ref = - /* */ - 128; - var Snapshot = - /* */ - 256; - var Passive = - /* */ - 512; - var Hydrating = - /* */ - 1024; - var HydratingAndUpdate = - /* */ - 1028; // Passive & Update & Callback & Ref & Snapshot - - var LifecycleEffectMask = - /* */ - 932; // Union of all host effects - - var HostEffectMask = - /* */ - 2047; - var Incomplete = - /* */ - 2048; - var ShouldCapture = - /* */ - 4096; - - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - function getNearestMountedFiber(fiber) { - var node = fiber; - var nearestMounted = fiber; - - if (!fiber.alternate) { - // If there is no alternate, this might be a new tree that isn't inserted - // yet. If it is, then it will have a pending insertion effect on it. - var nextNode = node; - - do { - node = nextNode; - - if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) { - // This is an insertion or in-progress hydration. The nearest possible - // mounted fiber is the parent but we need to continue to figure out - // if that one is still mounted. - nearestMounted = node.return; - } - - nextNode = node.return; - } while (nextNode); - } else { - while (node.return) { - node = node.return; - } - } - - if (node.tag === HostRoot) { - // TODO: Check if this was a nested HostRoot when used with - // renderContainerIntoSubtree. - return nearestMounted; - } // If we didn't hit the root, that means that we're in an disconnected tree - // that has been unmounted. - - - return null; - } - function getSuspenseInstanceFromFiber(fiber) { - if (fiber.tag === SuspenseComponent) { - var suspenseState = fiber.memoizedState; - - if (suspenseState === null) { - var current = fiber.alternate; - - if (current !== null) { - suspenseState = current.memoizedState; - } - } - - if (suspenseState !== null) { - return suspenseState.dehydrated; - } - } - - return null; - } - function getContainerFromFiber(fiber) { - return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null; - } - function isFiberMounted(fiber) { - return getNearestMountedFiber(fiber) === fiber; - } - function isMounted(component) { - { - var owner = ReactCurrentOwner.current; - - if (owner !== null && owner.tag === ClassComponent) { - var ownerFiber = owner; - var instance = ownerFiber.stateNode; - - if (!instance._warnedAboutRefsInRender) { - error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component'); - } - - instance._warnedAboutRefsInRender = true; - } - } - - var fiber = get(component); - - if (!fiber) { - return false; - } - - return getNearestMountedFiber(fiber) === fiber; - } - - function assertIsMounted(fiber) { - if (!(getNearestMountedFiber(fiber) === fiber)) { - { - throw Error( "Unable to find node on an unmounted component." ); - } - } - } - - function findCurrentFiberUsingSlowPath(fiber) { - var alternate = fiber.alternate; - - if (!alternate) { - // If there is no alternate, then we only need to check if it is mounted. - var nearestMounted = getNearestMountedFiber(fiber); - - if (!(nearestMounted !== null)) { - { - throw Error( "Unable to find node on an unmounted component." ); - } - } - - if (nearestMounted !== fiber) { - return null; - } - - return fiber; - } // If we have two possible branches, we'll walk backwards up to the root - // to see what path the root points to. On the way we may hit one of the - // special cases and we'll deal with them. - - - var a = fiber; - var b = alternate; - - while (true) { - var parentA = a.return; - - if (parentA === null) { - // We're at the root. - break; - } - - var parentB = parentA.alternate; - - if (parentB === null) { - // There is no alternate. This is an unusual case. Currently, it only - // happens when a Suspense component is hidden. An extra fragment fiber - // is inserted in between the Suspense fiber and its children. Skip - // over this extra fragment fiber and proceed to the next parent. - var nextParent = parentA.return; - - if (nextParent !== null) { - a = b = nextParent; - continue; - } // If there's no parent, we're at the root. - - - break; - } // If both copies of the parent fiber point to the same child, we can - // assume that the child is current. This happens when we bailout on low - // priority: the bailed out fiber's child reuses the current child. - - - if (parentA.child === parentB.child) { - var child = parentA.child; - - while (child) { - if (child === a) { - // We've determined that A is the current branch. - assertIsMounted(parentA); - return fiber; - } - - if (child === b) { - // We've determined that B is the current branch. - assertIsMounted(parentA); - return alternate; - } - - child = child.sibling; - } // We should never have an alternate for any mounting node. So the only - // way this could possibly happen is if this was unmounted, if at all. - - - { - { - throw Error( "Unable to find node on an unmounted component." ); - } - } - } - - if (a.return !== b.return) { - // The return pointer of A and the return pointer of B point to different - // fibers. We assume that return pointers never criss-cross, so A must - // belong to the child set of A.return, and B must belong to the child - // set of B.return. - a = parentA; - b = parentB; - } else { - // The return pointers point to the same fiber. We'll have to use the - // default, slow path: scan the child sets of each parent alternate to see - // which child belongs to which set. - // - // Search parent A's child set - var didFindChild = false; - var _child = parentA.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentA; - b = parentB; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentA; - a = parentB; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - // Search parent B's child set - _child = parentB.child; - - while (_child) { - if (_child === a) { - didFindChild = true; - a = parentB; - b = parentA; - break; - } - - if (_child === b) { - didFindChild = true; - b = parentB; - a = parentA; - break; - } - - _child = _child.sibling; - } - - if (!didFindChild) { - { - throw Error( "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." ); - } - } - } - } - - if (!(a.alternate === b)) { - { - throw Error( "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." ); - } - } - } // If the root is not a host container, we're in a disconnected tree. I.e. - // unmounted. - - - if (!(a.tag === HostRoot)) { - { - throw Error( "Unable to find node on an unmounted component." ); - } - } - - if (a.stateNode.current === a) { - // We've determined that A is the current branch. - return fiber; - } // Otherwise B has to be current branch. - - - return alternate; - } - function findCurrentHostFiber(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - - if (!currentParent) { - return null; - } // Next we'll drill down this component to find the first HostComponent/Text. - - - var node = currentParent; - - while (true) { - if (node.tag === HostComponent || node.tag === HostText) { - return node; - } else if (node.child) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === currentParent) { - return null; - } - - while (!node.sibling) { - if (!node.return || node.return === currentParent) { - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } // Flow needs the return null here, but ESLint complains about it. - // eslint-disable-next-line no-unreachable - - - return null; - } - function findCurrentHostFiberWithNoPortals(parent) { - var currentParent = findCurrentFiberUsingSlowPath(parent); - - if (!currentParent) { - return null; - } // Next we'll drill down this component to find the first HostComponent/Text. - - - var node = currentParent; - - while (true) { - if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI ) { - return node; - } else if (node.child && node.tag !== HostPortal) { - node.child.return = node; - node = node.child; - continue; - } - - if (node === currentParent) { - return null; - } - - while (!node.sibling) { - if (!node.return || node.return === currentParent) { - return null; - } - - node = node.return; - } - - node.sibling.return = node.return; - node = node.sibling; - } // Flow needs the return null here, but ESLint complains about it. - // eslint-disable-next-line no-unreachable - - - return null; - } - - /** - * Accumulates items that must not be null or undefined into the first one. This - * is used to conserve memory by avoiding array allocations, and thus sacrifices - * API cleanness. Since `current` can be null before being passed in and not - * null after this function, make sure to assign it back to `current`: - * - * `a = accumulateInto(a, b);` - * - * This API should be sparingly used. Try `accumulate` for something cleaner. - * - * @return {*|array<*>} An accumulation of items. - */ - - function accumulateInto(current, next) { - if (!(next != null)) { - { - throw Error( "accumulateInto(...): Accumulated items must not be null or undefined." ); - } - } - - if (current == null) { - return next; - } // Both are not empty. Warning: Never call x.concat(y) when you are not - // certain that x is an Array (x could be a string with concat method). - - - if (Array.isArray(current)) { - if (Array.isArray(next)) { - current.push.apply(current, next); - return current; - } - - current.push(next); - return current; - } - - if (Array.isArray(next)) { - // A bit too dangerous to mutate `next`. - return [current].concat(next); - } - - return [current, next]; - } - - /** - * @param {array} arr an "accumulation" of items which is either an Array or - * a single item. Useful when paired with the `accumulate` module. This is a - * simple utility that allows us to reason about a collection of items, but - * handling the case when there is exactly one item (and we do not need to - * allocate an array). - * @param {function} cb Callback invoked with each element or a collection. - * @param {?} [scope] Scope used as `this` in a callback. - */ - function forEachAccumulated(arr, cb, scope) { - if (Array.isArray(arr)) { - arr.forEach(cb, scope); - } else if (arr) { - cb.call(scope, arr); - } - } - - /** - * Internal queue of events that have accumulated their dispatches and are - * waiting to have their dispatches executed. - */ - - var eventQueue = null; - /** - * Dispatches an event and releases it back into the pool, unless persistent. - * - * @param {?object} event Synthetic event to be dispatched. - * @private - */ - - var executeDispatchesAndRelease = function (event) { - if (event) { - executeDispatchesInOrder(event); - - if (!event.isPersistent()) { - event.constructor.release(event); - } - } - }; - - 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); - - if (!!eventQueue) { - { - throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." ); - } - } // This would be a good time to rethrow if any of the event handlers threw. - - - rethrowCaughtError(); - } - - /** - * Gets the target node from a native browser event by accounting for - * inconsistencies in browser DOM APIs. - * - * @param {object} nativeEvent Native browser event. - * @return {DOMEventTarget} Target node. - */ - - function getEventTarget(nativeEvent) { - // Fallback to nativeEvent.srcElement for IE9 - // https://github.com/facebook/react/issues/12506 - var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG element events #4963 - - if (target.correspondingUseElement) { - target = target.correspondingUseElement; - } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). - // @see http://www.quirksmode.org/js/events_properties.html - - - return target.nodeType === TEXT_NODE ? target.parentNode : target; - } - - /** - * Checks if an event is supported in the current execution environment. - * - * NOTE: This will not work correctly for non-generic events such as `change`, - * `reset`, `load`, `error`, and `select`. - * - * Borrows from Modernizr. - * - * @param {string} eventNameSuffix Event name, e.g. "click". - * @return {boolean} True if the event is supported. - * @internal - * @license Modernizr 3.0.0pre (Custom Build) | MIT - */ - - function isEventSupported(eventNameSuffix) { - if (!canUseDOM) { - return false; - } - - var eventName = 'on' + eventNameSuffix; - var isSupported = eventName in document; - - if (!isSupported) { - var element = document.createElement('div'); - element.setAttribute(eventName, 'return;'); - isSupported = typeof element[eventName] === 'function'; - } - - return isSupported; - } - - /** - * Summary of `DOMEventPluginSystem` event handling: - * - * - Top-level delegation is used to trap most native browser events. This - * may only occur in the main thread and is the responsibility of - * ReactDOMEventListener, which is injected and can therefore support - * pluggable event sources. This is the only work that occurs in the main - * thread. - * - * - We normalize and de-duplicate events to account for browser quirks. This - * may be done in the worker thread. - * - * - Forward these native events (with the associated top-level type used to - * trap it) to `EventPluginRegistry`, which in turn will ask plugins if they want - * to extract any synthetic events. - * - * - The `EventPluginRegistry` will then process each event by annotating them with - * "dispatches", a sequence of listeners and IDs that care about that event. - * - * - The `EventPluginRegistry` then dispatches the events. - * - * Overview of React and the event system: - * - * +------------+ . - * | DOM | . - * +------------+ . - * | . - * v . - * +------------+ . - * | ReactEvent | . - * | Listener | . - * +------------+ . +-----------+ - * | . +--------+|SimpleEvent| - * | . | |Plugin | - * +-----|------+ . v +-----------+ - * | | | . +--------------+ +------------+ - * | +-----------.--->|PluginRegistry| | Event | - * | | . | | +-----------+ | Propagators| - * | ReactEvent | . | | |TapEvent | |------------| - * | Emitter | . | |<---+|Plugin | |other plugin| - * | | . | | +-----------+ | utilities | - * | +-----------.--->| | +------------+ - * | | | . +--------------+ - * +-----|------+ . ^ +-----------+ - * | . | |Enter/Leave| - * + . +-------+|Plugin | - * +-------------+ . +-----------+ - * | application | . - * |-------------| . - * | | . - * | | . - * +-------------+ . - * . - * React Core . General Purpose Event Plugin System - */ - - var CALLBACK_BOOKKEEPING_POOL_SIZE = 10; - var callbackBookkeepingPool = []; - - function releaseTopLevelCallbackBookKeeping(instance) { - instance.topLevelType = null; - instance.nativeEvent = null; - instance.targetInst = null; - instance.ancestors.length = 0; - - if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) { - callbackBookkeepingPool.push(instance); - } - } // Used to store ancestor hierarchy in top level callback - - - function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) { - if (callbackBookkeepingPool.length) { - var instance = callbackBookkeepingPool.pop(); - instance.topLevelType = topLevelType; - instance.eventSystemFlags = eventSystemFlags; - instance.nativeEvent = nativeEvent; - instance.targetInst = targetInst; - return instance; - } - - return { - topLevelType: topLevelType, - eventSystemFlags: eventSystemFlags, - nativeEvent: nativeEvent, - targetInst: targetInst, - ancestors: [] - }; - } - /** - * Find the deepest React component completely containing the root of the - * passed-in instance (for use when entire React trees are nested within each - * other). If React trees are not nested, returns null. - */ - - - function findRootContainerNode(inst) { - if (inst.tag === HostRoot) { - return inst.stateNode.containerInfo; - } // TODO: It may be a good idea to cache this to prevent unnecessary DOM - // traversal, but caching is difficult to do correctly without using a - // mutation observer to listen for all DOM changes. - - - while (inst.return) { - inst = inst.return; - } - - if (inst.tag !== HostRoot) { - // This can happen if we're in a detached tree. - return null; - } - - return inst.stateNode.containerInfo; - } - /** - * Allows registered plugins an opportunity to extract events from top-level - * native browser events. - * - * @return {*} An accumulation of synthetic events. - * @internal - */ - - - function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) { - var events = null; - - for (var i = 0; i < plugins.length; i++) { - // Not every plugin in the ordering may be loaded at runtime. - var possiblePlugin = plugins[i]; - - if (possiblePlugin) { - var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); - - if (extractedEvents) { - events = accumulateInto(events, extractedEvents); - } - } - } - - return events; - } - - function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) { - var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); - runEventsInBatch(events); - } - - function handleTopLevel(bookKeeping) { - var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components. - // It's important that we build the array of ancestors before calling any - // event handlers, because event handlers can modify the DOM, leading to - // inconsistencies with ReactMount's node cache. See #1105. - - var ancestor = targetInst; - - do { - if (!ancestor) { - var ancestors = bookKeeping.ancestors; - ancestors.push(ancestor); - break; - } - - var root = findRootContainerNode(ancestor); - - if (!root) { - break; - } - - var tag = ancestor.tag; - - if (tag === HostComponent || tag === HostText) { - bookKeeping.ancestors.push(ancestor); - } - - ancestor = getClosestInstanceFromNode(root); - } while (ancestor); - - for (var i = 0; i < bookKeeping.ancestors.length; i++) { - targetInst = bookKeeping.ancestors[i]; - var eventTarget = getEventTarget(bookKeeping.nativeEvent); - var topLevelType = bookKeeping.topLevelType; - var nativeEvent = bookKeeping.nativeEvent; - var eventSystemFlags = bookKeeping.eventSystemFlags; // If this is the first ancestor, we mark it on the system flags - - if (i === 0) { - eventSystemFlags |= IS_FIRST_ANCESTOR; - } - - runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, eventSystemFlags); - } - } - - function dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) { - var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags); - - try { - // Event queue being processed in the same cycle allows - // `preventDefault`. - batchedEventUpdates(handleTopLevel, bookKeeping); - } finally { - releaseTopLevelCallbackBookKeeping(bookKeeping); - } - } - /** - * We listen for bubbled touch events on the document object. - * - * Firefox v8.01 (and possibly others) exhibited strange behavior when - * mounting `onmousemove` events at some node that was not the document - * element. The symptoms were that if your mouse is not moving over something - * contained within that mount point (for example on the background) the - * top-level listeners for `onmousemove` won't be called. However, if you - * register the `mousemove` on the document object, then it will of course - * catch all `mousemove`s. This along with iOS quirks, justifies restricting - * top-level listeners to the document object only, at least for these - * movement types of events and possibly all events. - * - * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - * - * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but - * they bubble to document. - * - * @param {string} registrationName Name of listener (e.g. `onClick`). - * @param {object} mountAt Container where to mount the listener - */ - - function legacyListenToEvent(registrationName, mountAt) { - var listenerMap = getListenerMapForElement(mountAt); - var dependencies = registrationNameDependencies[registrationName]; - - for (var i = 0; i < dependencies.length; i++) { - var dependency = dependencies[i]; - legacyListenToTopLevelEvent(dependency, mountAt, listenerMap); - } - } - function legacyListenToTopLevelEvent(topLevelType, mountAt, listenerMap) { - if (!listenerMap.has(topLevelType)) { - switch (topLevelType) { - case TOP_SCROLL: - trapCapturedEvent(TOP_SCROLL, mountAt); - break; - - case TOP_FOCUS: - case TOP_BLUR: - trapCapturedEvent(TOP_FOCUS, mountAt); - trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function, - // but this ensures we mark both as attached rather than just one. - - listenerMap.set(TOP_BLUR, null); - listenerMap.set(TOP_FOCUS, null); - break; - - case TOP_CANCEL: - case TOP_CLOSE: - if (isEventSupported(getRawEventName(topLevelType))) { - trapCapturedEvent(topLevelType, mountAt); - } - - break; - - case TOP_INVALID: - case TOP_SUBMIT: - case TOP_RESET: - // We listen to them on the target DOM elements. - // Some of them bubble so we don't want them to fire twice. - break; - - default: - // By default, listen on the top level to all non-media events. - // Media events don't bubble so adding the listener wouldn't do anything. - var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1; - - if (!isMediaEvent) { - trapBubbledEvent(topLevelType, mountAt); - } - - break; - } - - listenerMap.set(topLevelType, null); - } - } - function isListeningToAllDependencies(registrationName, mountAt) { - var listenerMap = getListenerMapForElement(mountAt); - var dependencies = registrationNameDependencies[registrationName]; - - for (var i = 0; i < dependencies.length; i++) { - var dependency = dependencies[i]; - - if (!listenerMap.has(dependency)) { - return false; - } - } - - return true; - } - - var attemptUserBlockingHydration; - function setAttemptUserBlockingHydration(fn) { - attemptUserBlockingHydration = fn; - } - var attemptContinuousHydration; - function setAttemptContinuousHydration(fn) { - attemptContinuousHydration = fn; - } - var attemptHydrationAtCurrentPriority; - function setAttemptHydrationAtCurrentPriority(fn) { - attemptHydrationAtCurrentPriority = fn; - } // TODO: Upgrade this definition once we're on a newer version of Flow that - var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed. - - var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout. - // if the last target was dehydrated. - - var queuedFocus = null; - var queuedDrag = null; - var queuedMouse = null; // For pointer events there can be one latest event per pointerId. - - var queuedPointers = new Map(); - var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too. - - var queuedExplicitHydrationTargets = []; - function hasQueuedDiscreteEvents() { - return queuedDiscreteEvents.length > 0; - } - var discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT]; - var continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE]; - function isReplayableDiscreteEvent(eventType) { - return discreteReplayableEvents.indexOf(eventType) > -1; - } - - function trapReplayableEventForDocument(topLevelType, document, listenerMap) { - legacyListenToTopLevelEvent(topLevelType, document, listenerMap); - } - - function eagerlyTrapReplayableEvents(container, document) { - var listenerMapForDoc = getListenerMapForElement(document); // Discrete - - discreteReplayableEvents.forEach(function (topLevelType) { - trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc); - }); // Continuous - - continuousReplayableEvents.forEach(function (topLevelType) { - trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc); - }); - } - - function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) { - return { - blockedOn: blockedOn, - topLevelType: topLevelType, - eventSystemFlags: eventSystemFlags | IS_REPLAYED, - nativeEvent: nativeEvent, - container: container - }; - } - - function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) { - var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent); - queuedDiscreteEvents.push(queuedEvent); - } // Resets the replaying for this type of continuous event to no event. - - function clearIfContinuousEvent(topLevelType, nativeEvent) { - switch (topLevelType) { - case TOP_FOCUS: - case TOP_BLUR: - queuedFocus = null; - break; - - case TOP_DRAG_ENTER: - case TOP_DRAG_LEAVE: - queuedDrag = null; - break; - - case TOP_MOUSE_OVER: - case TOP_MOUSE_OUT: - queuedMouse = null; - break; - - case TOP_POINTER_OVER: - case TOP_POINTER_OUT: - { - var pointerId = nativeEvent.pointerId; - queuedPointers.delete(pointerId); - break; - } - - case TOP_GOT_POINTER_CAPTURE: - case TOP_LOST_POINTER_CAPTURE: - { - var _pointerId = nativeEvent.pointerId; - queuedPointerCaptures.delete(_pointerId); - break; - } - } - } - - function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) { - if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) { - var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent); - - if (blockedOn !== null) { - var _fiber2 = getInstanceFromNode$1(blockedOn); - - if (_fiber2 !== null) { - // Attempt to increase the priority of this target. - attemptContinuousHydration(_fiber2); - } - } - - return queuedEvent; - } // If we have already queued this exact event, then it's because - // the different event systems have different DOM event listeners. - // We can accumulate the flags and store a single event to be - // replayed. - - - existingQueuedEvent.eventSystemFlags |= eventSystemFlags; - return existingQueuedEvent; - } - - function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) { - // These set relatedTarget to null because the replayed event will be treated as if we - // moved from outside the window (no target) onto the target once it hydrates. - // Instead of mutating we could clone the event. - switch (topLevelType) { - case TOP_FOCUS: - { - var focusEvent = nativeEvent; - queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, container, focusEvent); - return true; - } - - case TOP_DRAG_ENTER: - { - var dragEvent = nativeEvent; - queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, container, dragEvent); - return true; - } - - case TOP_MOUSE_OVER: - { - var mouseEvent = nativeEvent; - queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, container, mouseEvent); - return true; - } - - case TOP_POINTER_OVER: - { - var pointerEvent = nativeEvent; - var pointerId = pointerEvent.pointerId; - queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, container, pointerEvent)); - return true; - } - - case TOP_GOT_POINTER_CAPTURE: - { - var _pointerEvent = nativeEvent; - var _pointerId2 = _pointerEvent.pointerId; - queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, container, _pointerEvent)); - return true; - } - } - - return false; - } // Check if this target is unblocked. Returns true if it's unblocked. - - function attemptExplicitHydrationTarget(queuedTarget) { - // TODO: This function shares a lot of logic with attemptToDispatchEvent. - // Try to unify them. It's a bit tricky since it would require two return - // values. - var targetInst = getClosestInstanceFromNode(queuedTarget.target); - - if (targetInst !== null) { - var nearestMounted = getNearestMountedFiber(targetInst); - - if (nearestMounted !== null) { - var tag = nearestMounted.tag; - - if (tag === SuspenseComponent) { - var instance = getSuspenseInstanceFromFiber(nearestMounted); - - if (instance !== null) { - // We're blocked on hydrating this boundary. - // Increase its priority. - queuedTarget.blockedOn = instance; - unstable_runWithPriority(queuedTarget.priority, function () { - attemptHydrationAtCurrentPriority(nearestMounted); - }); - return; - } - } else if (tag === HostRoot) { - var root = nearestMounted.stateNode; - - if (root.hydrate) { - queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of - // a root other than sync. - - return; - } - } - } - } - - queuedTarget.blockedOn = null; - } - - function attemptReplayContinuousQueuedEvent(queuedEvent) { - if (queuedEvent.blockedOn !== null) { - return false; - } - - var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.container, queuedEvent.nativeEvent); - - if (nextBlockedOn !== null) { - // We're still blocked. Try again later. - var _fiber3 = getInstanceFromNode$1(nextBlockedOn); - - if (_fiber3 !== null) { - attemptContinuousHydration(_fiber3); - } - - queuedEvent.blockedOn = nextBlockedOn; - return false; - } - - return true; - } - - function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) { - if (attemptReplayContinuousQueuedEvent(queuedEvent)) { - map.delete(key); - } - } - - function replayUnblockedEvents() { - hasScheduledReplayAttempt = false; // First replay discrete events. - - while (queuedDiscreteEvents.length > 0) { - var nextDiscreteEvent = queuedDiscreteEvents[0]; - - if (nextDiscreteEvent.blockedOn !== null) { - // We're still blocked. - // Increase the priority of this boundary to unblock - // the next discrete event. - var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn); - - if (_fiber4 !== null) { - attemptUserBlockingHydration(_fiber4); - } - - break; - } - - var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.container, nextDiscreteEvent.nativeEvent); - - if (nextBlockedOn !== null) { - // We're still blocked. Try again later. - nextDiscreteEvent.blockedOn = nextBlockedOn; - } else { - // We've successfully replayed the first event. Let's try the next one. - queuedDiscreteEvents.shift(); - } - } // Next replay any continuous events. - - - if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) { - queuedFocus = null; - } - - if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) { - queuedDrag = null; - } - - if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) { - queuedMouse = null; - } - - queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap); - queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap); - } - - function scheduleCallbackIfUnblocked(queuedEvent, unblocked) { - if (queuedEvent.blockedOn === unblocked) { - queuedEvent.blockedOn = null; - - if (!hasScheduledReplayAttempt) { - hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are - // now unblocked. This first might not actually be unblocked yet. - // We could check it early to avoid scheduling an unnecessary callback. - - unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents); - } - } - } - - function retryIfBlockedOn(unblocked) { - // Mark anything that was blocked on this as no longer blocked - // and eligible for a replay. - if (queuedDiscreteEvents.length > 0) { - scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's - // worth it because we expect very few discrete events to queue up and once - // we are actually fully unblocked it will be fast to replay them. - - for (var i = 1; i < queuedDiscreteEvents.length; i++) { - var queuedEvent = queuedDiscreteEvents[i]; - - if (queuedEvent.blockedOn === unblocked) { - queuedEvent.blockedOn = null; - } - } - } - - if (queuedFocus !== null) { - scheduleCallbackIfUnblocked(queuedFocus, unblocked); - } - - if (queuedDrag !== null) { - scheduleCallbackIfUnblocked(queuedDrag, unblocked); - } - - if (queuedMouse !== null) { - scheduleCallbackIfUnblocked(queuedMouse, unblocked); - } - - var unblock = function (queuedEvent) { - return scheduleCallbackIfUnblocked(queuedEvent, unblocked); - }; - - queuedPointers.forEach(unblock); - queuedPointerCaptures.forEach(unblock); - - for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) { - var queuedTarget = queuedExplicitHydrationTargets[_i]; - - if (queuedTarget.blockedOn === unblocked) { - queuedTarget.blockedOn = null; - } - } - - while (queuedExplicitHydrationTargets.length > 0) { - var nextExplicitTarget = queuedExplicitHydrationTargets[0]; - - if (nextExplicitTarget.blockedOn !== null) { - // We're still blocked. - break; - } else { - attemptExplicitHydrationTarget(nextExplicitTarget); - - if (nextExplicitTarget.blockedOn === null) { - // We're unblocked. - queuedExplicitHydrationTargets.shift(); - } - } - } - } - - function addEventBubbleListener(element, eventType, listener) { - element.addEventListener(eventType, listener, false); - } - function addEventCaptureListener(element, eventType, listener) { - element.addEventListener(eventType, listener, true); - } - - // do it in two places, which duplicates logic - // and increases the bundle size, we do it all - // here once. If we remove or refactor the - // SimpleEventPlugin, we should also remove or - // update the below line. - - var simpleEventPluginEventTypes = {}; - var topLevelEventsToDispatchConfig = new Map(); - var eventPriorities = new Map(); // We store most of the events in this module in pairs of two strings so we can re-use - // the code required to apply the same logic for event prioritization and that of the - // SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code - // duplication (for which there would be quite a bit). For the events that are not needed - // for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an - // array of top level events. - // Lastly, we ignore prettier so we can keep the formatting sane. - // prettier-ignore - - var discreteEventPairsForSimpleEventPlugin = [TOP_BLUR, 'blur', TOP_CANCEL, 'cancel', TOP_CLICK, 'click', TOP_CLOSE, 'close', TOP_CONTEXT_MENU, 'contextMenu', TOP_COPY, 'copy', TOP_CUT, 'cut', TOP_AUX_CLICK, 'auxClick', TOP_DOUBLE_CLICK, 'doubleClick', TOP_DRAG_END, 'dragEnd', TOP_DRAG_START, 'dragStart', TOP_DROP, 'drop', TOP_FOCUS, 'focus', TOP_INPUT, 'input', TOP_INVALID, 'invalid', TOP_KEY_DOWN, 'keyDown', TOP_KEY_PRESS, 'keyPress', TOP_KEY_UP, 'keyUp', TOP_MOUSE_DOWN, 'mouseDown', TOP_MOUSE_UP, 'mouseUp', TOP_PASTE, 'paste', TOP_PAUSE, 'pause', TOP_PLAY, 'play', TOP_POINTER_CANCEL, 'pointerCancel', TOP_POINTER_DOWN, 'pointerDown', TOP_POINTER_UP, 'pointerUp', TOP_RATE_CHANGE, 'rateChange', TOP_RESET, 'reset', TOP_SEEKED, 'seeked', TOP_SUBMIT, 'submit', TOP_TOUCH_CANCEL, 'touchCancel', TOP_TOUCH_END, 'touchEnd', TOP_TOUCH_START, 'touchStart', TOP_VOLUME_CHANGE, 'volumeChange']; - var otherDiscreteEvents = [TOP_CHANGE, TOP_SELECTION_CHANGE, TOP_TEXT_INPUT, TOP_COMPOSITION_START, TOP_COMPOSITION_END, TOP_COMPOSITION_UPDATE]; // prettier-ignore - - var userBlockingPairsForSimpleEventPlugin = [TOP_DRAG, 'drag', TOP_DRAG_ENTER, 'dragEnter', TOP_DRAG_EXIT, 'dragExit', TOP_DRAG_LEAVE, 'dragLeave', TOP_DRAG_OVER, 'dragOver', TOP_MOUSE_MOVE, 'mouseMove', TOP_MOUSE_OUT, 'mouseOut', TOP_MOUSE_OVER, 'mouseOver', TOP_POINTER_MOVE, 'pointerMove', TOP_POINTER_OUT, 'pointerOut', TOP_POINTER_OVER, 'pointerOver', TOP_SCROLL, 'scroll', TOP_TOGGLE, 'toggle', TOP_TOUCH_MOVE, 'touchMove', TOP_WHEEL, 'wheel']; // prettier-ignore - - var continuousPairsForSimpleEventPlugin = [TOP_ABORT, 'abort', TOP_ANIMATION_END, 'animationEnd', TOP_ANIMATION_ITERATION, 'animationIteration', TOP_ANIMATION_START, 'animationStart', TOP_CAN_PLAY, 'canPlay', TOP_CAN_PLAY_THROUGH, 'canPlayThrough', TOP_DURATION_CHANGE, 'durationChange', TOP_EMPTIED, 'emptied', TOP_ENCRYPTED, 'encrypted', TOP_ENDED, 'ended', TOP_ERROR, 'error', TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', TOP_LOAD, 'load', TOP_LOADED_DATA, 'loadedData', TOP_LOADED_METADATA, 'loadedMetadata', TOP_LOAD_START, 'loadStart', TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', TOP_PLAYING, 'playing', TOP_PROGRESS, 'progress', TOP_SEEKING, 'seeking', TOP_STALLED, 'stalled', TOP_SUSPEND, 'suspend', TOP_TIME_UPDATE, 'timeUpdate', TOP_TRANSITION_END, 'transitionEnd', TOP_WAITING, 'waiting']; - /** - * Turns - * ['abort', ...] - * into - * eventTypes = { - * 'abort': { - * phasedRegistrationNames: { - * bubbled: 'onAbort', - * captured: 'onAbortCapture', - * }, - * dependencies: [TOP_ABORT], - * }, - * ... - * }; - * topLevelEventsToDispatchConfig = new Map([ - * [TOP_ABORT, { sameConfig }], - * ]); - */ - - function processSimpleEventPluginPairsByPriority(eventTypes, priority) { - // As the event types are in pairs of two, we need to iterate - // through in twos. The events are in pairs of two to save code - // and improve init perf of processing this array, as it will - // result in far fewer object allocations and property accesses - // if we only use three arrays to process all the categories of - // instead of tuples. - for (var i = 0; i < eventTypes.length; i += 2) { - var topEvent = eventTypes[i]; - var event = eventTypes[i + 1]; - var capitalizedEvent = event[0].toUpperCase() + event.slice(1); - var onEvent = 'on' + capitalizedEvent; - var config = { - phasedRegistrationNames: { - bubbled: onEvent, - captured: onEvent + 'Capture' - }, - dependencies: [topEvent], - eventPriority: priority - }; - eventPriorities.set(topEvent, priority); - topLevelEventsToDispatchConfig.set(topEvent, config); - simpleEventPluginEventTypes[event] = config; - } - } - - function processTopEventPairsByPriority(eventTypes, priority) { - for (var i = 0; i < eventTypes.length; i++) { - eventPriorities.set(eventTypes[i], priority); - } - } // SimpleEventPlugin - - - processSimpleEventPluginPairsByPriority(discreteEventPairsForSimpleEventPlugin, DiscreteEvent); - processSimpleEventPluginPairsByPriority(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent); - processSimpleEventPluginPairsByPriority(continuousPairsForSimpleEventPlugin, ContinuousEvent); // Not used by SimpleEventPlugin - - processTopEventPairsByPriority(otherDiscreteEvents, DiscreteEvent); - function getEventPriorityForPluginSystem(topLevelType) { - var priority = eventPriorities.get(topLevelType); // Default to a ContinuousEvent. Note: we might - // want to warn if we can't detect the priority - // for the event. - - return priority === undefined ? ContinuousEvent : priority; - } - - // Intentionally not named imports because Rollup would use dynamic dispatch for - var UserBlockingPriority = unstable_UserBlockingPriority, - runWithPriority = unstable_runWithPriority; // TODO: can we stop exporting these? - - var _enabled = true; - function setEnabled(enabled) { - _enabled = !!enabled; - } - function isEnabled() { - return _enabled; - } - function trapBubbledEvent(topLevelType, element) { - trapEventForPluginEventSystem(element, topLevelType, false); - } - function trapCapturedEvent(topLevelType, element) { - trapEventForPluginEventSystem(element, topLevelType, true); - } - - function trapEventForPluginEventSystem(container, topLevelType, capture) { - var listener; - - switch (getEventPriorityForPluginSystem(topLevelType)) { - case DiscreteEvent: - listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container); - break; - - case UserBlockingEvent: - listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container); - break; - - case ContinuousEvent: - default: - listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container); - break; - } - - var rawEventName = getRawEventName(topLevelType); - - if (capture) { - addEventCaptureListener(container, rawEventName, listener); - } else { - addEventBubbleListener(container, rawEventName, listener); - } - } - - function dispatchDiscreteEvent(topLevelType, eventSystemFlags, container, nativeEvent) { - flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp); - discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, container, nativeEvent); - } - - function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, container, nativeEvent) { - runWithPriority(UserBlockingPriority, dispatchEvent.bind(null, topLevelType, eventSystemFlags, container, nativeEvent)); - } - - function dispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) { - if (!_enabled) { - return; - } - - if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) { - // If we already have a queue of discrete events, and this is another discrete - // event, then we can't dispatch it regardless of its target, since they - // need to dispatch in order. - queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know. - topLevelType, eventSystemFlags, container, nativeEvent); - return; - } - - var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent); - - if (blockedOn === null) { - // We successfully dispatched this event. - clearIfContinuousEvent(topLevelType, nativeEvent); - return; - } - - if (isReplayableDiscreteEvent(topLevelType)) { - // This this to be replayed later once the target is available. - queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent); - return; - } - - if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent)) { - return; - } // We need to clear only if we didn't queue because - // queueing is accummulative. - - - clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target, - // in case the event system needs to trace it. - - { - dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null); - } - } // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked. - - function attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) { - // TODO: Warn if _enabled is false. - var nativeEventTarget = getEventTarget(nativeEvent); - var targetInst = getClosestInstanceFromNode(nativeEventTarget); - - if (targetInst !== null) { - var nearestMounted = getNearestMountedFiber(targetInst); - - if (nearestMounted === null) { - // This tree has been unmounted already. Dispatch without a target. - targetInst = null; - } else { - var tag = nearestMounted.tag; - - if (tag === SuspenseComponent) { - var instance = getSuspenseInstanceFromFiber(nearestMounted); - - if (instance !== null) { - // Queue the event to be replayed later. Abort dispatching since we - // don't want this event dispatched twice through the event system. - // TODO: If this is the first discrete event in the queue. Schedule an increased - // priority for this boundary. - return instance; - } // This shouldn't happen, something went wrong but to avoid blocking - // the whole system, dispatch the event without a target. - // TODO: Warn. - - - targetInst = null; - } else if (tag === HostRoot) { - var root = nearestMounted.stateNode; - - if (root.hydrate) { - // If this happens during a replay something went wrong and it might block - // the whole system. - return getContainerFromFiber(nearestMounted); - } - - targetInst = null; - } else if (nearestMounted !== targetInst) { - // If we get an event (ex: img onload) before committing that - // component's mount, ignore it for now (that is, treat it as if it was an - // event on a non-React tree). We might also consider queueing events and - // dispatching them after the mount. - targetInst = null; - } - } - } - - { - dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst); - } // We're not blocked on anything. - - - return null; - } - // List derived from Gecko source code: // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js var shorthandToLonghand = { @@ -4782,7 +2621,6 @@ function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) { { - if (!nextStyles) { return; } @@ -4810,7 +2648,7 @@ } } - // For HTML, certain tags should omit their close tag. We keep a whitelist for + // For HTML, certain tags should omit their close tag. We keep a list for // those special-case tags. var omittedCloseTags = { area: true, @@ -4838,11 +2676,6 @@ }, omittedCloseTags); var HTML = '__html'; - var ReactDebugCurrentFrame$3 = null; - - { - ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame; - } function assertValidProps(tag, props) { if (!props) { @@ -4853,7 +2686,7 @@ if (voidElementTags[tag]) { if (!(props.children == null && props.dangerouslySetInnerHTML == null)) { { - throw Error( tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ( ReactDebugCurrentFrame$3.getStackAddendum() ) ); + throw Error( tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." ); } } } @@ -4867,7 +2700,7 @@ if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) { { - throw Error( "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information." ); + throw Error( "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information." ); } } } @@ -4880,7 +2713,7 @@ if (!(props.style == null || typeof props.style === 'object')) { { - throw Error( "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + ( ReactDebugCurrentFrame$3.getStackAddendum() ) ); + throw Error( "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." ); } } } @@ -4892,7 +2725,7 @@ switch (tagName) { // These are reserved SVG and MathML elements. - // We don't mind this whitelist too much because we expect it to never grow. + // We don't mind this list too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': @@ -4910,7 +2743,7 @@ } } - // When adding attributes to the HTML or SVG whitelist, be sure to + // When adding attributes to the HTML or SVG allowed attribute list, be sure to // also add them to this module to ensure casing and incorrect name // warnings. var possibleStandardNames = { @@ -4960,9 +2793,11 @@ dir: 'dir', disabled: 'disabled', disablepictureinpicture: 'disablePictureInPicture', + disableremoteplayback: 'disableRemotePlayback', download: 'download', draggable: 'draggable', enctype: 'encType', + enterkeyhint: 'enterKeyHint', for: 'htmlFor', form: 'form', formmethod: 'formMethod', @@ -5530,9 +3365,9 @@ }).join(', '); if (invalidProps.length === 1) { - error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type); + error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } else if (invalidProps.length > 1) { - error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type); + error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } } } @@ -5574,7 +3409,7 @@ var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); - validateProperty$1 = function (tagName, name, value, canUseEventSystem) { + validateProperty$1 = function (tagName, name, value, eventRegistry) { if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { return true; } @@ -5589,8 +3424,11 @@ } // We can't rely on the event system being injected on the server. - if (canUseEventSystem) { - if (registrationNameModules.hasOwnProperty(name)) { + if (eventRegistry != null) { + var registrationNameDependencies = eventRegistry.registrationNameDependencies, + possibleRegistrationNames = eventRegistry.possibleRegistrationNames; + + if (registrationNameDependencies.hasOwnProperty(name)) { return true; } @@ -5710,12 +3548,12 @@ }; } - var warnUnknownProperties = function (type, props, canUseEventSystem) { + var warnUnknownProperties = function (type, props, eventRegistry) { { var unknownProps = []; for (var key in props) { - var isValid = validateProperty$1(type, key, props[key], canUseEventSystem); + var isValid = validateProperty$1(type, key, props[key], eventRegistry); if (!isValid) { unknownProps.push(key); @@ -5727,1052 +3565,3949 @@ }).join(', '); if (unknownProps.length === 1) { - error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type); + error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } else if (unknownProps.length > 1) { - error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type); + error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } } }; - function validateProperties$2(type, props, canUseEventSystem) { + function validateProperties$2(type, props, eventRegistry) { if (isCustomComponent(type, props)) { return; } - warnUnknownProperties(type, props, canUseEventSystem); + warnUnknownProperties(type, props, eventRegistry); } - var didWarnInvalidHydration = false; - var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML'; - var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning'; - var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning'; - var AUTOFOCUS = 'autoFocus'; - var CHILDREN = 'children'; - var STYLE = 'style'; - var HTML$1 = '__html'; - var HTML_NAMESPACE$1 = Namespaces.html; - var warnedUnknownTags; - var suppressHydrationWarning; - var validatePropertiesInDevelopment; - var warnForTextDifference; - var warnForPropDifference; - var warnForExtraAttributes; - var warnForInvalidEventListener; - var canDiffStyleForHydrationWarning; - var normalizeMarkupForTextOrAttribute; - var normalizeHTML; + var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1; + var IS_NON_DELEGATED = 1 << 1; + var IS_CAPTURE_PHASE = 1 << 2; + var IS_REPLAYED = 1 << 4; + // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when + // we call willDeferLaterForLegacyFBSupport, thus not bailing out + // will result in endless cycles like an infinite loop. + // We also don't want to defer during event replaying. - { - warnedUnknownTags = { - // Chrome is the only major browser not shipping